Javascript ajax global variable undefined [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I try to get some info from external php with ajax and use the data but my global var return undefined.I try with async false but is deprecated.If i console in success function it has value outside is undefined.
var pkz;
$(function(){
$.ajax({
type:'GET',
url: '/user/cred',
success: function (data){
pkz=data;
}
});
console.log(pkz);

The problem with your code is that the execution is asyncronous. When you run console.log, the ajax did not finished. Put it inside the ajax callback.
The ajax do not block the execution. It continue without finished. You SHOULD use callbacks.
If you want to use ajax syncronous:
$.ajax({
type: "GET",
url: remote_url,
async: false
})
This is a horrible solution.

Related

Simplest solution for Synchronous XMLHttpRequest is deprecated and add a waiting circle gif animation while javascript do ajax call to php [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
My current code is :
var dataReceiveString = $.ajax({
url: "getDataReceiveString.php?"+param,
dataType: "text",
async: false
}).responseText;
// code that make use of dataReceiveString ;
The obvious choice of changing false to true does not work.
How should the code be rearranged ?
Also to add a waiting circle gif animation while javascript do ajax call to php.
edit : question is different from Execute function after Ajax call is complete
as avoiding use of async:false.
edit : question is different from
How do I return the response from an asynchronous call?
as it's too generic and not targetted to my question.
If you want to make it sync you can always rely to async functions:
async function doAjax(args) {
let result;
try {
result = await $.ajax({
url: ajaxurl,
type: 'POST',
data: args
});
// code that make use of dataReceiveString
return result;
} catch (error) {
console.error(error);
}
}

Why is the result of my Ajax request empty although the request goes through ok? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
My alert shows an "Undefined" with the following code:
var nonce = (function () {
$.ajax({
url: site_url + '/api/get_nonce/?controller=user&method=register&apikey=XXX&callback=?',
type: "GET",
dataType: 'json',
success: function(data){
nonce = data.nonce;
}
});
return nonce;
})();
alert(nonce);
The JSON is:
?({"status":"ok","controller":"user","method":"register","nonce":"XXX"})
What I'm doing wrong?
Ajax calls are asynchronous. At the point you are doing the return nonce; the result hasn't arrived yet - or at least isn't guaranteed to.
You'd need to put the alert(nonce);, and anything else you want to do with the result, inside the success handler of the Ajax call.
In the long run, you also want an error callback to handle when something goes wrong.

Ajax return value in another function - javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am calling ajax in one function and the result should be caught in another function.
It is better explained below
function myMain(){
var test = myWPackage();
alert(test);
}
function myWPackage(){
var tender_number = "TENDER_TEST-123";
//calling ajax function
$.ajax
({
url: "getWorkPackage.php",
type: "POST",
dataType: 'json',
data: {source1 : tender_number},
cache: false,
success: function (work_package)
{
return work_package[0];
})//ajax ending
}
The database if connected and the value is coming if i replace return with alert in myWPackage so there is no issue with database or the data coming.
When i call myMain() function it gives "UNDEFINED". Can anyone let me know what am i doing wrong? I am trying to ge the value from ajax to test.
thank you in advance.
I think the problem is of synchronization , Because Ajax in jquery if not synchronize
Try this link

How to to return a value from Ajax call to server [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I make an ajax call to my server to retrieve some records and return them as a JSON object.
Here is the code for the call
$(".reply").click(function (){
$.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success: function (data) {
sync_data=JSON.stringify(data)
}
});
Am trying to use the returned data to construct grid, so when I pass the variable syncd_data which I have declared global in the Ajax call, It seems to be undefined.
$(document).ready(function(){
var data = source_data;
//other code
..........................
..........................
But when I do alert(sync_data) from within the ajax call as below:
$(".reply").click(function (){
$.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success: function (data) {
sync_data=JSON.stringify(data)
}
});
It shows the data correctly.
I can I use this data outside the Ajax call?
Any Help Insights or examples will be highly appreciated.
Thanks
You need to make sure you are calling that function inside of the success callback of your ajax call:
success: function (data) {
sync_data=JSON.stringify(data);
doSomething(sync_data);
}
This is because AJAX is Asynchronous, you need to make sure your call is done and successful before proceeding to the next event. Even if the variable is declared to be global.
UPDATE:
var sync_data;
$(document).ready(function(){
$.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success: function (data) {
sync_data=JSON.stringify(data);
}
});
});
This way, you'll make sure sync_data is, technically, populated in document.ready upon returning from the AJAX request. You can now consume it anywhere.
add var sync_data = "" out of your ajax call and before it. And after your ajax call, you can see it's data by alert(sync_data);
by adding a variable before ajax call make it can use out of ajax call

How to block thread on getJSON [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have two web services calls I need to make from my JQuery 1.9.1 app. I need the results from the first one before I make the second call.
It appears that my getJSON requests do not block the thread. I'm told that javascript is not multi-threaded, so how do I block between these server calls?
jQuery's ajax functions all return a jqXHR object that implement the Promise interface.
Instead of blocking an asynchronous request (and everything else), nest your requests like so
$.ajax({...})
.done(function( data ) {
// second request
$.ajax({...});
});
Well, you don't need to block threads, that's old school.
You have two options:
Make the ajax call syncronous.
Cascade the ajax calls, so the second is made only once the first one is completed.
I recommend the second approach, because that is the right way to do it.
/* Call 1 */
$.ajax({
url: 'first url to call',
data: 'first data sent to the server',
success: function (results1){
// Do something with the results
/* make the second call */
$.ajax({
url: 'sencond url to call'
data: 'second data sent to the server'
success: function(results2){
// Do something when all completed
}
});
}
});
Call your 1st ajax request in async false mode to server
$.ajax({
url: Url,
dataType: 'json',
async: false,
data: myData,
success: function(data) {
//stuff
}
});

Categories