This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
Im retriving data from my php and its working fine , the problem is that
var myData is getting cached and only updates if i refesh my page 2 times...
on my firebug i can see the post updates but when i `console.log(myData);the data is the old one ..until i refresh..
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
}
});
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
You're probably trying to set and read mydata before the request/response is complete. Instead, move that into your success callback.
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
}
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have this script for submitting a form using jquery ajax, everything works fine except i can only get two responses, the loading part is implemented but the rest of them i can only get the else statement. the else if, none is working.
the json statement works just fine. and the data is passed to php successfully but the responses are not according.
(function($) {
'use strict';
const FormFunction = function(){
const checkSelectorExistence = function(selectorName) {
if(jQuery(selectorName).length > 0){return true;}else{return false;}
};
let registerForm = function() {
if(!checkSelectorExistence('.registration-form')){return;}
jQuery('.registration-form').on('submit', function( event ) {
event.preventDefault();
let response = $('.loading').addClass('show').show();
jQuery(this).find(".message").addClass('active').show('slow');
const formData = new FormData(this);
const formAction = jQuery(this).attr('action');
jQuery.ajax({
type: 'POST',
url: formAction,
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: 'json',
beforeSend : function(){
$('.info').addClass('show').show('slow');
},
complete : function(){
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
success : function(data)
{
if(data.status === 1){
response = $('.success').addClass('show').show('slow');
}
else if(data.status === 2) {
response = $('.taken').addClass('show').show('slow');
}
else if(data.status === 0){
response = $('.empty').addClass('show').show('slow');
}
else {
response = $('.error').addClass('show').show('slow');
}
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
error : function(data){
$('.error').addClass('show').show('slow');
$('.registration-form')[0].reset();
},
});
});
}
/* Functions Calling */
return {
afterLoadThePage:function(){
registerForm();
},
}
}(jQuery);
/* jQuery Window Load */
jQuery(window).on("load", function (e) {FormFunction.afterLoadThePage();});
})(jQuery);
Based on some comments that we traded I managed to test it out and found out, what is the root of your problem. Even thought you are setting dataType as JSON, what you actually pass from PHP is a string of value "{\"status\":1}". This is currently the content of your data variable in Success function of your AJAX call.
Adding following line of code at begging of your Success function will do what you want it to do: data = JSON.parse(data);. This will parse string returned by PHP into an JSON object in JS which will create data.status instance holding desired value of number type.
I did some test on my end and it worked as expected with IF and ELSE IF as well.
This question already has answers here:
Javascript POST not working - Sending Javascript array to PHP
(4 answers)
Closed 4 years ago.
Trying to have data passed to a php script so the said data can be added to the session.
The debug console log returns are the following:
the quant array is correct and typeof is object, the JSON.stringified data's type is string , lastly success from the ajax success.
In the PHP script var_dump return is NULL
$('#bigsubmit').click(function() {
var quant = [];
$('.input-number').each(function() {
var tmp = {};
tmp.id = this.id;
tmp.qu = $(this).val();
quant.push(tmp);
});
console.log(quant);
var data = JSON.stringify(quant);
console.log(typeof(data));
$.ajax({
type: "POST",
url: url,
data: {
data: data
},
success: function() {
console.log("success");
}
});
the php script (url var)
<?php
session_start();
$_SESSION['test'] = $_POST['data'];
var_dump($_SESSION['test']);
?>
Your success callback function isn't taking in a parameter, try changing to this,
success:function(data) {
console.log(data);
}
This question already has answers here:
AJAX not updating variable
(5 answers)
Closed 5 years ago.
I have the javascript code below that POSTs a request, I then want to save the response to a local variable named sku, but it is not binding.
the variable sku remains an empty string.
var sku = ""; //to be passed to server when filled
var cookie_info = {
number_nights: number_nights_cookie,
number_travelers: number_travelers_cookie,
type_traveler: type_traveler_cookie,
departure_date: departure_date_cookie,
country: country_cookie
};
$.ajax({
type: 'POST',
url: 'https://azooree.com/wp-admin/php/sku-calculation.php',
data: cookie_info,
success: function(response) {
console.log('success', response);
sku = response;
},
error: function() {
console.log('error!');
alert("[ERROR] Information lost, please try again. Thank you!");
}
});
var basic = {
info: sku + "LP"
};
The value of variable sku is being returned from your POST request which is asynchronous. That's why at the time of assigning the value of sku to basic - it will be empty.
You can easily update the value of basic either by using a callback function like below-
$.ajax({
type: 'POST',
url: 'https://azooree.com/wp-admin/php/sku-calculation.php',
data: cookie_info,
success: function(response) {
console.log('success', response);
sku = response;
updateBasicValue(sku);
},
error: function() {
console.log('error!');
alert("[ERROR] Information lost, please try again. Thank you!");
}
});
function updateBasicValue(sku) {
basic = {
info: sku+"LP"
};
}
Or else, you can do whatever you need to do with the sku variable inside the success function of your AJAX request.
UPDATE
You also need to check for CORS issues if your request is being sent from any other domain or subdomain different than the one causing it. - (Thanks LordNeo)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have an ajax getting values from db, and the result is pushed into an array:
function pushPONFail(dt, ct) {
if (ct < 12) {
var tMon = parseInt(dt.getMonth())+1;
var tYear = dt.getFullYear();
ct++;
} else {
return;
}
data = {"qType": 101,
"tbl": 'qualitypqa.dbo.centerthickness',
"month": tMon,
"year": tYear,
"type": 'Lotrafilcon B'};
$.ajax({
cache : false,
url: "getrpt.php",
type: "get",
data: data,
contentType: 'application/json; charset=utf-8',
async: true,
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error: "+textStatus+" : "+errorThrown);
}
})
.done(function(response){
var obj = jQuery.parseJSON(JSON.stringify(response));
arrPONFail.push({Month: months[tMon-1]+"/"+tYear, PONFail: obj[0].PONFail});
dt = new Date(dt.setMonth(parseInt(dt.getMonth()) - 1));
pushPONFail(dt, ct);
});
} // pushing values such as ["May/2017", 0]
$(function() {
var dt = new Date();
pushPONFail(dt, 0);
console.log(arrPONFail);
});
These are the complete function. When I console.log the array, it came out as my picture. I'm unable to extract the data.
When I print the array into the console, it came out as the picture below.
How do I get the values back out from the array?
When I do an arrT[0], I get an undefined.
Please advise.
This is most likely an asynchronous issue - are you accessing arrT[0] outside of the .done() function? If so, at the time you're accessing it, there is nothing in the array - it's empty. The ajax request you're making takes some time (milliseconds), and only after that data returns does your array have something in it. To use the values in the array, try putting the code that uses the array inside the .done() function itself.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I want to read the (images) files name inside a specific folder and then to preview images in Krajee Bootstrap FileInput (FileInput demo link) .
I have a problem with this code in javascript:
var initialPreviewArray = [];
var j = [];
$.ajax({
type: "POST",
url: "my_gallery_ajax.php?",
async: "FALSE",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert('ok');
$.each(data, function(i,filename) {
j[i] = filename;
initialPreviewArray.push("<img id='"+i+"' src='user_1/'"+j[i]+"'>");
});
alert(j[2]); // test - is working - value: '11.jpg'
}
});
alert(j[2]); // test - not working - value: 'undefined'
My goal is to fill 'initialPreviewArray' with data from AJAX, inside or outside.
Inside 'AJAX call' initialPreviewArray.push is not working, even with specific value (outside AJAX is working):
initialPreviewArray.push("<img style='height: 50px' id='1' src='user_1/1.jpg'>");
Conclusion: I am not able to get data outside AJAX.