Javascript passing variable from ajax function - javascript

I'm a learner and i'm facing a problem. First i made a variable. then with a ajax function i have got a json data. then i parsed it and tried to pass the json data to my variable named var invoice_details. Then with a click event i tried to see the variable but its showing only 0. but my console.log(parsed); command under ajax function showing the json data on my console log. but the console.log(invoice_details); on my action function showing 0. What wrong with me?
//function order started
var invoice_details;
function order(val1){
var order_no=getQueryVariable("order_number");
//AJAX START
$.ajax({
url: "/anamika/function/order.php",
type: "POST",
data: {item_code: item_added, paymentdetails: val1, order_no: order_no },
success:function(data, textStatus, jqXHR)
{
//console.log(data);
var parsed = JSON.parse(data);
var invoice_details = parsed;
console.log(parsed);
},//Success finished
error:function(jqXHR, textStatus, errorThrown)
{
} //Error finished
}) //AJAX FINISHED
}
//function order finished
order('91');
$("#invoice_pay").live("click", function (event) {
console.log(invoice_details);
})

When you declare var invoice_details = parsed; inside the success callback, you are actually creating a new local variable that lives only on the scope of the success callback, and hence this new local variable is getting your data and not the global one you're then performing the console.log on.
You already defined that variable on the outside, so just remove the var declaration and do:
invoice_details = parsed;

Related

Pass function reference to a separate Javascript file for callback

I have created a common Javascript file for all my ajax calls. I am trying to use this as a common way to keep track of all ajax calls. Below is the code for the same.
function doAjax(doAjax_params) {
var url = doAjax_params['url'];
var requestType = doAjax_params['requestType'];
var contentType = doAjax_params['contentType'];
var dataType = doAjax_params['dataType'];
var data = doAjax_params['data'];
var beforeSendCallbackFunction = doAjax_params['beforeSendCallbackFunction'];
var successCallbackFunction = doAjax_params['successCallbackFunction'];
var completeCallbackFunction = doAjax_params['completeCallbackFunction'];
var errorCallBackFunction = doAjax_params['errorCallBackFunction'];
//Make the ajax call
$.ajax({
url: getBaseURL() + url,
crossDomain: true,
type: requestType,
contentType: contentType,
dataType: dataType,
data: data,
success: function (data, textStatus, jqXHR) {
console.log(typeof successCallbackFunction);
debugger
//if (typeof successCallbackFunction === "function") {
successCallbackFunction(data);
//}
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof errorCallBackFunction === "function") {
errorCallBackFunction(errorThrown);
}
}
});
}
This code takes a list of parameters and creates an ajax request based on the parameteres. This code is saved in a file APIHandler.js.
I am trying to call this function from multiple files. An example call is below.
function RedirectToDashboard() {
var params = $.extend({}, doAjax_params_default);
params['url'] = `profile/5`;
params['successCallbackFunction'] = `testsuccess`
doAjax(params);
}
function testsuccess() {
alert("success");
}
When I run this function, I am able to make the call successfully. The only issue comes with the reference to callback function. console.log(typeof successCallbackFunction); returns string instead of function.
I thought maybe order of JS made a difference. I am loading APIHandler.js and then the page specific js. And this ajax call happens at button click, so both JS files are loaded before the ajax call is made.
Other than that, I think maybe I am sending the parameters wrong. That might be causing JS to consider function name as string. But I checked most of the google suggestions on how to pass function, and it seems it needs just the name.
Is there anything else that I might be missing here?
Damn it. I just figured out why it was causing the error. I used quotes when assigning the callback function. Right after posting the question, I realised what was wrong.
params['successCallbackFunction'] = 'testsuccess'
is supposed to be changed to
params['successCallbackFunction'] = testsuccess

Confused with javascript global variable scope and update

