Return false not working for jQuery live - ajax

Well this has me well and truly stumped. After searching for the last few hours I still cannot seem to work out where I am going wrong.
I am trying to append an AJAX response to a container when it gets clicked. That works fine but I don't want it to append another object when the elements from the AJAX response also gets clicked.... so:
<div id="container">
<!-- AJAX response to get inserted here, for example -->
<span id="ajaxResponse"></span>
</div>
Here is my script:
$('#container').click(function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
So it works fine but for some reason the click event on #container also fires when I click on the AJAX response span!?
According to jQuery documentation:
To stop further handlers from
executing after one bound using
.live(), the handler must return
false. Calling .stopPropagation() will
not accomplish this.
But unless I am mistaken, I am calling false? :(
Anyone help me out on this?
UPDATED:
So the only way I can get it to work is by updating my code to this:
$('#container').live('click', function() {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
});
$('#ajaxResponse').live('click', function(e) {
return false;
});
This seems a little messy though... anyone have a better solution?

Where is live part you mention in the title of the question ?
It is how the event model works.. If you click on element which does not handle the event, the event will travel up the DOM hierarchy until it finds an element that handles the click (and stops its propagation..). Otherwise you would not be able to put an image inside a <a> tag and click on it..
You can bind a canceling handler on the inner element assuming you have someway to target it..
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
// assuming the returned data from ajax are wrapped in tags
$(current_el).children().click(function(){ return false;});
}
});

I think the return false is referring to something else in this case...
you should try calling stopPropagation() - this should stop the "click" function from propagating down to the ajaxResponse span....

One option that you may want to try is switching over to using live(). Essentially, the click event you setup is calling bind(), and the solution you referenced is using live() which is a variation on bind().
For example:
$('#container').live("click", function(e) {
var current_el = $(this).get(0);
$.ajax({
url: 'text.html',
success: function(data) {
$(current_el).append(data);
}
});
return false;
});
HTH

Related

Jquery inside Ajax loaded page does not work

When I use
$('body').html(data1)
or
$('html').html(data1)
in AJAX, then any HTML tag or jQuery function does not work on the loaded page.
$.ajax({
type:"GET",
dataType: 'html',
url: 'hell.php',
success : function(data1) {
alert(data1);// will alert "ok"
$('body').html(data1);
},
});
The events you attached before $('body').html(data1) will not fire simply because the elements previously in the body will not exist anymore.
You have to re-attach the events or use .on() method and attach events directly to document.
better use jQuery live function, when attaching event handlers.
See: http://api.jquery.com/live/
First, define the functionality you want to attach to the loaded elements in a function, e.g.:
function attachEventsAfterAjax(){
$('.aLoadedElement').on('click', function(){
console.log('Yay!');
return false;
});
}
Then, after you've loaded your new content, call that function, e.g.:
$.ajax({
[...],
success: function(data){
// Don't replace the <body> HTML, that's not a good idea
// $('body').html(data);
$('#container').html(data);
// Now attach the functionality!
attachEventsAfterAjax();
}
});

reload page when clicking on current page link, using jQuery Address plugin

I am using jQuery Address plugin, and all my ajax navigation is based on it, and more precisely on internalChange or externalChange events like that
$(document).ready(function() {
initDeepLinking();
});
function linkClicked(e){
var request = $.ajax({
url: e.path,
data: e.queryString,
type: "GET",
dataType: "json",
});
request.done(handleResponse);
return false;
}
function handleResponse(response, textStatus, jqXHR){
$('#main').html(response.responseText);
};
function initDeepLinking(){
$.address.internalChange(function(event){
linkClicked(event);
});
$.address.externalChange(function(event){
linkClicked(event);
});
}
so when i click on a link leading to the current page, nothing happens.
I would like the page to reload when I do that. Any simple options ?
Thanks !
I am having troubles understanding what your question really is:
you don't know how to attach a handler to the link
you don't know what statement can be used to refresh the current page
In order to set a handler you can use some selector. For example, getting the element by class. More about jquery selectors here.
After you have the element, you can attach an event handler for the 'on click' event and do something like this:
window.location.reload(true);

jQuery Mobile transitions and AJAX Polling on a MasterPage

