Passing a callback function with included parameters? [duplicate] - javascript

This question already has answers here:
Pass an extra argument to a callback function
(5 answers)
Closed 6 years ago.
I have this below code..
function getGrades(grading_company) {
if (grading_company == 'Not Specified') {
// Remove grades box & show condition box
showConditionBox();
} else {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}
Edit: Here is the function that gets called as the callback function:
function showGradesBox(response) {
// Load data into grade field
jQuery('#grade').html(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
Now if I wanted to pass the grading_company variable to the callback function as a parameter is there a way to do that without having to add it as another parameter in the runAjax call? I'm trying to keep the runAjax function open to other usage so I don't want to pass in any extra parameters; but if it can somehow be included within the callback then great.

change your callback to an anonymous function:
// Set the callback function to run on success
var callback = function () {
showGradesBox(grading_company);
};
This allows you to pass parameters to the inner function.
Edit: to allow for the ajax response:
// Set the callback function to run on success
var callback = function (response) {
showGradesBox(grading_company, response);
};

Another possibility is instead of doing dataString do dataObject then pass that object to the callback. Like so:
function getGrades(grading_company) {
if (grading_company == 'Not Specified') {
// Remove grades box & show condition box
showConditionBox();
} else {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data object
var dataObject = {
'gc_id' : grading_company
/*to do multiples..
'item1' : value1,
'item2' : value2,
'etc' : etc */
}
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataObject, callback);
}
}
function runAjax(loadUrl, dataObject, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: $.param(dataObject),
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response, dataObject);
}
});
}
Note the addition of $.param().
Then in the callback function, you should know what data you're after. If function setGrades(resp, data) { ... } was the callback, then you can access the values in setGrades
function setGrades(resp, data) {
alert( data.gc_id);
}
EDIT
After testing, I realize that $(dataObject).serialize() will not work. So I've updated to use $.param(). Please see this SO post for more info.

Related

How to create callback function using Ajax?

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.
When I try this:
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.
Here is the full code:
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.
I have tried this and I still don't get a return value outside of the get_emailno function.
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
async: true,
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.
Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?
Thank you.
From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).
When you return data from the server in another function like this
function get_emailno(emailid, mailfolder) {
$.ajax({
// ajax settings
});
return email_number;
}
Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.
Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.
There are two ways you can define callbacks.
1. Define them within the jquery ajax request settings like this:
$.ajax({
// other ajax settings
success: function(data) {},
error: function() {},
complete: function() {},
});
2. Or chain the callbacks to the returned jqXHR object like this:
$.ajax({
// other ajax settings
}).done(function(data) {}).fail(function() {}).always(function() {});
The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().
On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).
With this knowledge, you can better write your code to catch the data returned from the server at the right time.
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
// sufficient to get returned data
email_number = data;
// use email_number here
alert(email_number); // alert it
console.log(email_number); // or log it
$('body').html(email_number); // or append to DOM
}
});
}

How do I manipulate data coming from multiple async ajax async calls with callback?

