How call a callback of an Ajax function in another function - javascript

I have an Ajax function which is loading data from a webservice. It looks like this:
$.ajax({
type: 'POST',
url: back + this.path_Uri,
data: {msg:this.msg},
dataType: "json",
success: function (data, statut) {
// traitement to not execute here
window.reloadFreelancersMission= data;
var number = reloadFreelancersMission.pagination[0].pagenbr;
window.pagination.ReloadPager(number);
/////////////////////////////////////////////////
},
error: function (data) {
console.log(data);
}
});
I need to do some treatment in the result of the response of this web service in another function in another file.
My file contains a function of sending data within my ajax function. It looks like this
sendFiltres: function () {
$("body").on('change', '.filtres' , function () {
var choix_filtres = $("#fitre_recherche");
var msgJson = JSON.stringify(serializeObject($("#fitre_recherche")));
window.sendData.start(choix_filtres,msgJson);
})
},
So I need here to use the callback of my function in this way:
request.done(function( msg ) {
console.log( msg );
});
and integrate my treatment, to obtain this for:
request.done(function( msg ) {
window.reloadFreelancersMission= data;
var number = reloadFreelancersMission.pagination[0].pagenbr;
window.pagination.ReloadPager(number);
});
but it seems that I can't call this callback in this file. I'm allowed to use it only in the same file of my ajax function, and that's exactly my problem.

In my case, I resolved my problem by recuperating the response of my service within the callback function of jQuery ajaxSuccess
$(document).ajaxSuccess(function (event, xhr, settings) {
if (settings.url === window.find_mission.route.getmission || settings.url === window.find_freelance.route.getfreelance) {
xhr = xhr.responseJSON;
var pagenumber = xhr.pagination[0].pagenbr;
window.pagination.ReloadPager(pagenumber);
}
});
where I was using the xhr variable to get my data.

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 force $.getJSON to run before $http in Javascript?

I have the following Javascript code in the controller of my web page.
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
});
$http({
method: 'GET',
url: $scope.properties.Properties.dataLocation
}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
The structure of the json file to be fetched is not the problem.
It is supposed to first run the $.getJSON command and afterwards run the $http-request, since the $http request gets its url from the variable that is defined in the $.getJSON part at the top but instead when i do a console.log(properties) just below it, it spits out "undefined".
Why is the code not executing in the order that it is written?
The code is executing in order that it's written, just callback functions are being executed when the corresponding requests are complete. So you should put the second call in the first callback:
$.getJSON('resources/properties/properties.json', function(data) {
$scope.properties = data;
$http({method: 'GET', url: $scope.properties.Properties.dataLocation}).
success(function (data) {
$scope.all_types_and_configs = data;
$scope.exec = [];
}).
error(function (data) {
$scope.error = data.message;
$scope.data = '';
return;
});
});
});
It is executed asynchronous so both call will be done independantly.
$.getJSON has third parameter - success callback this is the way to sync those.
http://api.jquery.com/jquery.getjson/
Not sure why you are mixing jQuery AJAX and Angular $http ?
You could use the JQuery.done, which will execute your code after your request has finished.
Example:
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
The same way that you have already got the line $scope.properties = data; to run after the JSON has been received. You put it in the callback function you pass to getJSON.
Why is the code not executing in the order that it is written?
It is.
getJSON(url, foo) means "Make an HTTP request to the url and set up an event handler to call foo when the response is received".
You seem to be expecting it to wait for the response before doing anything else. That would lock up the UI and be horrible.

Get data back from ajax call within ajax call

