AJAX not saving variables to javascript (asynchronous issues) - ajax

Why is alert saying that the text[0] is undefined?
This is my code:
var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
}
});
alert(text[0]);

var text = new Array;
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
success: function(rows){
text = rows;
alert(text[0]); // will work, this gets executed after you set text
}
});
//alert(text[0]); << don't put this here, it will get executed right after you send the request

Finally answered my own question, for anyone that comes across this question, here is what I did:
Because ajax is asynchronous, alert(text[0]) is getting executed before text=rows.
You can set ajax to run procedurally like this:
$.ajax({
url: 'engine1/api.php',
data: "",
dataType: 'json',
async: false;
success: function(rows){...
Apperently this is one of the few cases that you can/should set ajax to async:false (because you're serving javascript/jquery to the client).

Related

Variable loses some value when used in Ajax API Call

I have an issue that causes my variable “tempid” to lose some of its values when put into the second API call. As you can see from my image, if I log the variable to console (console.log(tempid)) it shows just fine. However, as soon as I place it in an API call it has some of the value but not all. Could you please help me by explaining why this would happen?
[console example][1]
$(document).ready(function() {
$.ajax({
url: "/api/Template/GetTemplates?classId=7ac62bd4-8fce-a150-3b40-16a39a61383d",
async:true,
dataType: 'json',
success: function(data) {
$(data).each(function (data) {
if (this.Name === "Name of Template"){
var tempid = this.Id
console.log (tempid)
var tempurl = "/api/V3/Projection/CreateProjectionByTemplate?id=" + tempid + "&createdById=703853d4-ffc4-fce3-3034-0b838d40c385"
$.ajax({
url: tempurl,
async: false,
dataType: 'json',
success: function(data) {
}
});
}
});
}
});
})
[1]: https://i.stack.imgur.com/gyesK.png
I found the answer, the console is just showing a shortened version of the URL and happened to cut off part of the tempid. Thank you

Ajax data collect in code lines

I did some admin panel in wordpress sheet but i'm adding options and have everything in one line in the data, it's pain if I keep adding options, works that way but it looks messy.
example
$.ajax({
type: 'POST',
url: ajaxurl,
data: 'action=general_settings_action&zkr_logo='+zkrlogo+'&zkr_favicon='+zkrfavicon+'&zkr_background='+zkrbackground+'&zkr_linkcolor='+zkrlinkcolor+'&zkr_linkhover='+zkrlinkhover+'&zkr_colorbackground='+zkrcolorbackground,
success: function(data){
alert(data);
}});
I would like to make some lines to that data field like for example
$.ajax({
type: 'POST',
url: ajaxurl,
data:
'action=general_settings_action&
zkr_logo='+zkrlogo+'&
zkr_favicon='+zkrfavicon+'&
zkr_background='+zkrbackground+'&
zkr_linkcolor='+zkrlinkcolor+'&
zkr_linkhover='+zkrlinkhover+'&
zkr_colorbackground='+zkrcolorbackground,
success: function(data){
alert(data);
}});
But putting the code like that doesn't work I have tried with \n and some other stuff but still wont do the work.
I apreciate the help... Thanks
Try doing this:
Make a JSON data object that contains the parameters you want to send
var DATA = {
action:'general_settings_action',
zkr_logo:zkrlogo,
zkr_favicon:zkrfavicon,
zkr_background:zkrbackground,
zkr_linkcolor:zkrlinkcolor,
zkr_linkhover:zkrlinkhover,
zkr_colorbackground:zkrcolorbackground
}
The send the data in your AJAX request using the data field
$.ajax({
type: 'POST',
url: ajaxurl,
data: DATA,
success: function(data){
alert(data);
}});
I checked this out at: David Walsh's guide
You need to add
'zkr_logo=' + zkrlogo + '' +
instead of
zkr_logo='+zkrlogo+'&
then it will form one String

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

Filling an array

My question is to fill an arrary with data from an ajax request. My ajax call receives the data fine and is logged n the console. What I'm having difficulty with is filling my array with that data. Here is my code.
$.ajax({
type: "GET",
url: WebRoot + "ws/GIS.asmx/CensusData",
data: d,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//loop through the data and pull out the fips codes
//alert("success");
fipsData = data;
console.log(fipsData);
} //ends success function
}); //ends ajax call
Just use JSON.parse() like this:
fipsData = JSON.parse(data);
and you should be good to go.

Chrome jquery ajax callback on success not firing

As far as I know, $.ajax has always worked pretty smoothly in every browser until now.
I have a pretty simple function, called when a couple of actions from the user occur.
In Firefox, everything runs smoothly. But in Chrome, while the $.ajax request is launched, the callback on success doesn't fire.
Here's the actual snippet:
var form = $("#templateCreator"),
formType = form.attr("method"),
formData = form.serialize(),
action = form.attr('action');
$.ajax({
type: formType,
url: action,
data: formData,
success: function(){
console.log('Can\'t see me in Chrome, but ok in firefox !')
// Handle all form submit events to form validator first
validator(form, targetInput);
}
});
What's puzzling is nothing seems wrong, data is serialized, and sent properly. Does anyone know what I missed?
Start by adding an error and complete method as #Jasper suggested.
$.ajax({
type: formType,
url: action,
data: formData,
success: function(){
console.log('Can\'t see me in Chrome, but ok in firefox !')
// Handle all form submit events to form validator first
validator(form, targetInput);
},
error: function() {
console.log($.makeArray(arguments));
},
complete: function() {
console.log($.makeArray(arguments));
}
});
Then you can:
open Chrome debugger (F12), go to the scripts tag, and put a breakpoint inside success/complete/error; check out the stack trace and values for an epiphany ;)
have a look at the console logs
For great joy, take off every Zig!
I had this issue, and set async: false. This works for me in Chrome. Looks like Chrome has an issue with async: true.
restget = function(url, cb){
$.ajax({
url: url,
dataType: 'json',
crossDomain: true,
async: false,
success: cb
});
Try this .....
data: formData,
async: false,
Chrome has some issues with async calls.
I had a similar problem while trying to get a json array. I had to add dataType: 'json' to my ajax so that non-Firefox browsers know what my data type is. For instance:
$.ajax({
type: 'Get',
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
success: function(data){
var jsonArray = jQuery.parseJSON(data);
alert(jsonArray.status.message);
}
});
and
$.ajax({
type: 'Get',
url: "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo",
dataType: 'json',
success: function(data){
var jsonArray = data;
alert(jsonArray.status.message);
}
});
will display the same thing when ran in Firefox firebug. But when you run this in Chrome DevTools it will only work on the bottom one. I hope this fixes your problem.

Resources