I have the following piece of code that make async ajax calls with callback.
My first main issue is that is that when i do data manipulation using callback functions setA,setB,... the returned values from ajax calls are not always present and I end doing operations on unidentified variables from "dataFromAjax". Is there a way to perform the operation in setB only when i know that i have some data in dataFromAjax['firstCall'] which was set by function setA ?
Second question is there a way to simplify the code without having to create a new success function for every data manipulation?
dataFromAjax = {};
function makeACall(url,successCallBack,errorCallback){
$.ajax({
type: 'GET',
async: true,
url: url,
success: successCallBack,
error: errorCallback
});
}
makeACall(url,setA,errorAjax)
makeACall(url,setB,errorAjax)
makeACall(url,setC,errorAjax)
makeACall(url,setD,errorAjax)
function setA(ajaxData){
dataFromAjax['firstCall'] = ajaxData;
}
function setB(ajaxData){
dataFromAjax['secondCall'] = dataFromAjax['firstCall'] + ajaxData;
}
function setC(ajaxData){
dataFromAjax['thirdCall'] = dataFromAjax['secondCall'] / ajaxData;
}
You can try with $.when function, here is documentation https://api.jquery.com/jquery.when/
Basically your code could looks like in example:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
In your case something like (depends on what you want achieve)
$.when($ajax.(url), $.ajax(url), $.ajax(url), $.ajax(url)).then(success, error);
function success(a, b, c, d) { return (a+b)/c; }
function error() { /* error handling */ }
If you want to check if property exists in the object (made it more consistent).
if (dataFromAjax.firstCall) {
dataFromAjax.secondCall = dataFromAjax.firstCall + ajaxData;
}
I'm not sure if I understand but if you don't want to make a separate success callback for every ajax call you can make a default one and remove an argument.
function defaultSuccess(ajaxData) {
// do what you want
}
function makeACall(url, errorCallback){
$.ajax({
type: 'GET',
async: true,
url: url,
success: defaultSuccess,
error: errorCallback
});
}

Set variables in JavaScript once function finishes

I have two functions that makes Ajax calls: getData and getMoreData. getMoreData requires a url variable that is dependent on the url variable getData. This questions continues from: String append from <select> to form new variable.
By appending an item obtained from the received from getData onto a base URL, I create a new variable (Let's call this NewDimensionURL) that I use for getMoreData url. However, NewDimensionURL will show error because the original list (from getData) has yet to be populated and will append nothing onto the base URL.
An idea that I have is to set NewDimensionalURL once getData finishes populating the combobox, so that getMoreData can run after.
JavaScript
var GetDimensions = 'SomeURL1';
//--Combines URL of GetDimensionValues with #dimensionName (the select ID)
var UrlBase = "Required URL of getMoreData";
var getElement = document.getElementById("dimensionName");
var GetDimensionValues = UrlBase + getElement.options[getElement.selectedIndex].text;
function handleResults(responseObj) {
$("#dimensionName").html(responseObj.DimensionListItem.map(function(item) {
return $('<option>').text(item.dimensionDisplayName)[0];
}));
}
function handleMoreResults (responseObj) {
$("#dimensionId").html(responseObj.DimensionValueListItem.map(function(item) {
return $('<option>').text(item.dimensionValueDisplayName)[0];
}));
}
function getData() {
debugger;
jQuery.ajax({
url: GetDimensions,
type: "GET",
dataType: "json",
async: false,
success: function (data) {
object = data;
handleResults(data);
}
});
}
function getMoreData() {
debugger;
jQuery.ajax({
url: GetDimensionValues,
type: "GET",
dataType: "json",
async: false,
success: function (data) {
object = data;
handleMoreResults (data);
}
});
}
Answered
Reordered as:
var GetDimensionValues;
function handleResults(responseObj) {
$("#dimensionName").html(responseObj.DimensionListItem.map(function(item) {
return $('<option>').text(item.dimensionDisplayName)[0];
}));
GetDimensionValues = UrlBase + getElement.options[getElement.selectedIndex].text;
}
Created onchange function Repopulate() for getMoreData() to parse and for handleMoreResults() to populate.
I'm guessing you just do getData(); getMoreData() back to back? If so, then you're running getmoreData BEFORE getData has ever gotten a response back from the server.
You'll have to chain the functions, so that getMoreData only gets executed when getData gets a response. e.g.
$.ajax($url, {
success: function(data) {
getMoreData(); // call this when the original ajax call gets a response.
}
});
Without seeing your code it's hard to say if this is the right solution, but you should try chaining the functions:
$.ajax({url: yourUrl}).then(function (data) {
// deal with the response, do another ajax call here
}).then(function () {
// or do something here
});

javascript variable is not showing correct value [duplicate]

This question already has answers here:
How to add callback to AJAX variable assignment
(4 answers)
Closed 8 years ago.
i have this ajax call function.
function saveData(ip)
{
$JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
return newtoken;
}
}
});
}
Then i have another function
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
alert(mytoken);
}
My token giving undefined in alert.Although if i alert newtoken variable in savedata response it gives correct value in alert box.why if i return that avlue it does not assigned to mytoken.
is it something time delay issue.??
Need your help...
You cannot return from an asynchronous call.
You have to consume the return data inside the success function. Whatever you are going to do with token, write that code inside the success handler.
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
// Global variable
sourceid = newtoken;
return newtoken; // This won't work
}
}
Also
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip); // This won't return any data
alert(mytoken); // This won't give you anything useful
}
Hi friends This is solution that for i was looking.
function saveData(ip)
{
return $JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
async: false,
}).responseText;
}
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
return mytoken;
}
The first 'A' in AJAX is 'Asynchronous'. Your alert is running before the AJAX request has had a chance to complete. You need to handle whatever you wish to do with the response inside of the success: function() or .done() functions of jQuery:
success: function(responce)
{
if(responce)
{
var newtoken = responce;
// Work here with newtoken...
}
}

