Calling ajax inside of ajax - javascript

I'm trying to make an ajax call that gets a type of a property. Using that type I then pass it into another ajax call. I'm having some difficulty doing this asynchronously because I'm trying to defer til the first property is loaded.
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) {
var res = xhr;
if (res.d.results != undefined) {
ent_PodType = res.d.results[0].Ent_PodType;
}
console.log("The ent pod type value is "+ ent_PodType);
return ent_PodType;
}
});
}
function getProjects() {
var QUERY_FILTER = getEnt_PodType().done(function (result) {
"$filter=Ent_PodType eq '" + result + "'";
});
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
}
When I call the getProjects(), I thought building the url would wait for getEnt_PodType() to return its value but it doesn't seem to work that way.
Instead it goes ahead and executes the rest of getProjects(). Is there any way to do this asynchronously?

Your second ajax call need to be placed inside done promise. You can wrap rest of your code in local function and call it inside done, like so:
function getProjects() {
function getProjectsViaAjax(){
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
}; // end of getProjectsViaAjax
var QUERY_FILTER = getEnt_PodType().done(function (result) {
"$filter=Ent_PodType eq '" + result + "'";
getProjectsViaAjax();
});
}

AJAX is asynchronous. Anything that depends on the result must be done in the callback function.
I also recommend always passing the parameters as an object, to allow jQuery to encode it properly.
function getProjects() {
getEnt_PodType().done(function (result) {
var QUERY_FILTER = { "$filter": "Ent_PodType eq '" + result + "'"};
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: restUrl,
data: QUERY_FILTER,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
});
}

The ajax call needs to be in the done promise. Something like the following should be ok.
function getProjects() {
return getEnt_PodType().done(function (result) {
var QUERY_FILTER = "$filter=Ent_PodType eq '" + result + "'";
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
async: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
});
}

For this to work you need to call the second code from the success function of first code.Or you put the code in a function and call that function from the success callback of first ajax call.Using .done calllback is more appropriate.So call second function from done callback of first ajax call.
function getProjects() {
return getEnt_PodType().done(function (result) {
var QUERY_FILTER = "$filter=Ent_PodType eq '" + result + "'";
var url = restUrl + QUERY_FILTER;
console.log("The url form getProjects is " + QUERY_FILTER);
return $.ajax({
url: url,
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("ACCEPT", accept);
},
success: function (xhr, textStatus) {
projects = parseODataResultTest(xhr);
return projects;
}
});
});
}

You need to call one function synchronously, because second task is depends on first task.
You can call function getEnt_PodType synchronously, you need to make
async: false in this function.
And then it will work as you expected.

Related

calling a function on complete of multiple ajax events

So say i have multiple ajax requests that are fired at the same time through a parent function. Each ajax function has a seperate individual completion function which are unrelated to each other. If i want a further function to execute upon completion of all ajax functions, but after the completion functions specified in each individual ajax function, how would i go about this?
function ajax1(str) {
return $.ajax({
type: 'get',
data: "q=" + str,
url: 'foo.php',
success: function (result) {
//success!
}
},
complete: function (data) {
function ajaxcomplete1();
},
)
};
function ajax2(str) {
return $.ajax({
type: 'get',
data: "q=" + str,
url: 'foo.php',
success: function (result) {
//success!
}
},
complete: function (data) {
function ajaxcomplete2();
},
)
};
function ajaxcall() {
ajax1();
ajax2();
}
function allajaxcomplete() {
// some code to be executed on completion of all ajax requests but after individual "ajaxcomplete1" and "ajaxcomplete2" functions
}
ajaxcall();
allajaxcomplete();
$.ajax returns a jQuery Deferred object (a promise). You then just have to use $.when to call a function when all those promises are resolved:
function ajax1(str) {
return $.ajax({
type: 'get',
data: "q=" + str,
url: 'foo.php',
success: function (result) {
//success!
ajaxcomplete1();
}
});
};
function ajax2(str) {
return $.ajax({
type: 'get',
data: "q=" + str,
url: 'foo.php',
success: function (result) {
//success!
ajaxcomplete2();
}
});
};
function ajaxcall() {
// store the promises (for clarity, you also could call the functions directly in the when)
var d1 = ajax1(),
d2 = ajax2();
// this function will be called only when both promises d1 and d2 are resolved
$.when(d1, d2).done(function(result1, result2){
// do stuff when both functions are done
// result1 and result2 are the result of the ajax calls inside your functions
allajaxcomplete();
});
}

jsCall return value to outside of jquery ajax post request

I want to get jquery ajax post request value to outside from the ajax function. my code is this and it return undefined as console output. How should fix it
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.post(urlForPhp + '/' + url, formData, function (outputData) {
output = outputData;
});
return output;
}
Edited
I changed my code to sync type ajax post request and check output. But it is not changed. here my code
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
output = e;
}
});
return output;
}
You can use Deferred jQuery
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole').then(function (outputFromAjax) {
console.log(outputFromAjax);
});
}
function submitViaPost(url) {
var dfd = jQuery.Deferred();
var formData = $('form').serializeArray();
$.post(urlForPhp + '/' + url, formData, function (outputData) {
dfd.resolve(outputData);;
});
return dfd;
}
Don't return , make it a callback as $.post is async
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole', function(out){ //Result comes here
var outputFromAjax = out;
console.log(outputFromAjax);
});
}
function submitViaPost(url , callback) { //Added callback
var formData = $('form').serializeArray();
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
callback(e);
}
});
}

still not call with ajax in separate javascript file

I am new in jquery and ajax but my requirement is calling servlet/jsp through ajax using jquery so that my ajax code dosen't work in separate javascript file
Here is my javascript file that I called ajax through jquery :
function insertData(idvalue)
{
var forsplit = idvalue.id.split("_");
var qtsrl = forsplit[2];
var qtno = forsplit[3];
alert(qtsrl);
alert(qtno);
var queryid=idvalue.id;
var qtsrl_id = document.getElementById("qstn_srl_"+qtsrl+"_"+qtno).value;
var qstn_no_id = document.getElementById("qstn_no_"+qtsrl+"_"+qtno).value;
alert(qtsrl_id);
alert(qstn_no_id);
$.ajax(
{
url: "aftermarksave.jsp",
type: "get",
data:{setvalues : queryid},
dataType: "JSON",
success: function(data)
{
alert('Successful :'+data);
},
error: function(data)
{
alert('Not Successful: '+data);
}
});
}
Still not call to jsp page and I tried for Servlet page also that servlet is not called through ajax.
Try Like
$.ajax({
url: "URL",
type: "GET",
contentType: "application/json;charset=utf-8",
data: {setvalues : queryid},
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
OR
$.get("URL",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});

function calling ajax returns false

I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}

jQuery $.ajax(), pass success data into separate function

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
I am wanting this to be the same as:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}
Works fine for me:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
In the first code block, you're never using the str parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};

Categories

Resources