I am trying to use AJAX polling with jQuery to update a span element on a razor MasterPage in ASP.NET MVC3. The page uses the jQuery Mobile 1.0 framework that adorns simple view changes (like navigating from /home to /about) with some sort of "transition" animation.
This is the Javascript code that does the polling, while the "unreadBubble" span is located in the body - both are defined in the MasterPage!
<script type="text/javascript">
$(document).bind("pageinit", function poll() {
setTimeout(function () {
$.ajax({ url: "/Notification/GetUnreadNotificationsCount",
dataType: "json",
success: function (data) {
$('#unreadBubble').text(data.UnreadCount);
poll();
}
});
}, 1000);
});
So, imagine I have a HomeController and a NotificationController that both use the MasterPage and provide an Index view. The AJAX polling works on both views and updates the span every second as expected. As soon as I navigate from one view to another though, the span gets re-initialized with its default value from the MasterPage (empty) and doesn't update anymore. Interestingly the async GetUnreadNotificationsCount method is still called on the NotificationsController repeatedly - the span just doesn't update. I also tried to alert the span tag in JS and it wasn't null or something.
According to the documentation, jQuery Mobile also loads new pages with AJAX to insert this fancy "SWOOSH" transition animation. This seems to somehow disturb the JS/DOM initialization.
Do you have any idea how to resolve this? Should I bind to another event or can I somehow force the span tag to update?
Solution: It was a caching problem! The following did the trick:
Add class="command-no-cache" to your page div add the following JavaScript to the MasterPage:
$(":jqmData(role=page)").live('pagehide', function (event, ui) {
if ($(this).children("div[data-role*='content']").is(".command-no-cache"))
$(this).remove();
});
I would use the pagebeforeshow to actually bind the event, and pagehide to remove the event.
Did you try that instead of initializing only once in the pageinit event?
UPDATE: some code for example,
<script type="text/javascript">
var timer = null;
$(":jqmData(role=page)").bind("pagebeforeshow", function() {
timer = setTimeout(function() {
$.ajax({ url: "/Notification/GetUnreadNotificationsCount",
dataType: "json",
success: function (data) {
$('#unreadBubble').text(data.UnreadCount);
}
});
}, 1000);
});
$(":jqmData(role=page)").bind("pagehide", function() {
if (timer != null){
clearTimeout(timer);
timer = null;
}
});
</script>
Also corrected some other ""mistypes" along the way, have a look and compare to your code!
Hope this helps

mootools inline Ajax call not working

I am trying to use mootools ajax requests to record clicks on outgoing links. So far here is what I'm doing.
Each link looks like follows:
<div id="1">
StackOverflow
</div>
The javascript function clickRecord(id) is defined as follows:
function clickRecord(id){
var u = "record.php";
var req = new Request({
method: 'post',
url: u,
data:{'id':id},
onComplete:function(response){
}
}).send();
}
The problem I have is this. If I add a return false; to the onclick="" declaration, everything works fine, of course the problem there is that click does not take the user to the intended page. If I do not have the return false; then it seems like the ajax call is never executed.
I thought the onclick event should execute first and then only the default action should execute. Is this not the case?
There is an even stranger scenario if you use onmousedown event instead. It seems like on Firefox, if you use the onmousedown event, once you go to the new page, you cant simply navigate back to the old page, you have to refresh the old page. Else the call is not executed. This does not happen on IE.
Don't use onclick - very 1995.
Instead attach an event to the element and use event.stop(), ie:
StackOverflow
JS:
document.getElements('a').addEvents({
click: function(event) {
event.stop();
var u = 'record.php';
var req = new Request({
method: 'post',
url: u,
data: {
'id': this.get('data-id');
},
onComplete: function(response) {}
}).send();
}
});
Btw. <div id="1"> this is not valid in HTML, an ID'd needs to start with a letter.
OK. Found an answer to one of the questions:
The inline mootools request did not execute when declared through the onclick().
It seems this was caused by the script not being synchronous. So probably it returns without actually fully committing the request, and the browser then moves to another page breaking the execution. Adding a synchronous call to the script fixes the problem:
function clickRecord(id){
var u = "record.php";
var req = new Request({
async:false,
method: 'post',
url: u,
data:{'id':id},
onComplete:function(response){
}
}).send();
}
The second problem that was mentioned on the onmousedownevent, i.e. firefox not executing the ajax call if the browser navigates back is still unsolved. However I am leaving that to be as that wasn't the main question raised.

JQM (jQueryMobile) problem with AJAX content listview('refresh') not working

This is a mock of what I'm doing:
function loadPage(pn) {
$('#'+pn).live('pagecreate',function(event, ui){
$('#'+pn+'-submit').click( function() {
$.mobile.changePage({
url: 'page.php?parm=value',
type: 'post',
data: $('form#'+pn+'_form')
},'slide',false,false);
loadAjaxPages(pn);
});
});
function loadAjaxPages(page) {
// this returns the page I want, all is working
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data); // removed .page(), causing page to transition, but if I use .page() I can see the desired listview
}
});
}
in the ajax call return if I add the .page() (which worked in the past but I had it out side of the page function, changing the logic on how I load pages to save on loading times), make the page transition to the next page but I can see the listview is styled the way I want:
$('#display_'+page+'_page').html(data).page();
Removing .page() fixes the transition error but now the page does not style. I have tried listview('refresh') and even listview('refresh',true) but no luck.
Any thoughts on how I can get the listview to refresh?
Solution:
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data);
$("div#name ul").listview(); // add div wrapper w/ name attr to use the refresh
}
});
Be sure to call .listview on the ul element
If it didn't style earlier, you just call .listview(), bot the refresh function. If your firebug setup is correct, you should have seen an error message telling you that.
I didn't have time to get down to creating some code before you posted your fix, but here's a little recommendation from me:
if(data !== null){ $('#display_'+page+'_page').html(data).find("ul").listview() }
This is a bit nicer than a new global selector. Also - you don't need the div and you can provide a detailed selector if you have multiple ULs.
caution: the above code requires data !== null. If it's null - it will throw an error.
If you add items to a listview, you'll need to call the refresh() method on it to update the styles and create any nested lists that are added. For example:
$('#mylist').listview('refresh');
Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons. Any list items already enhanced will be ignored by the refresh process. This means that if you change the contents or attributes on an already enhanced list item, these won't be reflected. If you want a list item to be updated, replace it with fresh markup before calling refresh.
more info here.

Resources