Javascript callback functions with ajax

I am writing a generic function that will be reused in multiple places in my script.
The function uses ajax (using jQuery library) so I want to somehow pass in a function (or lines of code) into this function to execute when ajax is complete.
I believe this needs to be a callback function, but after reading through a few callback answers I'm still a bit confused about how I would implement in my case.
My current function is:
function getNewENumber(parentENumber){
$.ajax({
type: "POST",
url: "get_new_e_number.php",
data: {project_number: projectNumber, parent_number: parentENumber},
success: function(returnValue){
console.log(returnValue);
return returnValue; //with return value excecute code
},
error: function(request,error) {
alert('An error occurred attempting to get new e-number');
// console.log(request, error);
}
});
}
With this function I want to be able to do something in the same way other jQuery functions work ie;
var parentENumber = E1-3;
getNewENumber(parentENumber, function(){
alert(//the number that is returned by getNewENumber);
});
Just give getNewENumber another parameter for the function, then use that as the callback.
// receive a function -----------------v
function getNewENumber( parentENumber, cb_func ){
$.ajax({
type: "POST",
url: "get_new_e_number.php",
data: {project_number: projectNumber, parent_number: parentENumber},
// ------v-------use it as the callback function
success: cb_func,
error: function(request,error) {
alert('An error occurred attempting to get new e-number');
// console.log(request, error);
}
});
}
var parentENumber = E1-3;
getNewENumber(parentENumber, function( returnValue ){
alert( returnValue );
});
#patrick dw's anwser is correct. But if you want to keep calling the console.log (or any other actions) always, no matter what the caller code function does, then you can add the callback (your new parameter) inside the success function you already have:
function getNewENumber(parentENumber, cb_func /* <--new param is here*/){
$.ajax({
type: "POST",
url: "get_new_e_number.php",
data: {project_number: projectNumber, parent_number: parentENumber},
success: function(returnValue){
console.log(returnValue);
cb_func(returnValue); // cb_func is called when returnValue is ready.
},
error: function(request,error) {
alert('An error occurred attempting to get new e-number');
// console.log(request, error);
}
});
}
And the calling code remains the same as yours except that the function will receive the returnValue by parameter:
var parentENumber = E1-3;
getNewENumber(parentENumber, function(val /* <--new param is here*/){
alert(val);
});
This would be better done with jQuery's Deferred Objects. Have your AJAX call return the jqXHR object.
function getNewENumber(parentENumber) {
return $.ajax( { ... } );
}
getNewENumber(E1 - 3).then(success_callback, error_callback);
If you want to keep the error callback within that function you can register that there instead:
function getNewENumber(parentENumber) {
var jqXHR = $.ajax( { ... } );
jqXHR.fail( ... );
return jqXHR;
}
getNewENumber(E1 - 3).done(success_callback);

Categories

Resources