jQuery Ajax don't remember generated code? - ajax

I just started using Ajax with jQuery and PHP. I have a working code (below) which inserts some HTML code to a HTML container (div called nav sub).
Next time I try to run a similar code to the one below on my generated HTML, jQuery don't seem to find it. I guess it don't update it self about it when it's added.
$(".nav.top a").click(function(){
var a_class = $(this).parent().attr("class");
$(".nav.sub").html("loading...");
$(".nav.sub").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{button: a_class});
return false;
});
Let's say the generated code looks like this:
<div class="nav sub">
My new generated button, forgotten by jQuery?
</div>
And the new container looks like this:
<div class="settings"><?php # AJAX ?></div>
Is it some way to use jQuery and Ajax on HTML code generated with jQuery?

I figured it out. The solution is to use "live".
$('.nav.top a').live( 'click', function() {
var a_class = $(this).parent().attr("class");
$(".nav.sub").html("loading...");
$(".nav.sub").load("<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",{button: a_class});
return false;
});

Related

Ajax html response to div

Hi I am printing the ajax html response to div element and giving radio input option to select the file. after selecting the specific file the another div should show the message. but the ajax html response is not working
Jquery script:
$(document).ready(function()
{
$('#upload').ajaxForm({
beforeSubmit: function() {
$('#Analysis').show();
$('#Content_column').hide();
$('#file_list').show();
$('#trait').show();
$('#trait').html('Submitting...');
},
success: function(data) {
var $out = $('#file_list');
$out.html('&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFile list:');
$out.append('<div id="list">');
$('#list').html(data);
$out.append('</div>');
}
});
});
The output of this script is
<ul class="php-file-tree"><li class="pft-directory">Genotypic<ul><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/jquery.txt" />jquery.txt<br><input id="Penotypic" type="radio" name="uploads/Genotypic/" value="uploads/Genotypic/marker.csv" />marker.csv<br></ul></li><li class="pft-directory">Other</li><li class="pft-directory">Penotypic<ul><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/namPheno.csv" />namPheno.csv<br><input id="Penotypic" type="radio" name="uploads/Penotypic/" value="uploads/Penotypic/perl.pl" />perl.pl<br></ul></li></ul>
Jquery script:
$('#Penotypic').click(function() {
var $out1 = $('#trait');
$('#trait').show();
$out1.append('Submitted...');
});
this is not showing anything in the div trait. may be the html response is loading as a tesxt so the #Penotypic is not recognised. please help me to fix this.
Thanku
You have many inputs of id="Penotypic". Make every id unique or use classes as function trigger.
I wouldn't use "/" in the name attribute. See: http://www.w3.org/TR/html401/types.html#type-name
Then try if your ajax script does work. If it doesn't work, try if it works from static page (don't use your first jQuery script, but it's output as a static form). You probably need to bind your event trigger. Use jQuery's on().

Reloading everything but one div on a web page

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

How to manipulate the ajax response text

I've an ajax code like this:
var req = new XMLHttpRequest();
req.open('GET', 'http://www.example.org/', false);
req.send(null);
if(req.status == 200)
var response = http_attendance.responseText;
document.getElementById('divAttendance').innerHTML = response;
When I get result on the page, FF browser shows the DOM elements on 'divAttendance'. If I want to put put some jquery effect on the result, I can't be able to do it.
DOM elements is clearly viewed using firebug. But, when I generate the source code of that page then there is no repsonse text on 'divAttendance'. It is blank like thisL:
<html>
....
..
<div id="divAttendance"></div>
..
..
</html>
How to manipulate or put some effect on that result ???
Well, if you are using jQuery then you should be using jquery ajax anyways
http://api.jquery.com/jQuery.ajax/
Regardless, if you are populating your div with AJAX response then it will not show up using "View Source" rather you will have to use a tool like firebug.
Your div initially should look like following
<div id="divAttendance" style="display:none"></div>
and your javascript should have the following
.....
document.getElementById('divAttendance').innerHTML = response;
$("#divAttendance").show("slow");
For such operations jQuery load is easy and usefull function, have a look at
http://api.jquery.com/load/
Your specific example can be rewritten as
<html>
....
IMPORT JQUERY.JS
<script language="javascript">
$('#divAttendance').load('http://www.example.org/', function() {
$("#divAttendance").show("slow");
});
</script>
..
<div id="divAttendance" style="display:none"></div>
..
..
</html>

