Jquery - Calling a ajax function within ajax function - javascript

Can I use ajax function withing a ajax function.
In my case there are two ajax calls. First ajax will return some data , If it is successful then the second ajax should be called .
Below is my code snippet,
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here"
dataType = "json",
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
Some more info :
I had checked chrome dev console and the error I am getting is
//success - 1
success: function(data) {
//Error message : Uncaught SyntaxError: Unexpected identifier
That was the error message I got.
And yes I cleared the syntactical mistakes and I was getting the same error message.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "my service url here",
dataType : "json"
//success - 1
success: function(data) {
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
$.ajax({
alert('inside ajax-2');
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function(data) {
//some functionality
} //success-2
} //success-1
}); //ajax - 2
}); //ajax - 1
I checked the service URL in RESTClient extension of firefox browser and again yes , there is Jsondata coming from that service.
Any good suggestion will be highly appreciable
Merry Christmas :)

There are some errors in your scripts.
In the first ajax call, where are the commas to separate the members ?
url:"my service url here",
dataType= "json",
and this should be:
dataType : "json",
Going back to your answer, yes you can but, what if you had the third ajax call?
Your code would be a mess and really hard to read.
The best would be to use promises.
This is the best way to work with asynchronous in javascript (that's also the reason why I've commented your async:false ).
You can read how promises work here.
$.ajax already returns a promise:
var promise = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url:"my service url here",
dataType: "json",
});
which could be chained with another one:
promise.then(function(result){ });
I tend to prefer the approach where I split my ajax call in different function which create a new promise and return it; just in case I want to manipulate the result:
You can split the two ajax calls:
function FirstAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
// async : false,
url:"my service url here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
and
function SecondAjaxCall()
{
var deferred = $.Deferred();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
// async:false,
url: "my second service URL here",
dataType: "json",
success: function (jsonData) {
deferred.resolve(jsonData);
},
error: function (req, status, error) {
var errorMessage = (error.message) ? error.message : error;
deferred.reject(errorMessage);
}
});
return deferred.promise();
}
Now you could resolve the first one and chain the second one:
FirstAjaxCall()
.then(function(result){
return SecondAjaxCall(result);
})
.then(function(result){
// final result
})
.fail(function(reason){
// reason should contain the error.
});
As you can see FirstAjaxCall() is resolve in the .then() branch and it passes it's result in the anonymous function. Same thing happens with the second ajax call SecondAjaxCall(). If something fails in the first or the second call the errors are trapped here:
.fail(function(reason){
// reason should contain the error.
});
The beauty of promises is you can chain them or execute them in parallel.

Yes you can.
Something wrong in your code that I can see is that }//success-1 is before });//ajax - 2 and it should be after.
also there is a missing coma ( ,) after url:"my service url here",
replace the '=' you have by ':' for your two dataTypes.
your should correct that and try again.

Try something like below in a structured way:
//First method with callback
function myFirstCall(callback) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here",
dataType= "json",
success:function(data){
callback();
});
}
// Second method
function mySecondCall() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my second service url here",
dataType= "json",
success:function(data){
});
}
//Let's trigger it
myFirstCall(function() {
mySecondCall();
});

You have to change "=" after the first "dataType" to ":"
dataType= "json", => dataType : "json",
and move "alert" function to the outside the second $ajax block.
$.ajax({ => alert('inside ajax-2');
alert('inside ajax-2'); $.ajax({
Last, order of closing brackets are opposite.
}//success-1 => });//ajax - 2
});//ajax - 2 }//success-1
The following code should work as you thought.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async:false,
url:"my service url here"
dataType : "json",
//success - 1
success:function(data){
//I ll collect the data from service
//now the second ajax must run.
//Because in first call I ll receive some data
//That data I going to use in my second call
alert('inside ajax-2');
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "my second service URL here",
dataType: "json",
//success - 2
success: function (data) {
//some functionality
}//success-2
});//ajax - 2
}//success-1
});//ajax - 1

Related

Returns error when consuming this php response

Return error in the query
From the browser the answer is correct.
$.ajax({
type: "POST",
url: url,
async: true,
contentType: " charset=utf-8",
dataType: "XMLHttpRequest",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});
The message says "error".
I see three issues. First, dataType is a choice of xml, json, script, or html, unless you did something really fancy. jQuery can guess it based on received data though, so there is normally no need to set it. But if you want to be explicit (assuming your page returns json):
dataType: "json"
Second, contentType value looks like some truncated thing. I would just completely remove it, as you are not sending any data and just requesting a page.
Finally, when you are sending no data and just requesting a resource, the best is to use GET.
All in all:
$.ajax({
type: "GET",
url: url,
async: true,
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});

