I am using jquery mobile auto complete , Please see the demo at http://jsfiddle.net/Q8dBH/11/.
So whenever user press any letter,i need to show some message like "please wait."
So i added some code like below.But its showing only 1st time or 2nd time or not showing at all some times..How to show message whenever user types something until server responds back with data.
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
my full js is below.
$(document).on("pagecreate", ".ui-responsive-panel", function () {
$(document).on("click", "li", function () {
var text = $(this).text();
$(this).closest("ul").prev("form").find("input").val(text); });
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length >0) {
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then(function (response) {
$.each(response, function (i, val) {
html += "<li data-role='collapsible' data-iconpos='right' data-shadow='false' data-corners='false'><h2>Birds</h2>" + val + "</li>";
});
$ul.html(html);
//$ul.listview("refresh");
//$ul.trigger("updatelayout");
$('.ui-responsive-panel').enhanceWithin();
});
}
});
});
Working example: http://jsfiddle.net/Gajotres/Q8dBH/12/
Now this is a complex question. If you want to show jQuery Mobile AJAX loader there's one prerequisite, AJAX call must take longer then 50 ms (jQuery Mobile dynamic content enhancement process time will not get into account). It works in jsFiddle example but it may not work in some faster environment.
You can use this code:
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
beforeSend: function() {
// This callback function will trigger before data is sent
setTimeout(function(){
$.mobile.loading('show'); // This will show ajax spinner
}, 1);
},
complete: function() {
// This callback function will trigger on data sent/received complete
setTimeout(function(){
$.mobile.loading('hide'); // This will hide ajax spinner
}, 1);
$.mobile.loading('hide'); // This will hide ajax spinner
},
data: {
q: $input.val()
}
})
beforeSend callback will trigger AJAX loader and complete callback will hide it. Of course this will work only if AJAX call lasts more then 50ms. Plus setTimeout is here because jQuery Mobile AJAX loader don't work correctly when used with web-kit browsers, it is a triggering workaround.
Related
I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});
The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.
I have a simple jQuery function that resizes text areas, and I want it to apply to all text areas.
For the most part, this works great:
$(document.ready(function(){$("text_area").resizer('250px')});
However, because it is only called once when the document is ready, it fails to catch text areas that are later added onto the page using Ajax. I looked at the .live() function, which seems very close to what I'm looking. However, .live() must be bound to a specific event, whereas I just need this to fire once when they're done loading (the onLoad event doesn't work for individual elements).
The only thing I can get working is a really obtrusive inclusion of the JavaScript call directly into the Ajax. Is that the recommended way to be doing this?
Edit: Here is the rails source code for what it does for Ajax requests:
$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
var link = $(this);
if (!allowAction(link)) return false;
if (link.attr('data-remote') != undefined) {
handleRemote(link);
return false;
} else if (link.attr('data-method')) {
handleMethod(link);
return false;
}
});
// Submits "remote" forms and links with ajax
function handleRemote(element) {
var method, url, data,
dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
if (element.is('form')) {
method = element.attr('method');
url = element.attr('action');
data = element.serializeArray();
// memoized value from clicked submit button
var button = element.data('ujs:submit-button');
if (button) {
data.push(button);
element.data('ujs:submit-button', null);
}
} else {
method = element.attr('data-method');
url = element.attr('href');
data = null;
}
$.ajax({
url: url, type: method || 'GET', data: data, dataType: dataType,
// stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: function(xhr, settings) {
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
return fire(element, 'ajax:beforeSend', [xhr, settings]);
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
},
complete: function(xhr, status) {
element.trigger('ajax:complete', [xhr, status]);
},
error: function(xhr, status, error) {
element.trigger('ajax:error', [xhr, status, error]);
}
});
}
So in my particular case, I've got a link, that has data-remote set to true, which points to a location that will return JavaScript instructing a form containing a text area to be appended to my document.
A simple way to do this would be to use ajaxComplete, which is fired after every AJAX request:
$(document).ajaxComplete(function() {
$('textarea:not(.processed)').resizer('250px');
});
That says "every time an AJAX request completes, find all textarea elements that don't have the processed class (which seems to be added by the resizer plugin -- terrible name for its purpose!) and call the resizer plugin on them.
You may be able to optimise this further if we could see your AJAX call.
Generally speaking, I would do it this way..
$.ajax({
type : "GET",
url : "/loadstuff",
success: function(responseHtml) {
var div = $("#containerDiv").append(responseHtml);
$("textarea", div).resizer("250px");
}
});
Wondering if you could use .load for this. For example:
$('text_area').load(function() {
$("text_area").resizer('250px');
});
I want a basic spinner or processing animation while my AJAX POST is processing. I'm using JQuery and Python. I looked at the documentation but can't figure out exactly where to put the ajaxStart and ajaxStop functions.
Here is my js:
<script type="text/javascript">
$(function() {
$('.error').hide();
$("#checkin-button").click(function() {
var mid = $("input#mid").val();
var message = $("textarea#message").val();
var facebook = $('input#facebook').is(':checked');
var name = $("input#name").val();
var bgg_id = $("input#bgg-id").val();
var thumbnail = $("input#thumbnail").val();
var dataString = 'mid='+mid+'&message='+message+'&facebook='+facebook+'&name='+name+'&bgg_id='+bgg_id+'&thumbnail='+thumbnail;
$.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
success: function(badges) {
$('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
$('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
$.each(badges, function(i,badge) {
$('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='"+badge.image_url+"'><span class='badge-title'>"+badge.name+"</span></p>");
});
}
});
return false;
});
});
</script>
$.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
beforeSend: function () {
// ... your initialization code here (so show loader) ...
},
complete: function () {
// ... your finalization code here (hide loader) ...
},
success: function (badges) {
$('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
$('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
$.each(badges, function (i, badge) {
$('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
})
}
});
http://api.jquery.com/jQuery.ajax/:
Here are the callback hooks provided by $.ajax():
beforeSend callback is invoked; it receives the jqXHR object and the settings map as parameters.
error callbacks are invoked, in the order they are registered, if the request fails. They receive the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
dataFilter callback is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success.
success callbacks are then invoked, in the order they are registered, if the request succeeds. They receive the returned data, a string containing the success code, and the jqXHR object.
complete callbacks fire, in the order they are registered, when the request finishes, whether in failure or success. They receive the jqXHR object, as well as a string containing the success or error code.
Note the beforeSend and complete method additions to the code.
Hope that helps.
If you're using jQuery 1.5 you could do that nicely, unobtrusively and generically with a prefilter. Let's make a very simple plugin for this:
(function($) {
var animations = {};
$.ajaxPrefilter(function( options, _, jqXHR ) {
var animation = options.animation && animations[ options.animation ];
if ( animation ) {
animation.start();
jqXHR.then( animation.stop, animation.stop );
}
});
$.ajaxAnimation = function( name, object ) {
if ( object ) {
animations[ name ] = object;
}
return animations[ name ];
};
})( jQuery );
You install an animation as follows:
jQuery.ajaxAnimation( "spinner" , {
start: function() {
// code that starts the animation
}
stop: function() {
// code that stops the animation
}
} );
then, you specify the animation in your ajax options:
jQuery.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
animation: "spinner",
success: function() {
// your success code here
}
});
and the prefilter will ensure the "spinner" animation is started and stopped when needed.
Of course, that way, you can have alternative animations installed and select the one you need per request. You can even set a default animation for all requests using ajaxSetup:
jQuery.ajaxSetup({
animation: "spinner"
});
The best method I have found, assuming you are populating a present but empty field is to have a .loading class defined with background-image: url('images/loading.gif') in your CSS. You can then add and remove the loading class as necessary with jQuery.
you can set global ajax loading icon handler using here #ajxLoader takes your loading icon
$( document ).ajaxStart(function() {
$("#ajxLoader").fadeIn();
});
$( document ).ajaxComplete(function() {
$("#ajxLoader").fadeOut();
});
$(function() {
$('.error').hide();
$("#checkin-button").click(function() {
var mid = $("input#mid").val();
var message = $("textarea#message").val();
var facebook = $('input#facebook').is(':checked');
var name = $("input#name").val();
var bgg_id = $("input#bgg-id").val();
var thumbnail = $("input#thumbnail").val();
var dataString = 'mid=' + mid + '&message=' + message + '&facebook=' + facebook + '&name=' + name + '&bgg_id=' + bgg_id + '&thumbnail=' + thumbnail;
$.ajax({
type : "POST",
url : "/game-checkin",
data : dataString,
beforeSend : function() {
$('#preloader').addClass('active');
},
success : function(badges) {
$('#preloader').removeClass('active');
$('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
$('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
$.each(badges, function(i, badge) {
$('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
});
},
complete : function() {
$('#preloader').removeClass('active');
}
});
return false;
});
});
#preloader{
background: url(staticpreloader.gif);
}
.active {
background: url(activepreloader.gif);
}
I wrote a blog post about how to do this on a generic document level.
// prepare the form when the DOM is ready
$(document).ready(function() {
// Setup the ajax indicator
$('body').append('<div id="ajaxBusy"><p><img src="images/loading.gif"></p></div>');
$('#ajaxBusy').css({
display:"none",
margin:"0px",
paddingLeft:"0px",
paddingRight:"0px",
paddingTop:"0px",
paddingBottom:"0px",
position:"absolute",
right:"3px",
top:"3px",
width:"auto"
});
});
// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){
$('#ajaxBusy').show();
}).ajaxStop(function(){
$('#ajaxBusy').hide();
});
The AJAX process starts when you run the $.ajax() method, and it stops when the 'complete' callback is run. So, start your processing imagery/notification right before the $.ajax() line, and end it in the 'complete' callback.
ajaxStart and ajaxStop handlers can be added to any elements, and will be called whenever ajax requests start or stop (if there are concurrent instances, start only gets called on the first one, stop on the last to go). So, it's just a different way of doing global notification if you had, for example, a status spinner somewhere on the page that represents any and all activity.
Right now it contacts the server every time a user toggles "Comments (X)"
I'd like to make it so as soon as a user clicks ".info .reply" (Comments (X)), an ajax loader appears just until the data is finished loading, then the loader disappears.
// Replies - Toggle display of comments
$('.info .reply').click( function() {
$('.reply', this.parentNode.parentNode).toggle();
return false;
});
// Load comments
$('.info .reply', this).mousedown( function() {
var id = $('form #id', this.parentNode.parentNode).val();
$.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
success: function(data) {
for (var i in data) {
// Do AJAX Updates
}
}
});
return false;
});
What's the proper way to do this?
Thanks!
Basically
Show the image on mousedown using show() or fadeIn() or whatever tickles your fancy, then hide it inside your success callback. Like this
$('.info .reply', this).mousedown( function() {
$("#loading-image").show(); // Show the progress indicator
var id = $('form #id', this.parentNode.parentNode).val();
$.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
success: function(data) {
$("#loading-image").hide(); // Hide the progress indicator
for (var i in data) {
// Do AJAX Updates
}
}
});
return false;
});
You can use a plugin such as jQuery BlockUI to do this. Just call $.blockUI() before calling $.ajax. Then at the end of the success event, call $.unblockUI().