I am trying to get a specific piece of data from from a json source. I have declared a global variable and try to update the global variable but it doesn't update correctly. Also, the order in which my debug alerts run is confusing.
<script>
//global variable
var latestDoorStatus = "initialized value"; //set value for debugging purposes
//debug alert which also calls the function
alert("Alert#1: call getDoorStatus = " + getDoorStatus("***********"));
function getDoorStatus(public_key) {
//get data in json form
var cloud_url = 'https://data.sparkfun.com/output/';
// JSONP request
var jsonData = $.ajax({
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var latest = results[0];
//debug alert
alert("Alert #2: latestDoorStatus = " + latestDoorStatus);
//update the global variable
latestDoorStatus = latest.doorstatus;
//debug alert
alert("Alert #3: latestDoorStatus = " + latestDoorStatus);
//return the global variable
return latestDoorStatus;
});
alert("Alert #4: latestDoorStatus = " + latestDoorStatus);
}
</script>
When I run this in my browser I get the following behaviors:
First I get alert#4 (supposed to run at END of the script) with the initialized value of the global variable
then I get alert#1 as "undefined". This is supposed to be the result of calling the function getDoorStatus which should return an updated value of latestDoorStatus
then I get alert #2 as the initialized value of latestDoorStatus which makes sense since the global variable has not yet been updated
then I get alert #3 with the correct value of latestDoorStatus
The function is supposed to return the variable latestDoorStatus AFTER alert #3 (i.e. after global variable has been updated correctly) so I don't understand why alert #1 (which is supposed to have the returned value) is coming back undefined and why alert#4 which is supposed to run at the very end of the script is running first.
You are calling $.ajax asynchronously, and passing a callback function to done.
function makeRequest() {
$.ajax({ // An async Ajax call.
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
// this code is executed only after the request to cloud_url is finished.
console.log("I print second.");
});
console.log("I print first.");
}
The callback is called when the request is finished, and when depends entirely on how long the request to https://data.sparkfun.com/output/ takes. So the code after your Ajax call is executed immediately, we're not waiting for the http request to finish.
Your function getDoorStatus returns nothing, but your callback passed to done does. The thing you need to know is that you can't return anything from asynchronously executed functions. Well, you can return, but there will be nothing there to use the returned value.
So instead, do the things you want to do with the returned data from https://data.sparkfun.com/output/ in the callback passed to done.
function getDoorStatus(public_key) {
//get data in json form
var cloud_url = 'https://data.sparkfun.com/output/';
// JSONP request
var jsonData = $.ajax({
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
// latestDoorStatus = results[0]; // Not a good practice.
// Instead:
showDoorStatus(results[0]);
});
}
function showDoorStatus(status) {
document.getElementById("door-status").innerText = status;
// Or something like this.
}
getDoorStatus("***********");
And somewhere in your HTML:
<p id="door-status"></p>
.done() will be called after the response of the AJAX request got received!
1) getDoorStatus() is called from inside alert() at top of code => #4 shown. It does not matter that the function is defined below and not above.
2) alert() at top of code is called & getDoorStatus() does not directly return a value => #1 shown with undefined.
3) AJAX response returned, .done() function gets called => #2 and #3 are shown.

Retrieve all 'data' properties of json data with ajax

I'm trying to figure out how to access to all the data from a json provided by movie database api, but I don't understand how to retrieve it.
The console log give me an "data is not defined" error.
So here is my code:
$(document).ready (function(){
var key = 'api key provided';
$.ajax({
type: 'GET',
url : 'http://api.themoviedb.org/3/search/movie'+key+'&query=Minions',
dataType: 'jsonp',
data: {
format:'json'
},
error: $('#result').append("errore"),
success: function(data){$('#result').append("ok")}
});
var jsonData=data.results.original_title;
//this give me a data is not provided
});
Here a portion of json:
Let's assume that I only want to access to the release_date propriety, how can I achieve this?
data not is defined out of $.ajax() closure, you need to move the code to success handler like, then loop through the JSON data.results.
success: function(data){
$('#result').append("ok");
console.log(data);
$.each(data.results, function(i, result) {
console.log('Release date is' + result.release_date);
});
}
alternatively, you can define a variable, then update that variable in success handler of $.ajax()
var ajaxResponse;
$.ajax({
/* skipped lines*/
success: function(data){
ajaxResponse = data
}
});

key in object returning undefind after AJAX call

