JS Function including AJAX returning 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.
function idToUnitNum(id){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
return result;
}
});
}
This is the function. It's called from another function. I tried testing it's output by logging result before it returns, and it displays the appropriate result.
Result (JSON):
{"success":"true","time":1524462577,"data":"ADMIN"}
However, when I try catching the variable (a string), it does shows as "undefined".
It's probably a stupid mistake.
Calling the function:
var unitnum = idToUnitNum(adata.arresting_officer);
console.log(unitnum);
Thank you for your assistance!

pass callback function to idToUnitNum. something like below
function idToUnitNum(id,callback){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
callback(result);
}
});
}

Hi Please change the AJAX function like this :
function idToUnitNum(id){
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
dfd.resolve(result);
// return result;
}
});
return dfd.promise();
}
And you can use this function like this
idToUnitNum(adata.arresting_officer).done(function(response){
console.log(response);
});
FYI : not tested code

function idToUnitNum(id){
var result = '';
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
async: false,
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
result = ofd.data;
}
});
return result;
}
Thank you to whoever suggested I turn off async and call it outside fo the AJAX request. Solved the issue.

You should either use a callback function as a parameter or, even better, use promises. Simply put return in front of your ajax call and call .then() on the return value to read the result when it is available.
This has been asked many times, so you shouldn’t have any trouble finding more information about these solutions

Related

Jquery Ajax Call Return

I have made a function which is the one below that i pass data to and returns the result as is. I made this way because i will be needing a lot of ajax call and i just made a function that i pass the data to and get the result as is and work with the result.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}});
return ret;}
Now i am calling it where i need it:
$('#register-name, #register-surname').keyup(function(e) {
var x = FunctionsCall({query: $(this).val(), funcid: 1});
(x!==1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
But strange is that i always see x as undefined. Pointing out the ret is filled with either 1 or 0 i don't know why it is not being passed to x.
Can you please help me out? It might be simple but i just experiment when needed with javascript and jquery.
Regards
ret doesn't get set until the success function runs, which is when the ajax finishes. FunctionCall returns straight away however. You'll either need to return the ajax deferred object or put your addClass/removeClass functionality in your success function.
A way to add your addClass/removeClass functionality to your success function would be like this:
function FunctionsCall(data, successFn) {
$.ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: successFn
});
}
$('#register-name, #register-surname').keyup(function(e) {
var element = $(this);
var data = { query: element.val(), funcid: 1 };
var successFn = function(x) {
if (x !== 1) {
element.addClass('input-has-error')
} else {
element.removeClass('input-has-error');
}
}
FunctionsCall(data, successFn);
});
The problem is that the ajax call takes time to execute, whereas your processing of x is immediately after the call to FunctionsCall
Imagine that in order to go to the php file and get the result, the browser has to send a request over the wire, the server needs to process the request and return the value, again over the wire. This process takes an unpredictable amount of time as it relies on network connections and server specs / current load.
The code to call the function and process the result happens immediately after this step and as such won't have the required values when it is run (browsers are much quicker at executing the next step than networks are at processing requests).
The best thing to do is to wrap your processing code up in it's own function, so it isn't immediately called, then call that function with the result once you get it. Like this:
// function defined, won't be called until you say so
var processMe = function(result) {
alert(result);
}
$.ajax({
// ajax params
success: function(result) {
// function called within success - when we know the request is fully
// processed, however long it takes
processMe(result));
}
});
You could also do the processing directly in the success block but the advantage of using a function is it's there to re-use in the future, plus, you also get to give it a nice understandable name, like outputValidatedMessage.
you must send ajax request syncronous
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
Ajax calls are asynchronous.
This means that while you call $.ajax(), the function continues to run and return x which is undefined, as the ajax response has not been send yet.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
The below should work for you
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
(result !==1 ) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
}});
}
maybe is because the ajax function is called asynchronously so the line var x= .... doesn't wait for the asignment and thats why is undefined. for that you should use a promise here is an example http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
check if the following works, may be your GET method is taking time to execute.
var x;
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
x= result;
alert(x)
}});
return ret;}
if the snippet works, you should make you synchronous async: false or make callback function
try this code.
function FunctionsCall(data,callback) {
try {
ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: function (result) {
callback(result);
}
});
} catch(e) {
alert(e.description);
}
}
$('#register-name, #register-surname').keyup(function (e) {
var data = {
uery: $(this).val(),
funcid: 1
};
FunctionsCall(JSON.stringify(data), function (result) {
(result !== 1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error');
});
});

AJAX response into an object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a stringified array of objects in a database that I'm retreiving with an $.ajax call. I'm trying to use a callback function to get that data into an array outside of my ajax function.
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
function dataHandler(data){
console.log(JSON.parse(data));
return JSON.parse(data);
}
var loadedMap = getMap();
console.log(loadedMap);
The console.log inside of the dataHandler function shows up in my Javascript console as a standard Array (clickable, can view all the data). The console.log at the very end shows up in the console as [object Object]. I can see the actual data inside of that object in a "responseJSON" field, but I can't seem to correctly get that into the loadedMap array.
What am I missing here?
Edit: I feel like my question is different from all of the answers to other questions. Mine seems to be more of a scope problem. A lot of the answers advocated the .done and .fail ways to handle AJAX.
var loadedMap = [];
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap = r;
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
console.log(loadedMap);
This code successfully gets the array where "loadedMap = r", but when you console.log the loadedMap on the outside, its undefined. How can we get the actual data to be outside the AJAX functions?
The function getMap does not return the response, it just calls dataHandler when the response arrives.
create a global variable and assign the vallue of the JSON.parse(data) to that variable. :
var myData;
function getMap(){
...
});
};
function dataHandler(data){
console.log(JSON.parse(data));
myData = JSON.parse(data);
}
getMap();
JQuery's AJAX returns a promise, so you can either go the callback route, as it looks like you were trying to do, or you can simplify it with promises:
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
data: "",
dataType: 'JSON',
success: dataHandler
});
};
getMap().then(function(data){
loadedMap = JSON.parse(data);
console.log(loadedMap);
});

