I want to append first, then run ajax to update the data and then do the search. See the code below. I want to put a code like if append, then run $.post. How can I do that in jquery, thanks?
$('<span />', { class: 'result_tag', text: href }).insertBefore($input);
$('.result_tag').append(' ');
//make sure append first and then run .post
$.post("member_search.php", {
search_text: $(".result_tag").text()
}).done(function()
{
$.post("member_search.php", {
search_text: $(".result_tag").text()
},
function(data){
$("#find_members").html(data);
});
});
The $.post() function returns a promise. You can call the done() function on this promise. The done() function takes a callback function which will be executed after the post to the server is done:
$.post("update.inc.php", {
tag : $(this).closest("a").text(),
users_id : $("#users_id").val()
}).done(function(){
// your second post goes here
});
You can use $.ajax and its Event beforeSend like this:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
data: 'search_text='+$(".result_tag").text(),
beforeSend: function( xhr ) {
$('.result_tag').append(' ');
}
})
.done(function( data ) {
//now do your other ajax things
});
Hope this will help you.
More Details are given in jQuery DOC
Related
I'm searching a solution for this:
I have a function that updates the content of a table in my application.
function prev_update(cli_id){
$("#list").empty();
$("#list").append("<tr><td colspan=11><img src='images/loading.gif' alt=loading title=loading /></td></tr>");
$.ajax({
type : 'POST',
url : 'json/get.php?t=2&id='+cli_id,
dataType : 'json',
encode : true
})
.done(function(data) {
$("#list").empty();
if ((data)["prev_list"]) {
$.each((data)["prev_list"], function( i, val ) {
$( "#list" ).append(val);
});
$("#edit").hide("slow");
} else {
$("#list").append("<tr><td colspan=11> </td></tr>");
}
});
};
In another function I'm updating a row of a table, when I finish to edit the content of a row of the table i launch a similar function but in the .done row I call the prev_update function and AFTER this is finished I have to push a button in the updated table content, for review the modifications...
Here's the code:
$("#prev_mod").on("click",(function( event ) {
$('#loading_img').css('display','inline');
header_print();
$.ajax({
type : 'POST',
url : 'json/post.php?mod='+$('#prev_id').val(),
data : $("#form_sog").serialize(),
dataType : 'json',
encode : true
})
.done(function(data) {
if ((data)["success"]===false) {
$('#form_edit').hide('slow');
prev_update();
$('#edit_'+$('#prev_id').val()).click();
});
});
}));
I have to wait when prev_update() function ends then click the button because the button is in the table that is updating.
I tried to use also deferred object but it doesn't works (maybe for my error).
I can't edit the function prev_update because it's used by other functions.
Instead of .done you can use .then to organize your code. This is because .then can be chained
Not tested but it can be like this
function prev_update(cli_id){
$("#list").empty();
$("#list").append("<tr><td colspan=11><img src='images/loading.gif' alt=loading title=loading /></td></tr>");
$.ajax({
type : 'POST',
url : 'json/get.php?t=2&id='+cli_id,
dataType : 'json',
encode : true
})
.then(function(data) {
$("#list").empty();
// rest of code
}).then(function(data) {
if ((data)["success"]===false) {
// rest of code
};
});
If you want to know when everything inside of prev_update() is done, you HAVE to modify it to keep track of the async operations in it and to return a promise. Then, the caller can use that returned promise to know when things are done.
So, inside of prev_update(), the two async operations are the ajax call and the .hide() animation. The hide animation occurs inside of the completion handler for the ajax operation. So, if you change .done() to .then(), we can chain together these promises and return a single promise that will tell the caller when everything is done.
jQuery has a .promise() method that will get us a promise that is linked to any jQuery animation so if we just get the promise for the animation, we can return it and it will chain to the parent promise. If there was no animation, then we can just return nothing and the promise chain will continue.
This does not change the functionality of prev_update() at all - it just returns a promise that tracks its completion (when you were previously not returning anything).
That can work like this:
function prev_update(cli_id){
$("#list").empty();
$("#list").append("<tr><td colspan=11><img src='images/loading.gif' alt=loading title=loading /></td></tr>");
return $.ajax({
type : 'POST',
url : 'json/get.php?t=2&id='+cli_id,
dataType : 'json',
encode : true
}).then(function(data) {
var p;
$("#list").empty();
if ((data)["prev_list"]) {
$.each((data)["prev_list"], function( i, val ) {
$( "#list" ).append(val);
});
p = $("#edit").hide("slow").promise();
} else {
$("#list").append("<tr><td colspan=11> </td></tr>");
}
// return promise if there was one
return p;
});
};
So, then you can use this in your other code like this:
$("#prev_mod").on("click",(function( event ) {
$('#loading_img').css('display','inline');
header_print();
$.ajax({
type : 'POST',
url : 'json/post.php?mod='+$('#prev_id').val(),
data : $("#form_sog").serialize(),
dataType : 'json',
encode : true
}).then(function(data) {
if ((data)["success"]===false) {
$('#form_edit').hide('slow');
prev_update().then(function() {
// apply click when everything in prev_update() is done
$('#edit_'+$('#prev_id').val()).click();
});
});
});
}));
Im using the following function to call an ajax request, and fill certain corresponding divs with the response:
$( function() {
$(document).ready(function() {
var postData = "";
$.ajax( {
url : \'functions/ajax_api.php?\',
type : \'post\',
data : postData,
success : function( resp ) {
$(\'#id1\').html($(\'#id1\' , resp).html());
$(\'#id2\').html($(\'#id2\' , resp).html());
}
});
return false;
});
});
The function works fine. My question is how can I call it automatically every few seconds?
I tried using window.setTimeout(function, 3000) but I couldnt set it up correctly.
use setInterval(); instead of .setTimeout()
Let me help you a little bit with that
var interval , setItinterval; // just a variables you can change names
interval = function(){
// ajax code here
}
to run it .. use:
setItinterval = setInterval(interval , 3000);
to stop it .. use
clearInterval(setItinterval);
Make sure to read setInterval for more information.
For Complete answer and Last thing I want to say when using setInterval(); Its better to use visibilitychange to avoid server error , server load or something like that
document.addEventListener('visibilitychange',function(){
if(document.visibilityState == 'visible'){
// user view the page
}else{
// user not see the page
}
});
You can use setTimeout() or setInterval, but setInterval may result in multiple simultaneous ajax calls if those calls take too long to respond. That isn't a problem if you call setTimeout() in the ajax success callback.
To use setTimeout(), first wrap your ajax call in a function. You can then add a call to setTimeout() to the ajax success callback. You also need to call the function once to start of the looping.
$(function() {
function postData() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?',
type: 'post',
data: postData,
success: function(resp) {
$('#id1').html($('#id1', resp).html());
$('#id2').html($('#id2', resp).html());
// Call postData again after 5 seconds.
setTimeout(function() { postData(); }, 5000);
}
});
}
// Call postDate the first time to start it off.
postData();
});
Note: With the call to setTimeout in the success callback, the cycle will break if an ajax call fails. You may want that, but if you want it to act more like setInterval, you can place the call to setTimeout in the complete callback.
Here's some example code that will do it (note that it runs the function when the document loads, and then starts the interval). You can always use clearInterval(refresh_interval) if you need to stop it.
var refresh_interval;
function update_content() {
$.ajax({
url : \'functions/ajax_api.php?\',
type : \'post\',
data : postData,
success : function( resp ) {
$(\'#id1\').html($(\'#id1\' , resp).html());
$(\'#id2\').html($(\'#id2\' , resp).html());
}
});
}
$(document).ready(function() {
update_content();
setInterval(update_content, 3000);
}
The relevant documentation for using intervals is here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
Though you may want to look into Server Sent Events, it's probably a better solution for what you want.
I am having some trouble with the timing of javascript events. The problem I am having is that one part of the code seems to be executing before another part of the code completes. I need to ensure that the first code finishes before the latter code begins. Here is the initial code:
function(){
myLoop(); //this needs to complete before the call to myMethod below
$.ajax({
url: sURL + "myController/myMethod",
success: function() {
$.msg("My Success Message",{live:10000});
error: function(){
$.msg("My Error Message",{live:10000});
});
}
And here is the code that loops and inserts records into a db:
function myLoop(){
$('input[name=c_maybe].c_box').each(function(){
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
success: function(data) {
//not sure what to do on success.
}
});
}
});
}
The problem that seems to be happening is that the call to myController\myMethod is happening before myLoop completes inserting all the records into the database.
Can someone suggest a way for me to redesign this code so that I can ensure that myController\myMethod is not called until myLoop has completely finished?
Thanks.
function myLoop() {
var jqxhrs = [];
if( $(this).prop('checked') ){
var rn = $(this).prop('value');
jqxhrs.push($.ajax({...
}
return jqxhrs;
}
function () {
$.when.apply(undefined, myLoop()).done(function () {
$.ajax({
url: sURL + "myController/myMethod",
...
});
}
$.when.apply is used to call $.when on the array of ajax requests, so .done is not called until they are all complete.
You can use the $.when function that has been added to jQuery.
It goes something like this:
$.when(ajaxFunction1(), ajaxFunction1()).done(function(response1, response2){
// when the function calls are done this code here will be executed -> the response will be passed as parameters corresponding to the functions -> response1, response2
});
Or you can try to use "beforeSend" within the ajax function:
$.ajax({
beforeSend: function(){
alert("doing stuff before the ajax call ...");
},
success: function(){
alert("Whoa!");
}
});
You can make the ajax call synchronous. That way, the execution will be blocked till ajax call returns:
$.ajax({
url: sURL + 'myController/myInsert',
type:"POST",
dataType: 'text',
data: {'rn': rn},
async: false,
success: function(data) {
//not sure what to do on success.
}
});
I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page.
So jQuery ajax() function have an timeout variable. But i want to use getJSON function. And i think that i can use ajaxStart() and ajaxStop() functions. But how?
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
setTimeout("throw '';",15000) //i used this but didn't work
setTimeout("return;",15000) //i used this but didn't work
setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events)
})
.ajaxStop(function() {
$(this).fadeOut();
});
getJSON() returns a promise on which you can call the abort function :
var p = $.getJSON(..., function(){ alert('success');});
setTimeout(function(){ p.abort(); }, 2000);
EDIT : but if your goal is just to abort if it takes too much time, then lethal-guitar's answer is better.
getJSON() is just a shorthand for the following:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So you could use $.ajax() and specify the timeout option as desired. See also: http://api.jquery.com/jQuery.getJSON/
As lethal-guitar mentioned getJSON() function is just an shorthand for $.ajax(). If you want to detect if a timeout has occurred rather than an actual error use the code below.
var request = $.ajax({
dataType: "json",
url: url,
data: data,
success: function( ) { },
timeout: 2000
}).fail( function( xhr, status ) {
if( status == "timeout" ) {
// do stuff in case of timeout
}
});
There's always the nuclear route as well:
//Set AJAX timeout to 10 seconds
$.ajaxSetup({
timeout: 10*1000
});
This will set all the AJAX requests your program makes (even via $.getJSON) to have a time out of 10 seconds (or what have you).
the setTimeout function executes a set of code after a specified number of milisecons in the global scope.
The getJSON function (per the jQuery documentation here http://api.jquery.com/jQuery.getJSON/) is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
so you would want to make your call like so:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success,
timeout: 15000
});
$('.loadingDiv')
.hide()
.ajaxStart(function() {
$(this).fadeIn();
})
.ajaxStop(function() {
$(this).fadeOut();
});
I don't think any of these answers are ideal. I know this is years late, but what you want to do is use the success/error callback options of the .ajax(); method when receiving a JSONP response.
Example of how I would structure this:
// Call
$.ajax({
// URL you want to get
url: 'http://example.com/json?callback=?',
// Set a realistic time in milliseconds
timeout: 3000,
// Put in success callback function here, this example
// shows you the data you got back from the call
success: function(data) {
console.log(data);
},
// Put in an error handling function, just an alert in this case
error: function(badData) {
alert('The call was unsuccessful');
},
type: 'POST'
});
I'm having an issue with my update button and jquery ajax. Right now when I click on my update button, it saves whatever updated data to the database. My goal is I want to slide up a message if the update is successful. I was looking at ajax post and using the success event seems like it would work but I dont know how to incorporte it. How would I do this? Would it be something like this?
$(document).ready(function(){
$('#divSuccess').hide();
$('#btnUpdate').click( function() {
alert('button click');
$.ajax({
url: "test.aspx",
context: document.body,
success: function(){
$('#divSuccess').show("slide", { direction: "down" }, 3000);
$('#divSuccess').hide("slide", { direction: "down"}, 5000);
}
});
});
});
check out this question for an example on how to handle the success event. Hope this helps!
$("#targetDiv").load("page.php",$("#form").serializeArray(),function (response)
{
if (response == '0' && response != '')
alert('Request not sent to server !\n');
else if(response == '-1')
alert('Please write some more !\n');
else
{
alert("success! ");
}
}
);
i've echo ed 0 and -1 for failure and other for success
In the jquery post function, you can execute some callback function.
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc...
this; // the options for this ajax request
// textStatus can be one of:
// "timeout"
// "error"
// "notmodified"
// "success"
// "parsererror"
// NOTE: Apparently, only "success" is returned when you make
// an Ajax call in this way. Other errors silently fail.
// See above note about using $.ajax.
}
http://docs.jquery.com/Post
With at least jQuery 1.5, you've got deferred objects and new syntax for AJAX events (including success).
var $ajaxcall = $.ajax({
url : 'myurl.svc/somemethod',
data : '{ somedata : "sometext" }'
});
$ajaxcall.success(function() {
// do something on successful AJAX completion
});
Of course you can chain that as well, and call something along the lines of $.ajax().success() or something.
Just wrote a blog post on it myself, if you're interested in reading more.