I am doing an Ajax request on an XML file and mapping the XML into a JavaScript object my problem is that am logging the object and seeing the values I won't but when I try to return the values I keep getting undefined, even that all the code is inside the success callback of the AJAX request, my code is as bellow:
// Errors Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
// Ajax Request
$.ajax({
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
$(xml).find('EcaAdminBc').each(function () {
var code = $(this).find('code').text();
var msg = $(this).find('msg').text();
ErrorsObject[code] = msg;
});
// Reformat Errors
if(ErrorApplet.length > 0) {
$(ErrorApplet).each(function(){
var Error = $(this).text();
if(Error.indexOf("SBL") >= 0){
var ErrorCode = Error.split('(')[1].replace(")","");
var ErrorText = ErrorsObject[ErrorCode];
// The Log is showing the values correctly but i cant access the object values
console.log(ErrorsObject);
// ErrorText And ErrorCode Are always undefined !!
if(typeof ErrorText != 'undefined'){
$(this).text(ErrorText);
}
}
});
}
}
});
I need additional context, but I guess what the problem is. You are trying to do some thing like this:
var myFunction = function(){
// Error Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
$.ajax(
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
//using response to fill ErrorsObject
ErrorsObject['Ok'] = 'This key has Value!';
//more awesome code here
//... lets check again:
console.log(ErrorsObject['OK']); //Outputs 'This key has Value!'
}
);
return ErrorsObject;
};
var myAwesomeErrorObject = myFunction();
console.log(myAwesomeErrorObject['OK']); //undefined!
console.log(myAwesomeErrorObject); //Empty object!
The problem is that myFunction finished before the success callback function gets executed (the callback is asynchronous). That is why logging myAwesomeErrorObject['OK'] shows undefined. I guess that you also tried return ErrorsObject inside the success callback, but that won't work either.
In order to fix your code you must either:
Use the ErrorsObject inside the success callback (i.e. don't return it).
Call a second function from inside the success callback, passing it the ErrorsObject.
Pass a calback function to myfunction and execute it from inside the success callback.

javascript & jQuery scope question

I have the following method:
function priceRange(FESTIVALID){
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
}//success
});//ajax;
//
return formatedPriceRange;
};
The second console.info correctly displays the formatedPriceRange,
but outside the function is undefined.
how can I access this variable out side the priceRange function?
Thanks
It's normal, that's how AJAX works. It's asynchronous, meaning that the jQuery.ajax function returns immediately and in this case formatedPriceRange hasn't yet been assigned a value and once the server responds (which can be for example 10 seconds later), the success callback is invoked and the variable is assigned a value.
So always consume the results of your AJAX requests inside the success callback function.
You also have the possibility to pass the async: false option to your jQuery.ajax call which will perform a synchronous request to the server and block until the result is retrieved. Obviously this will lead to your browser freezing during the execution of the request. So it would no longer be AJAX (Asynchronous Javascript And Xml) but SJAX (Synchronous Javascript and Xml).
You have to make sure that the AJAX request finishes before you access the price range data.
You need to expose the price range data outside the scope of the success function.
Here's how you can do it:
function priceRange(FESTIVALID, callback) {
jQuery.ajax({
url: '/actions/festheads.cfc?method=getPriceRangeByGUID',
type: 'POST',
data: 'FESTIVALID=' + FESTIVALID,
dataType: 'json',
success: function(data) {
console.info("AJAX:qPrices", data.MINPRICE);
formatedPriceRange = '$ ' + data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
callback.call(this, formatedPriceRange);
} //success
}); //ajax;
}
var myFestivalID = 1;
priceRange(myFestivalID, function(priceRange) {
// this code runs when the ajax call is complete
alert('The formatted price range is:' + priceRange);
});
how can I access this variable out
side the priceRange function?
Like Darin said, you have to use your results in the success callback function.
Assuming you're using your current function like this:
var range = priceRange(festivalId);
// ... doing stuff with range variable
You'll want reorganize your code so that anything you do with the range variable stems from the success callback. For example, you can create a function to handle updating the UI with the new range:
function handleRangeVariabe(range) {
/// ... do stuff with range variable
}
Call it from success:
success: function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
handleRangeVariable(formatedPriceRange);
}
Flower the steps of sample Code:
//declare function
function priceRange(FESTIVALID, functionCallBack){
//1º step
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
//3º step, because this function will only trigger when server responds to request
//handle data in other function
functionCallBack(data);
}//success
});//ajax;
//more code
//2º step
//no return value, because this method no know when the data will return of server
//return formatedPriceRange;
};
var formatedPriceRange;
//using function
princeRange(1 , function(data){
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
});

Categories

Resources