How to call one ajax inside other ajax in a chained manner?

How to call multiple ajax calls one after another in a chained way?
Hi,
I am having a controller method which returns json based on the start limit and end limit which needs to done by ajax call.
So, initially in first ajax call start limit =1 and end limit=100 and on success of this ajax, same ajax call should be called with updated start limit =101 and end limit=200.
Like wise multiple ajax reuqests needs to be sent till actual dead line of 1000 i reached.
So totatlly 10 ajax calls from 1-100,101-200,201-300 e.t.c till 1000 have to be sent.
Actually i am sending these chained ajax;s this way,
$.ajax({
url: getdata/100/200",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//2nd ajax
$.ajax({
url: getdata/101/201",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
//some logic
//3rd ajax
$.ajax({
url: getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
}
}
But all the time only my first ajax is getting success and rest of the ajax;s are not getting executed and giving 404 error.
Is there any timeinterval needs to be set for calling one ajax inside?
What is the mistake i am doing here..?
can anyone help me in this issue?
Thanks
You can solve these issue by using function like following :-
// Make initial call to function with your data
myAjaxCall(data, 1, 100);
function myAjaxCall(data, startLimit, endLimit)
{
$.ajax({
url: "getdata/"+startLimit+"/"+endLimit, // Concat variables as per your codes
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(data) {
json=JSON.stringify(data);
console.log("json" + json);
console.log(JSON.stringify(data));
if(json != null && json != "") {
myAjaxCall(data, endLimit+1, endLimit+100);
}
}
});
}
If you need to chain Ajax call try to use Jquery.Deferred
it will looks like:
$.when($.ajax(...)).then($.ajax(..)) ...
You can achive this by recursive function
function ajaxRun(data){
$.ajax({
url: "getdata/201/301",
type: "GET",
contentType: "application/json",
dataType: "json",
global: false,
data: JSON.stringify(data),
async: false,
success: function(resultData) {
json=JSON.stringify(resultData);
console.log("json" + json);
console.log(JSON.stringify(resultData));
if(json != null && json != "") {
ajaxRun(data);
}
}
});
}
Hello change your parameter name every ajax success method like
success: function(resultData)
second time
success: function(secondresultData)

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

How do I debug Jquery Success function

I am using Javascript to get records from the database, everything works the way i want but i cannot show alerts in success handler. When i place a break point to sucess:function(data) it gets hit but this line is not being hit $("#Alert").html(data).show().... Another unusually thing i have noticed is that some time $("#Alert").html(data).show().. gets hit. Is there any way i can debug this?
function MethodNAme() {
ajReq.abort();
ajReq = $.ajax({
type: "POST",
url: "Services/",
data: ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
getSomething();
$("#Alert").html(data).show().delay(5000).fadeOut();
alert("working");
}
}
your syntax is not correct, you are placing a function getSomething() in middle of $.ajax(),
function MethodNAme() {
ajReq.abort();
ajReq = $.ajax({
type: "POST",
url: "Services/",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
// getSomething(); <-- remove this
success: function (data) {
$("#Alert").html(data).show().delay(5000).fadeOut();
alert("working");
}
});
}
You can use console.log() to print data in browser console. You can access console window by pressing F12 key and then go to console tab.

jquery Post , data object

I try to understand one thing.
I want to post an object with jquery Ajax POST , something like this:
var dataPostYear = {
viewType:GetViewType(),
viewDate:'2009/09/08',
languageId:GetLanguageId()
};
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
and it doesn't work.
But this one works fine:
var dataPostYear = "{viewType:'"+ GetViewType() + "',viewDate:'2009/09/08',languageId:'"+GetLanguageId()+"}";
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
GetViewType() return --'0'
languageId() return --'1'
it's just a string
there is a way to post an object, something what I try to do in my first way ? Or not ?
Thanks
Use jQuery.param(). Here is the documentation
You should look at .postJSON.
Essentially, you just add json as a 4th argument to the $.post
From the site:
// Send the request
$.post('script.php', data, function(response) {
// Do something with the request
}, 'json');
If you want the .ajax call version, you can convert it using the .post docs.

Categories

Resources