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

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)

Related

How to express != in URLs

I wrote the following ajax call to fetch data using the nb (number of document view) parameter:
if ($("#fetch").hasClass("active")) {
$.ajax({
url: "ServletAjaxController",
type: "POST",
dataType: "json",
data: "c=" + controller + "&nb=300",
success: onSuccess,
contentType: "application/x-www-form-urlencoded;charset=UTF-8"
});
}
Now I want to do the same thing but expressing nb != 300 instead of the equal expression. Any IDEAs?

Codes raises exception '[specific_method] is not defined'

I've got following javascript code. It's simply class, that should receive some data from REST WCF client.
class EmployeesWcfClient {
constructor(url) {
if (url == null) {
url = "http://localhost:35798/MyCompanyService.svc/";
}
this.url = url;
}
doGetRequest(relUrl) {
return $.ajax({
type: 'GET',
contentType: 'json',
dataType: 'json',
url: this.url + relUrl,
async: false
});
}
doPostRequest(relUrl, data) {
return $.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
url: this.url + relUrl,
async: false
});
}
getEmployees() {
return doGetRequest('Employees');
}
}
And I don't know why it's raises exception: 'doGetRequest is not defined'. Could someone help?
The answer is simple:
Use this operator in 'return this.doGetRequest('Employees');'. In first code example the this operator was missing.
inside ajax of doGetRequest the this.url will not refer to EmployeesWcfClient.url, instead it will point to the ajax options object itself. So take the reference of this before calling ajax request.
doGetRequest(relUrl) {
var _this = this;
return $.ajax({
type: 'GET',
contentType: 'json',
dataType: 'json',
url: _this.url + relUrl,
async: false
});
}
But I am not sure returning this ajax function will exactly return you the response from the request though you made it async: false. Better use callbacks or promise.

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) {
...
}
});

Jquery - Calling a ajax function within ajax function

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

Ajax passing null value to controller

I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.

Categories

Resources