This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I want to get data from another page using AJAX. I also want to wrap this AJAX call into my "user defined function".
But I can not write like this:
function func(){
var tmp;
$.ajax({
url: 'url',
type: "POST",
dataType: "json",
success: function (data) {
tmp=data;
}
});
return tmp;
}
because AJAX is asynchronous and this code returns - "undefined".
When AJAX async param set to false
var tmp=$.ajax({...});
possible do the trick.
I also can create some global variables and write like this:
function setMyVariable(){
$.ajax({
...
success: function (data) {
myGlobalVariable=data;
}
});
}
The question is - Is it good practice to use global variables in this case?
Or it is completely wrong and I need search something else
The best practice would be to return the promise from $.ajax:
function func(){
var tmp;
return $.ajax({
url: 'url',
type: "POST",
dataType: "json",
});
}
Then you can do function().done(function(result) { ... } );
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have the following ajax script
dataString = 'cipher'; //
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
returnedvalue = result //I wanted to store the value returned by php in this variable
alert(returnedvalue);
and the tokenize.php is
$data = json_decode(stripslashes($_POST['data']));
return $data; //Pass this value as ajaxs response
But im not able to get this.When I checked in the console I get error uncaught:result is not defined.
Im new to query,searched on google and done upto this.
The json is not necessary,all I wanted to do is pass a value to php and process it and give a rssponse back to teh javascript so that i can use it in the javascript
You are passing just string(dataString = 'cipher';) into ajax file. There is no need to JSON.
To use echo for return values from AJAX file.
Update in JS:
dataString = 'cipher'; //
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(result) { //just add the result as argument in success anonymous function
var returnedvalue = result;
alert(returnedvalue);
}
});
Update in PHP file:
$data = stripslashes($_POST['data']);
echo $data;
You need to pass the parameter into the anonymous function for the success event.
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
I declare an array then make an ajax call which returns multiple rows of values. I'm trying to add the id of these rows to that array that i declared previously, but it keeps returning undefined.
var recipeIds = Array();
$.ajax({
url: url,
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
crossDomain: true,
jsonp: 'jsoncallback',
cache:true,
success: function(data, status){
$.each(data, function(i,item){
recipeIds.push(item.id);
});
},
error: function(){
console.log("Ajax not working - recipies in cat");
}
});
alert("array0 = " + recipeIds[0]);
any suggestions?
When you alert, the ajax call hasn't yet returned. It's asynchronous, meaning the ajax call will happen after the alert.
You must use the result from inside the success callback you give to the ajax function.
I am completely new to Javascript/jquery world and need some help. Right now, I am writing one html page where I have to make 5 different Ajax calls to get the data to plot graphs. Right now, I am calling these 5 ajax calls like this:
$(document).ready(function() {
area0Obj = $.parseJSON($.ajax({
url : url0,
async : false,
dataType : 'json'
}).responseText);
area1Obj = $.parseJSON($.ajax({
url : url1,
async : false,
dataType : 'json'
}).responseText);
.
.
.
area4Obj = $.parseJSON($.ajax({
url : url4,
async : false,
dataType : 'json'
}).responseText);
// some code for generating graphs
)} // closing the document ready function
My problem is that in above scenario, all the ajax calls are going serially. That is, after 1 call is complete 2 starts, when 2 completes 3 starts and so on .. Each Ajax call is taking roughly around 5 - 6 sec to get the data, which makes the over all page to be loaded in around 30 sec.
I tried making the async type as true but in that case I dont get the data immediately to plot the graph which defeats my purpose.
My question is:
How can I make these calls parallel, so that I start getting all this data parallely and my page could be loaded in less time?
Thanks in advance.
Using jQuery.when (deferreds):
$.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){
// plot graph using data from resp1, resp2 & resp3
});
callback function only called when all 3 ajax calls are completed.
You can't do that using async: false - the code executes synchronously, as you already know (i.e. an operation won't start until the previous one has finished).
You will want to set async: true (or just omit it - by default it's true). Then define a callback function for each AJAX call. Inside each callback, add the received data to an array. Then, check whether all the data has been loaded (arrayOfJsonObjects.length == 5). If it has, call a function to do whatever you want with the data.
Let's try to do it in this way:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var area0Obj = {responseText:''};
var area1Obj = {responseText:''};
var area2Obj = {responseText:''};
var url0 = 'http://someurl/url0/';
var url1 = 'http://someurl/url1/';
var url2 = 'http://someurl/url2/';
var getData = function(someURL, place) {
$.ajax({
type : 'POST',
dataType : 'json',
url : someURL,
success : function(data) {
place.responseText = data;
console.log(place);
}
});
}
getData(url0, area0Obj);
getData(url1, area1Obj);
getData(url2, area2Obj);
});
</script>
if server side will be smth. like this:
public function url0() {
$answer = array(
array('smth' => 1, 'ope' => 'one'),
array('smth' => 8, 'ope' => 'two'),
array('smth' => 5, 'ope' => 'three')
);
die(json_encode($answer));
}
public function url1() {
$answer = array('one','two','three');
die(json_encode($answer));
}
public function url2() {
$answer = 'one ,two, three';
die(json_encode($answer));
}
So there, as you can see, created one function getData() for getting data from server and than it called 3 times. Results will be received in asynchronous way so, for example, first can get answer for third call and last for first call.
Console answer will be:
[{"smth":1,"ope":"one"},{"smth":8,"ope":"two"},{"smth":5,"ope":"three"}]
["one","two","three"]
"one ,two, three"
PS. please read this: http://api.jquery.com/jQuery.ajax/ there you can clearly see info about async. There default async param value = true.
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...
The following worked for me - I had multiple ajax calls with the need to pass a serialised object:
var args1 = {
"table": "users",
"order": " ORDER BY id DESC ",
"local_domain":""
}
var args2 = {
"table": "parts",
"order": " ORDER BY date DESC ",
"local_domain":""
}
$.when(
$.ajax({
url: args1.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args1),
error: function(err1) {
alert('(Call 1)An error just happened...' + JSON.stringify(err1));
}
}),
$.ajax({
url: args2.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args2),
error: function(err2) {
calert('(Call 2)An error just happened...' + JSON.stringify(err2));
}
})
).then(function( data1, data2 ) {
data1 = cleanDataString(data1);
data2 = cleanDataString(data2);
data1.forEach(function(e){
console.log("ids" + e.id)
});
data2.forEach(function(e){
console.log("dates" + e.date)
});
})
function cleanDataString(data){
data = decodeURIComponent(data);
// next if statement was only used because I got additional object on the back of my JSON object
// parsed it out while serialised and then added back closing 2 brackets
if(data !== undefined && data.toString().includes('}],success,')){
temp = data.toString().split('}],success,');
data = temp[0] + '}]';
}
data = JSON.parse(data);
return data; // return parsed object
}
In jQuery.ajax you should provide a callback method as below:
j.ajax({
url : url0,
async : true,
dataType : 'json',
success:function(data){
console.log(data);
}
}
or you can directly use
jQuery.getJSON(url0, function(data){
console.log(data);
});
reference
You won't be able to handle it like your example. Setting to async uses another thread to make the request on and lets your application continue.
In this case you should utilize a new function that will plot an area out, then use the callback functions of the ajax request to pass the data to that function.
For example:
$(document).ready(function() {
function plotArea(data, status, jqXHR) {
// access the graph object and apply the data.
var area_data = $.parseJSON(data);
}
$.ajax({
url : url0,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url1,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url4,
async : false,
dataType : 'json',
success: poltArea
});
// some code for generating graphs
}); // closing the document ready function
It looks like you need to dispatch your request asynchronously and define a callback function to get the response.
The way you did, it'll wait until the variable is successfully assigned (meaning: the response has just arrived) until it proceeds to dispatch the next request. Just use something like this.
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(data) {
area0Obj = data;
}
});
This should do the trick.
Here's a solution to your issue: http://jsfiddle.net/YZuD9/
you may combine all the functionality of the different ajax functions into 1 ajax function, or from 1 ajax function, call the other functions (they would be private/controller side in this case) and then return the result. Ajax calls do stall a bit, so minimizing them is the way to go.
you can also make the ajax functions asynchronous (which then would behave like normal functions), then you can render the graph at the end, after all the functions return their data.
My variable is Global, but she doesn't display the same result :
function checkLiveRdv(salle, jour, dateus, heure)
{
var resu;
var urlaction = myUrl;
$.ajax({
type: "POST",
dataType: "json",
url: urlaction,
data: myDatas,
success: function(message)
{
data = $.parseJSON(message);
if(data['nb']==1)
resu = "ok";
else resu = "pasok";
//this alert display the good result
alert (resu);
}
});
//this alert display 'undefined', why ???
alert(resu);
}
I don't know why resu doesn't keep the data :/
First, your resu variable is not global. It is local inside the scope of the checkLiveRdv function. Global variables in javascript are declared without the var keyword. However, omitting global variables is a good practice.
The first alert which appears displays a yet valueless undefined resu. The asynchronous $.ajax finishes later and as it fills the value of resu, it gets displayed correctly.
I would leave the ajax call asynchronous as it is now. And work with resu only inside the ajax callback as it gets its value inside it.
That is becouse you are not waiting for the $.ajax() call to complete.
If you need synchronous requests, set the sync option to false:
$.ajax({
type: "POST",
async: false,
...
It is because $.ajax() in this case is asynchronous. Modify $.ajax() to include async: false:
$.ajax( {
type : 'POST',
dataType: 'json',
url : urlaction,
data : myDatas,
async : false,
success : function(message) {
data = $.parseJSON(message);
if(data['nb']==1)
resu = "ok";
else resu = "pasok";
alert (resu);
}
} );