Using Jquery in Controller Page-ASP.NET MVC-3

Could any one give an example, how to use Jquery in Controller Page. MVC3 -ASP.NET(How To put various tags like )
I want to show a simple alert before rendering a view in Controller.
Thank you.
Hari Gillala
Normally scripts are part of the views. Controllers shouldn't be tied to javascript. So inside a view you use the <script> tag where you put javascript. So for example if you wanted to show an alert just before rendering a view you could put the following in the <head> section of this view:
<script type="text/javascript">
alert('simple alert');
</script>
As far as jQuery is concerned, it usually is used to manipulate the DOM so you would wrap all DOM manipulation functions in a document.ready (unless you include this script tag at the end, just before closing the <body>):
<script type="text/javascript">
$(function() {
// ... put your jQuery code here
});
</script>
If you are talking about rendering partial views with AJAX that's another matter. You could have a link on some page that is pointing to a controller action:
#Html.ActionLink("click me", "someAction", null, new { id = "mylink" })
and a div container somewhere on the page:
<div id="result"></div>
Now you could unobtrusively AJAXify this link and inject the resulting HTML into the div:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href, function() {
alert('AJAX request finished => displaying results in the div');
});
return false;
});
});

jquery ajax post callback - manipulation stops after the "third" call

EDIT: The problem is not related to Boxy, I've run into the same issue when I've used JQuery 's load method.
EDIT 2: When I take out link.remove() from inside the ajax callback and place it before ajax load, the problem is no more. Are there restrictions for manipulating elements inside an ajax callback function.
I am using JQuery with Boxy plugin.
When the 'Flag' link on the page is clicked, a Boxy modal pops-up and loads a form via ajax. When the user submits the form, the link (<a> tag) is removed and a new one is created from the ajax response. This mechanism works for, well, 3 times! After the 3rd, the callback function just does not remove/replace/append (tested several variations of manipulation) the element.
The only hint I have is that after the 3rd call, the parent of the link becomes non-selectable. However I can't make anything of this.
Sorry if this is a very trivial issue, I have no experience in client-side programming.
The relevant html is below:
<div class="flag-link">
<img class="flag-img" style="width: 16px; visibility: hidden;" src="/static/images/flag.png" alt=""/>
<a class="unflagged" href="/i/flag/showform/9/1/?next=/users/1/ozgurisil">Flag</a>
</div>
Here is the relevant js code:
$(document).ready(function() {
$('div.flag-link a.unflagged').live('click', function(e){
doFlag(e);
return false;
});
...
});
function doFlag(e) {
var link = $(e.target);
var url = link.attr('href');
Boxy.load(url, {title:'Inappropriate Content', unloadOnHide:true, cache:false, behaviours: function(r) {
$("#flag-form").live("submit", function(){
var post_url = $("#flag-form").attr('action');
boxy = Boxy.get(this);
boxy.hideAndUnload();
$.post(post_url, $("#flag-form").serialize(), function(data){
par = link.parent();
par.append(data);
alert (par.attr('class')); //BECOMES UNDEFINED AT THE 3RD CALL!!
par.children('img.flag-img').css('visibility', 'visible');
link.remove();
});
return false;
});
}});
}
Old and late reply, but.. I found this while googling for my answer, so.. :)
I think this is a problem with the "notmodified" error being thrown, because you return the same Ajax data.
It seems that this is happening even if the "ifModified" option is set to false (which is also the default).
Returning the same Ajax data three times will cause issues for me (jQuery 1.4). Making the data unique (just adding time/random number in the response) removes the problem.
I don't know if this is a browser (Firefox), jQuery or server (Apache) issue though..
I have had the same problem, I could not run javascript after I call boxy. So I put all my javascript code in afterShow:function one of boxy attributes. I can run almost except submit my form. My be my way can give you something.

Resources