I'm need some help figuring out how to get back data from the second ajax call, not the first.
I have this method that calls my ajax calls
var projectWithIssues = getProjects().done(function(result) {
....
}
When I look at the results from this, I get back the results on my first ajax call(getEnt_PodType().done()). I want to get the results from the second ajax call within getProjects(). I understand the reason I'm getting the first results back is because I have the return on the first ajax call. However, If I don't have a return there. I get a undefined on the line above. How can I return the data from the second call?
function getEnt_PodType() {
var ent_PodType;
var oDataUrl = //URL to my data;
return $.ajax({
url: oDataUrl,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
}
});
}
function getProjects() {
return getEnt_PodType().done(function (res) {
var ent_PodType;
if (res.d.results != undefined) {
ent_PodType = res.d.results[0].Ent_PodType;
}
console.log("The ent pod type value is " + ent_PodType);
var QUERY_FILTER =
"$filter=Ent_PodType eq '" + ent_PodType + "'";
var url = restUrl + QUERY_FILTER;
// I want to return the results from this ajax call
$.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
//projects = parseODataResultTest(xhr);
//return projects;
}
});
});
}
Thanks in advance!
Try utilizing pattern found at deferred.then
// first request
var request = $.ajax(url1),
chained = request.then(function( data ) {
console.log(data) // first request response data
// return second request
return $.ajax(url2)
});
chained.then(function( data ) {
console.log(data) // second request response data
// data retrieved from url2 as provided by the first request
});
var request = $.ajax("https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/ticker.json"), // first request , `html` document
chained = request.then(function( data ) {
console.log(data) // `["abc"]`
// return `data` from second request
return $.ajax("https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/49fbc054731540fa68b565e398d3574fde7366e9/abc.txt")
});
chained.then(function( data ) {
console.log(data) // `abc123`
// data retrieved from url2 as provided by the first request
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Use .then instead of .done, it allows better chaining of functions.
Break your code apart so that the two AJAX calls are in separate functions, and have both those functions return the result of their $.ajax call. You can then use:
func1().then(func2).then(...);
func2 will be passed the result of the first AJAX call, and then the result of that will be passed to whatever function is in the final then.
In your case you can also put the call to parseODataResultTest in the chain and then the final function will (eventually) be called with the required data, i.e.:
getEnt_PodType().then(getProjects).then(parseODataResultTest).then(function(projects) {
// use projects here, and _only_ here because it won't
// be in scope or defined anywhere else
...
});

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 and order of execution of functions

My Class looks like
function classUser() {
var userName;
var firstName;
var lastName;
var sessionid;
}
classUser.prototype.set_user_name = function (user_name) {
this.userName = user_name;
}
classUser.prototype.set_first_name = function (first_name) {
this.firstName = first_name;
}
classUser.prototype.set_last_name = function (last_name) {
this.lastName = last_name;
}
classUser.prototype.get_curr_session = function () {
return this.sessionid;
}
classUser.prototype.save = function () {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
}
});
}
I call them as
var User = new classUser();
User.set_first_name(userFirstName);
User.set_last_name(response.last_name);
User.set_user_name(response.username);
User.save();
var currSessionID = User.get_curr_session();
Sometimes, get_curr_session is called before success: call.
Question :
I tried returning sessionid from success itself so that save() function does the job. That is not working. hence i split across 2 functions.
Can I do it in one call itself? if I have use 2 functions - how do i make sure that it works all the time.
I could actually put assigning the currSessionID within success, however that breaks class sanctity. I have seen other solution like using "done", not sure if that would help here.
=======================================
I modified the code as below
classUser.prototype.save = function (callback) {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
callback(null, currSessionID);
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
callback("error", null);
}
});
}
When I call
User.save(mycallback);
function mycallback(error, sessId){
if(error) {
console.log("Some error occurred. Check code");
return;// Something went wrong
} else {
console.log("Session : " + sessId);
}
}
Is this good now?
Thanks
Ajay
That's because the success and error function of the ajax request are executed asynchronously.
To make sure this doesn't happen, you should add a callback to your save function that is called after the success or error functions ran.
classUser.prototype.save = function (callback) {
$.ajax({
type: "POST",
url: "http://myapihost.com:8080/api/1.0/user/",
data: JSON.stringify(this),
dataType: "json",
success: function (apiResponse) {
var currSessionID = apiResponse.sessionId;
this.sessionid= currSessionID;
callback(null, currSessionID);
},
error: function (apiResponse) {
alert("error : " + apiResponse);
this.sessionid= "Error";
callback(apiResponse, null);
}
});
}
Then, when calling the save function, you can do something like this:
User.save(function(error, sessId) {
if(error) {
// Something went wrong
} else {
// Do whatever you need to do
}
});
You should note that this will also run asynchronously. So if you want to work with the session ID, don't do that after the User.save(...) call, but inside the function.
$.ajax() issues an asynchronous call to the url specified in the options object. See the jQuery documentation at http://api.jquery.com/jQuery.ajax/
success is a callback function that is invoked when the call is completed and all the response stream is read by the browser so basically in most of the cases the callback (updating the session id) will execute after you try to retrieve it.
I think what is happening here is that the default ajax call is async which means that the code var currSessionID = User.get_curr_session(); can execute before the success call completes.
You have a couple of options, you can try and update your code to be more async capable, using callbacks or other methods, or specify that you want your ajax call to be synchronous.

Categories

Resources