jquery ajax async stopped - javascript

i run the ajax request with async set to false inside the loop, and it stopped when the counter at 2. here is the script
var x = 0;
for(i=0; i<10; i++){
$.ajax({
async: false,
global: isGlobal,
type: 'POST',
url: url,
dataType: 'json',
data: JSON.stringify(body),
headers: {'Content-type':'application/json', 'Accept':'application/json'},
success: function(result){
x = result.something.value;
},
error: function(){
callback(false);
}
});
console.log(x); // debug x value
}
any idea why this is not working correctly?
PS: the url is cross domain

i solve this problem my self. here is the working script, in case you, visitor, have the same problem as mine.
var theList = [/*LIST GOES HERE*/];
var yourGlobalVar = '';
i = 0;
(function gcr(){
var body = {
ID: theList[i].ID
};
$.ajax({
async: false,
global: isGlobal,
type: 'POST',
url: url,
dataType: 'json',
data: JSON.stringify(body),
headers: {'Content-type':'application/json', 'Accept':'application/json'},
success: function(result){
yourGlobalVar += result.anything.value;
if(i < theList.length - 1){
// wait for the response then call itself
i++;
gcr();
}
}
});
})();

Related

Passing data with ajax and read it with Request.Form[""]

I try to pass parameters into aspx.cs page from js script. When I omit:
contentType: "application/json; charset=utf-8"
in ajax request I get by Request.Form["ORDER"] sth like {%7b%22ORDER_ID%22%3a126333%7d}. It means that this data comes to aspx.cs, but it is not decoded.
When I add contentType I get nothing in request.
Below I attach request.
It is important to read parameters from Request.Form["ORDER"] in aspx.cs;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ORDER_ID: orderKeyId }),
dataType: "json",
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});
According to #Rory McCrossan comment, below ajax state worked:
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: "ORDER_ID=" + encodeURIComponent(orderKeyId),
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});

Cant get value from ajax request to be save in variable outside the success

Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}

AJAX GET returns undefined on the first call, but works on the second one

I am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);

How to loop the ajax call for pdf file download?

if( $.isArray(certTypeReq) ){
$.each(certTypeReq,function(key,certType){
$.ajax({
url: baseUrl+"/user/certificate/getlink",
type: 'GET',
data: { 'certType' : certType},
dataType : 'json',
cache: false,
async:false,
success: function(data) {
window.location.href = data.link;
}
});
});
}
This is my code and its working fine in Firefox but not in chrome browser. If anyone has solution please help me.
var i=1;
if( $.isArray(certTypeReq) ){
$(certTypeReq).each(function(key,certType){
setTimeout(function () {
$.ajax({
url: baseUrl+"/user/certificate/getlink",
type: 'POST',
data: { 'certType' : certType},
dataType : 'json',
success: function(data) {
window.location.href = data.link;
}
});
}, 3000*i);
i++;
});
}
Applied delay in each iteration and it worked.
Thanks to all for your replies.

JSON.Parse causes error in javascript

I'm having some problems with JSON.Parse in my code and I cant find the reason of this I have a function which call two ajax functions, one on the start and another on the success function . Its working fine but when I'm try to parse the second one response the code breaks without giving any error and the real mystery is JSON.parse(object); dosent give any problem but when I use a variable to store the result like this var list =JSON.parse(object); my code broke and I dont what is the reason behind this my current code is given below
function getData()
{
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData",
data: JSON.stringify({ data: data})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = JSON.parse(response.d);
var temp = 0;
for (var i = 0; i < result.length; i++) {
if (result[i].data > 1) {
var subList = JSON.parsegetFullData (result[i].id));
}
}
});
}
function getFullData (id) {
var sublist;
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData2",
data: JSON.stringify({ id: id }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
return response.d;
}
});
}
any thought will help a lot
When you use $.ajax with dataType:"json", the response is already parsed for you. And there doesn't seem to be a reason to try to parse response.d.
Simply use
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData",
data: JSON.stringify({ data: data})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
for (var i = 0; i < results.length; i++) {
console.log(results[i].id, results[i].LastName);

Categories

Resources