scope of var in jquery function? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does Asynchronous means in Ajax?
why my var "temp" is 0 after the ajax?
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
Because the ajax call is asynchronous, so temp is returned before being updated ...
Because the success function doesn't run until the HTTP response is comes back from the server.
Ajax is asynchronous.
Do what you want to do with the data in the success function (or in functions you call from it).
Don't try to wait for a response and then return data to a calling function.
Ajax calls are asynchronous but you can use CommonJS Promises/A pattern to achieve what you want. jQuery provides it's own implementation of it: jQuery.Deferred().
As others have mentioned here, because ajax is asynchronous, you're not guaranteed to get the updated temp variable before your return statement. It would be best to work within your success function. However, if you absolutely have to wait for that call to finish and return the temp variable, you can make it Non-asynchronous by adding async: false
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
async: false,
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
S.ajax/$.post/$.get etc etc, all these are asynchronous process (which means, you will come out of the loop even before $.ajax is completed, even though it will be going to server side after coming out of the loop)
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
.............
..............
}
});
return temp;
}
So just after the loop if you will check, the following statement might not have executed(depending upon the data set).
temp = parseFloat(myJSONObject.bindings[0].value);
so to check the data in temp variable you should put a debugger/alert inside $.ajax. example :
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
alert(temp);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
now you will get the value of temp

jQuery ajax return value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
How can I return the value "pinNumber" from jquery ajax so I can append it outside of the ajax. Here is my code
var x = pinLast + 1;
for(i=x;i<=pinMany;i++) {
var i = x++;
var cardNumber = i.toPrecision(8).split('.').reverse().join('');
var pinNumber = '';
jQuery.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false,
success: function(msg){
var pinNumber = msg;
return pinNumber;
//pin number should return
}
});
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+'');
// the variable pinNumber should be able to go here
}
Please ask me if you don't understand.. ^^ thanks
AJAX is asynchronous by default, you cannot return a value from the callback without making a synchronous call, which you almost certainly don't want to do.
You should supply a real callback function to the success: handler, and put your program logic there.
var pinNumber = $.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator",
async: false
}).responseText;
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+' ');
It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.
Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.
var _successEvent = function(response){
$('.pin_generated_table').append(cardNumber + ' = ' + response);
};
$.ajax({
type: "POST",
url: "data.php",
data: "request_type=generator"
}).done(_successEvent);
You can use this example:
window.variable = 'some data';
This make you variable global and you can access to this from anywhere
Here is the simple solution.
//---------------------------Ajax class ------------------------------//
function AjaxUtil()
{
this.postAjax = function(Data,url,callback)
{
$.ajax({
url: url,
async: true, //must be syncronous request! or not return ajax results
type: 'POST',
data: Data,
dataType: 'json',
success: function(json)
{
callback(json);
}
});
}//--end postAjax
}
//--------------------------------End class--------------------//
var ajaxutil = new AjaxUtil();
function callback(response)
{
alert(response); //response data from ajax call
}
var data={};
data.yourdata = 'anydata';
var url = 'data.php';
ajaxutil.postAJax(data,url,callback);

jquery trouble with getJSON call

Got some basic problem again.
I need to modify a function that previously returned a in code written object.
Im now trying to get the object from json through $.getJSON
function getEventData() {
var result = '';
$.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data) {
result = data;
});
return result;
}
Problem is that result isn't set in the callback function for obvious reasons.
Do you guys have a solution for this?
Edit:
Ok i got an answer that was removed.
I just had to change it abit..
This is the answer that works:
function getEventData() {
var result = '';
url = "ajax.php?cmd=getbydate&fromdate=&todate=";
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:
function getEventData() {
var result = '';
result = $.ajax({
url: "ajax.php?cmd=getbydate&fromdate=&todate=",
async: false,
dataType: "json",
data: data,
success: function(data) {
return data;
}
});
return result;
}
Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

Categories

Resources