How to retrieve variable values outside ajax call? - ajax

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.

Related

Weird object returned from AJAX request

I have this method:
var chineseCurrency = getChinese();
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
});
}
That is what printed when console.log(chineseCurrency);:
I am not able to make chineseCurrency equal to "price", so it would be "6.80071377". How can I do that? Tried chineseCurrency.responseText, nope, chineseCurrency['responseText'], nope. Tried to JSON.parse(chineseCurrency), nope. Nothing works!
Sorry if repeated, couldn't find any answer at Stackoverflow.
How do I return the response from an asynchronous call?
Data that is received as response to asynchronous ajax call cannot be returned from the function that calls $.ajax. What you are returning is XMLHttpRequest object (see http://api.jquery.com/jquery.ajax/) that is far from the desired data.
var chineseCurrency = null;
function getChinese(){
return $.ajax({
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny",
success: function(data) {
alert("success1: chineseCurrency=" + chineseCurrency);
chineseCurrency = data.ticker.price;
alert("success2: chineseCurrency=" + chineseCurrency);
// do what you need with chineseCurrency
}
});
}
You are not taking the data from that is returned from the Ajax call. instead you are just returning the ajax object.
Change your code to :
$.ajax(
{
context: this,
type: 'GET',
dataType: 'json',
url: "https://www.cryptonator.com/api/ticker/usd-cny"
data :{},
error : function(data)
{
console.log('error occured when trying to find the from city');
},
success : function(data)
{
console.log(data); //This is what you should return from the function.
}
});

Keep loading AJAX request

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);

Return ajax data [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have an ajax call in a function and I did not find a solution how to return the data:
function get_blog_post(id){
var info="id="+id;
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
success: function(data){
return data;
}
});
}
The code above doesn't works. The data contains the right answer but I can't use it if I callthe get_blog_post() function.
:\
function get_blog_post(id, callback){
var info="id="+id;
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
success: function(data){
callback(data);
}
});
}
get_blog_post(5, function(data){
// use data here
});
OR set async = false (not recommended):
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
async: false,
success: function(data){
return data;
}
});
The success function runs some time after the ajax call completes. That's the nature of asynchronous calls--like ajax in javascript.
That means you cant return it and have to do something with the data in that function. Perhaps it is text and you put it into a text area like:
success: function(data){
$('textarea').val(data);
}
Provide a callback method and do what ever you want to do inside it
function get_blog_post(id, callback){
var info="id="+id;
$.ajax({
type: 'POST',
url: 'get_blog_post.php',
data: info,
success: callback
});
}

Function Execution order when ajax included in jQuery mobile

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/

jQuery ajax event success handling

I have the following code multiple times:
$.ajax({
type: "POST",
cache: false,
url: "url here",
success: function (data) {
// do something here...
}
});
I'd like to turn this into a function as use it only once, somthing like:
function ajax (type, url, complete){
$.ajax({
type: type,
cache: false,
url: url,
success: function (data) {
GO TO THE METHOD SPECIFIED IN complete
}
});
How would I run a method specified in the complete variable? Is it possible? I've looked at the ajax success event for jQuery but since it would be triggered on every item that uses it, I would then have to check if it is the correct ajax request...
If complete is a reference to a function,
function ajax (type, url, complete){
$.ajax({
type: type,
cache: false,
url: url,
success: complete
});
Just make sure complete's arguments match what is given by success.
EDIT: If complete is an object, just find the function on it and use that:
success: complete.foo
Hope this is what you're asking...
If understand question correctly
function ajax (type, data, url, complete){
$.ajax({
type: type,
data:data,
cache: false,
url: url,
success: complete
});
}
var obj={ id:1}
/* example case use */
ajax ('POST', obj 'site.com', myAjaxComplete);
/* a success callback from ajax*/
function myAjaxComplete(data){
// data argument is return data from server
}
EDIT: you'll definitely want to add an argument for data to send to server

Resources