I got a doubt regarding the way of execution of functions having ajax calls in jQuery.
Consider two functions.
function auth() {
$.ajax({
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
function getData() {
$.ajax({
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
and i call these functions one after other as show below...
auth();
getData();
My situation is, I want to execute the getData() only after completing 'auth()' .I know we can call the getData() inside the success function of auth. But what i want to know is, how these functions will be executed if i call the one after another, like i shown above.
Any kind of help would be appreciated :)
Thanks.
You can use deferred objects in jQuery. Simply return the ajax() result.
function auth() {
return $.ajax({
type: "POST",
dataType : "json",
url: API_URL,
data: { .... },
success: function (response) {
}
});
};
auth.done(getData);
This will call getData when auth is complete.
They will execute Asynchronously. You can make them wait (Synchronous), if that is what you want, by setting "async=false" in the call.
function auth() {
$.ajax({
**async: false,**
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
function getData() {
$.ajax({
**aysnc: false,**
type: "POST",
dataType: "json",
url: API_URL,
data: {....
},
success: function (response) {}
});
};
This will make the call finish before moving on to the next call, BUT will lock the browser usually when making the calls:
async (default: true)
Type: Boolean By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Src JQM Site: http://api.jquery.com/jQuery.ajax/
Related
On Chrome its working properly but on firefox its not working
function myfoo(){
// Write your logic here
$.ajax({
type: "POST",
url: "update.php",
dataType: 'json',
data: {Eventid: 'Eventid',Seats:'Seats'},
success: function (r) {}
});
}
When unloading window
$(window).on('beforeunload', function () {
return 'Are you sure you want to leave?';
});
when unloading call function
$(window).on('unload', function () {
console.log('calling ajax');
myfoo();
});
Both "onbeforeunload" and "unload" is working but in your scenario you are expecting to send ajax call. so try changing ajax asynchronous to false.
function myfoo(){
// Write your logic here
$.ajax({
type: "POST",
url: "update.php",
dataType: 'json',
async: false,
data: {Eventid: 'Eventid',Seats:'Seats'},
success: function (r) {}
});
}
I have an AJAX request which gets data from the database and then populates the page with the data collected. The problem I am having is that currently the ajax request is in a setInterval which is being called every second.
setInterval(function () {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}, 1000);
This is fetching the data every second which is a huge strain on the server as it's making a request and then I am calling it again even when the data hasn't come through first time.
Is there a way that I can call the same AJAX request over and over but only after it's finished fetching the data first time and not keep going up?
There are better architectures to accomplish this type of scenario (websockets as mentioned in the comments would be one example), but to do strictly what you're asking, sure! Wrap it in a function that calls itself:
function getData(){
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
getData();
}
});
}
Replace the setInterval with a setTimeout only once you're done:
function fetchAjax() {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
setTimeout(fetchAjax, 1000);
}
});
};
Add a variable to distunguish if ajax call is already underway. If it is, don't do anything. If not, go ahead.
var isAjaxInProgress = false;
setInterval(function () {
if (!isAjaxInProgress){
isAjaxInProgress = true;
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
isAjaxInProgress = false;
}
});
}
}, 1000);
I have an ajax function call that has a variable sum with value as 5. But when I try to access this variable outside the ajax function call, am getting null value.
Is there any way to access the value outside the ajax function?
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
success: function(data) {
var mydata = 5;
}
});
alert(mydata);
Try this:
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
success: function(data) {
doGetMyData(data);
}
});
function doGetMyData(data){
alert(data);
}
The first "A" in AJAX means Asynchronous, so your code runs the alert before the request completes. To achieve the goals you want, you may try to make your request synchronous adding the async:false option to your query:
$.ajax({
type: "POST",
url: "Service.asmx/chart",
data: appid,
async:false,
success: function(data) {
doGetMyData(data);
}
});
function doGetMyData(data){
alert(data);
}
The bad news is synchronous request locks your browser until it's finish, it's a good pratice to avoid this.
I'm not clear if my response to a JSONP call needs to have the callback reference in the response. For example, the following AJAX call:
$.ajax({
type: 'GET',
url: ajaxurl ,
async: false,
dataType: "jsonp",
jsonpCallback: "do_teacher_survey_callback",
data: {action: 'test'},
success: function (result) {
},
error: function (request,error) {
}
});
Does the response need to look like the following:
do_teacher_survey_callback({"field":"data"})
Or can I just return pure JSON like this:
{"field":"data"}
I'm confused because I have used JSONP before to resolve cross-domain calls to servers that I had no control over the response and it worked fine.
Hello guys i have the next ajax call for login. I serialize the form and send the data to server and return redirect url link. My problem is that my url after post is like
http://localhost:50802/?username=&password= and not http://localhost:50802/Home
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
alert(result.link);
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
It looks like you wrote this $.ajax call in the .click event of a submit button or in the .submit event of a form without canceling the default action by returning false from the callback or by calling preventDefault on the argument. Here's how your code should look like:
$('#id_of_your_form').submit(function(e) {
e.preventdefault(); // <-- That's what I am talking about and what you forgot
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
});
Also async: false,????? You know what this does, do you? That's not AJAX. That's a blocking synchronous call to your webserver during which the client browser would be frozen like during the Ice Age 2 ruining all user experience.
Try returning false at the end of your submit function
$('#id_of_your_form').submit(function(e) {
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
return false; });
Another option would of course be to return the correct redirectlink from the controller instead of overriding it in the java script.