javascript cannot set value inside ajax [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a question about $.ajax in javascript:
If I have a function like this:
var jQueryFunction = function()
{
var array = new Array();
...
$.ajax ({
type: "GET",
async: false,
url: TPS_URL_1,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
array[0] = 1;
array[1] = 2;
}
});
}
After that when I check array value, it isn't set by anything and still null.
However I do like this:
var jQueryFunction = function()
{
var array = new Array();
array[0] = 1;
array[1] = 2;
...
$.ajax ({
...
});
}
It works fine.
So why I cannot set value for array inside $.ajax?

The line $.ajax({...}) is the equivalent of
var obj = {...};
$.ajax(obj);
The statement array[0] = 1 is not something that can be placed inside a object declaration like that (ie the code var obj = {array[0]=1} is not valid), thus the code you've posted is invalid (it throws a SyntaxError)
If you want to set these array elements AFTER the ajax returns, you should use the success callback:
$.ajax({url: ...,
success: function(returnData) {
array[0] = 1;
}
});

Try with:
Simple:
var setup = {
url : 'index.php',
dataType : "json",
type : "post",
data : {
time : "now"
},
success : function(response)
{
console.log( response ) ;
}
};
$.ajax( setup );
API( ajaxSetup ):
$.ajaxSetup({
url : 'index.php',
dataType : "json",
type : "post",
success : function(response)
{
console.log( response ) ;
}
});
$.ajax({
data:{
time : "now"
}
});

Related

Display returned JSON [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
Im having an issue being able to access the returned object and getting it to display. It is cross domain so I am using jsonp, but can't seem to access the returned object and I don't know why.
$(function(){
var API = "https://ratesjson.fxcm.com/DataDisplayer";
$.ajax({
url: API,
dataType: 'jsonp',
crossDomain: true,
success:function( msg ) {
var Symbol = msg.Rates.Symbol;
console.log("Symbol: " +Symbol);
}
});
});
The data looks like this, and I have no control over how it is formatted or returned:
jQuery1102016139126126654446_1458048453204({"Rates":[{"Symbol":"EURAUD","Bid":"1.48741","Ask":"1.48751","Spread":"1.00","ProductType":"1",},{"Symbol":"Copper","Bid":"2.23","Ask":"2.2325","Spread":"2.50","ProductType":"2",},{"Symbol":"AUDNZD","Bid":"1.12279","Ask":"1.12295","Spread":"1.60","ProductType":"1",},{"Symbol":"EURSEK","Bid":"9.2382","Ask":"9.23974","Spread":"15.40","ProductType":"1",},{"Symbol":"CADJPY","Bid":"84.603","Ask":"84.609","Spread":"0.60","ProductType":"1",},{"Symbol":"USDCHF","Bid":"0.98628","Ask":"0.98632","Spread":"0.40","ProductType":"1",},{"Symbol":"USDCNH","Bid":"6.50553","Ask":"6.50581","Spread":"2.80","ProductType":"1",},{"Symbol":"XAGUSD","Bid":"15.222","Ask":"15.263","Spread":"4.10","ProductType":"5",},{"Symbol":"US30","Bid":"17134.00","Ask":"17136.00","Spread":"2.00","ProductType":"2",},{"Symbol":"USDSEK","Bid":"8.316","Ask":"8.31711","Spread":"11.10","ProductType":"1",},{"Symbol":"AUDCHF","Bid":"0.73659","Ask":"0.73664","Spread":"0.50","ProductType":"1",},{"Symbol":"GER30","Bid":"9921.00","Ask":"9922.00","Spread":"1.00","ProductType":"2",},{"Symbol":"USOil","Bid":"36.61","Ask":"36.66","Spread":"5.00","ProductType":"3",},{"Symbol":"GBPNZD","Bid":"2.13329","Ask":"2.13358","Spread":"2.90","ProductType":"1",},{"Symbol":"EURCAD","Bid":"1.48262","Ask":"1.48272","Spread":"1.00","ProductType":"1",},{"Symbol":"EURUSD","Bid":"1.11089","Ask":"1.1109","Spread":"0.10","ProductType":"1",},{"Symbol":"XPTUSD","Bid":"956.60","Ask":"959.70","Spread":"31.00","ProductType":"5",},{"Symbol":"EURJPY","Bid":"125.441","Ask":"125.449","Spread":"0.80","ProductType":"1",},{"Symbol":"AUS200","Bid":"5089.00","Ask":"5091.00","Spread":"2.00","ProductType":"2",},{"Symbol":"EURGBP","Bid":"0.78286","Ask":"0.7829","Spread":"0.40","ProductType":"1",},{"Symbol":"USDCAD","Bid":"1.33461","Ask":"1.33471","Spread":"1.00","ProductType":"1",},{"Symbol":"EURNOK","Bid":"9.48035","Ask":"9.48285","Spread":"25.00","ProductType":"1",},{"Symbol":"GBPCHF","Bid":"1.39949","Ask":"1.39961","Spread":"1.20","ProductType":"1",},{"Symbol":"GBPAUD","Bid":"1.89993","Ask":"1.90006","Spread":"1.30","ProductType":"1",},{"Symbol":"USDJPY","Bid":"112.919","Ask":"112.923","Spread":"0.40","ProductType":"1",},{"Symbol":"USDNOK","Bid":"8.5339","Ask":"8.5353","Spread":"14.00","ProductType":"1",},{"Symbol":"AUDCAD","Bid":"0.99675","Ask":"0.99684","Spread":"0.90","ProductType":"1",},{"Symbol":"ITA40","Bid":"18746.00","Ask":"18766.00","Spread":"20.00","ProductType":"2",},{"Symbol":"FRA40","Bid":"4458.50","Ask":"4459.50","Spread":"1.00","ProductType":"2",},{"Symbol":"AUDUSD","Bid":"0.74683","Ask":"0.74686","Spread":"0.30","ProductType":"1",},{"Symbol":"USDHKD","Bid":"7.75917","Ask":"7.75948","Spread":"3.10","ProductType":"1",},{"Symbol":"NZDCHF","Bid":"0.65595","Ask":"0.65607","Spread":"1.20","ProductType":"1",},{"Symbol":"EURTRY","Bid":"3.21593","Ask":"3.21737","Spread":"14.40","ProductType":"1",},{"Symbol":"AUDJPY","Bid":"84.333","Ask":"84.339","Spread":"0.60","ProductType":"1",},{"Symbol":"USDZAR","Bid":"15.90479","Ask":"15.9158","Spread":"110.10","ProductType":"1",},{"Symbol":"Bund","Bid":"161.49","Ask":"161.52","Spread":"3.00","ProductType":"4",},{"Symbol":"USDMXN","Bid":"17.88412","Ask":"17.88669","Spread":"25.70","ProductType":"1",},{"Symbol":"USDTRY","Bid":"2.8947","Ask":"2.89508","Spread":"3.80","ProductType":"1",},{"Symbol":"USDOLLAR","Bid":"12022.00","Ask":"12024.00","Spread":"2.00","ProductType":"7",},{"Symbol":"JPN225","Bid":"16926.50","Ask":"16936.50","Spread":"10.00","ProductType":"2",},{"Symbol":"HKG33","Bid":"20290.00","Ask":"20300.00","Spread":"10.00","ProductType":"2",},{"Symbol":"UK100","Bid":"6136.00","Ask":"6137.00","Spread":"1.00","ProductType":"2",},{"Symbol":"CADCHF","Bid":"0.73895","Ask":"0.73904","Spread":"0.90","ProductType":"1",},{"Symbol":"NAS100","Bid":"4353.00","Ask":"4354.00","Spread":"1.00","ProductType":"2",},{"Symbol":"ZARJPY","Bid":"7.097","Ask":"7.10","Spread":"0.30","ProductType":"1",},{"Symbol":"GBPCAD","Bid":"1.89381","Ask":"1.894","Spread":"1.90","ProductType":"1",},{"Symbol":"NGAS","Bid":"1.8745","Ask":"1.8845","Spread":"10.00","ProductType":"3",},{"Symbol":"ESP35","Bid":"8995.00","Ask":"9003.00","Spread":"8.00","ProductType":"2",},{"Symbol":"GBPUSD","Bid":"1.41899","Ask":"1.41906","Spread":"0.70","ProductType":"1",},{"Symbol":"SPX500","Bid":"2007.63","Ask":"2008.13","Spread":"5.00","ProductType":"2",},{"Symbol":"GBPJPY","Bid":"160.231","Ask":"160.244","Spread":"1.30","ProductType":"1",},{"Symbol":"XPDUSD","Bid":"561.70","Ask":"564.70","Spread":"30.00","ProductType":"5",},{"Symbol":"EUSTX50","Bid":"3060.00","Ask":"3061.00","Spread":"1.00","ProductType":"2",},{"Symbol":"TRYJPY","Bid":"38.986","Ask":"39.003","Spread":"1.70","ProductType":"1",},{"Symbol":"NZDCAD","Bid":"0.88767","Ask":"0.8878","Spread":"1.30","ProductType":"1",},{"Symbol":"EURNZD","Bid":"1.67013","Ask":"1.67029","Spread":"1.60","ProductType":"1",},{"Symbol":"XAUUSD","Bid":"1231.13","Ask":"1231.55","Spread":"42.00","ProductType":"5",},{"Symbol":"NZDUSD","Bid":"0.66508","Ask":"0.66516","Spread":"0.80","ProductType":"1",},{"Symbol":"SUI20","Bid":"7960.00","Ask":"7964.00","Spread":"4.00","ProductType":"2",},{"Symbol":"NZDJPY","Bid":"75.101","Ask":"75.108","Spread":"0.70","ProductType":"1",},{"Symbol":"UKOil","Bid":"38.98","Ask":"39.03","Spread":"5.00","ProductType":"3",},{"Symbol":"CHFJPY","Bid":"114.488","Ask":"114.494","Spread":"0.60","ProductType":"1",},{"Symbol":"EURCHF","Bid":"1.0957","Ask":"1.09574","Spread":"0.40","ProductType":"1",}]});
Everything returnes 'undefined'. Here is a fiddle
Your response is returning an array of objects. Iterating over that array should give you the data. Something like this could work:
$(function(){
var API = "https://ratesjson.fxcm.com/DataDisplayer";
$.ajax({
url: API,
dataType: 'jsonp',
crossDomain: true,
success:function( msg ) {
var html = '';
var Symbol = msg.Rates.Symbol;
for(var i = 0; i < msg.Rates.length; i ++) {
html += '<tr><td>'+msg.Rates[i].Symbol+'</td><td>'+msg.Rates[i].Bid+'</td><td>'+msg.Rates[i].Ask+'</td><td>'+msg.Rates[i].Spread+'</td></tr>';
console.log("Symbol: " +msg.Rates[i].Symbol);
}
$('#dataTable tbody').html(html);
}
});
});
Updated fiddle: https://jsfiddle.net/igor_9000/5o9q8g0y/2/
Hope that helps!
Try with this :
var Symbol = msg.Rates[0].Symbol;
console.log(JSON.stringify(Symbol));
Try this-
$(function(){
var API = "https://ratesjson.fxcm.com/DataDisplayer";
$.ajax({
url: API,
dataType: 'jsonp',
crossDomain: true,
success:function( msg ) {
$.each(msg.Rates, function ( key, value )
{
console.log(key +":"+ value);
});
}
});
});

Send php array to jquery ajax and make a each loop from that array

hi actually i read many topic about array and jquery and they all show example using jquery inside the hmtl script tag but what i try to learn is how to read an array sent by php throught ajax inside a js file
here is my php example
$record = array('jazz','rock', 'punk', 'soft', 'metal');
echo json_encode($record);
then here is my ajax
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
// here i want to read the array and make a loop for each element
},
});
thanks if you can help me
try basic for loop with count using length This .. this should help surely.
function ajax_test()
{
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i]);
}
}
});
}
Try a for loop to loop the records
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
var record;
for(record in response)
{
console.log(response[record]);
});
},
});
Please use below code :
$(response).each(function(key,value){
console.log(value);
});
Here each loop of response array and value get ('jazz',rock,...etc).
try see this, clear solution for your question
https://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
$.each : A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. Reference documentation
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
//Check if the response is in expected JSON format.
var flag = isJSON(response);
if(flag === true)
{ response = JSON.parse(response); }
//Iterate the Array using for each loop of jquery
$.each(response, function( index, value ) {
console.log( "Index : " + index + "Value : " + value );
});
} // End of success function
}); //End of Ajax
//JSON format check
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
You can get array indexes and values by using .each in jQuery as:
$.ajax({
url: "system/music_list.php",
dataType: 'json',
cache: false,
success: function(response){
$.each(response, function(index,value)
{
console.log(index); // print all indexes
console.log(value); // print all values
});
},
});
<div id="dat" name="dat"></div>
<script type="text/javascript">
$.ajax({ url: "music_list.php",
dataType: 'json',
cache: false,
success:function(response) {
for( res in response) {
document.getElementById('dat').innerHTML+=response[res]+"<br/>";
}
}
});
</script>

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

Javascript scope when using ajax post and functions in general

I'm relatively new to javascript, and I have a restful api I'm connecting to that returns me a json string, which I can parse properly like so:
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
success: function(output) {
var json = $.parseJSON(output);
for( var i = 0 ; i < json.response.length; i++ ){
times.push (json.response[i].time);
}
}
});
Inside of the success callback the variables in the array exist. I also have times array instantiated outside the ajax call function. But outside of the ajax call the array is empty. I'm sure it's a scoping issue. Can anyone give me a way to get the data from inside the array? Does the construct $.ajax({url:... , data:... , success: function(){}}); returns callback return value?
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
dataType: 'json',
success: function(output) {
times = [];
for( var i = 0 ; i < output.response.length; i++ ){
times.push (output.response[i].time);
}
},
complete: function(){
if(times.length > 0){ console.log(times); } else { console.log("times empty"); }
}
});

jquery function access local javascript variable

New to jQuery and having simple yet confusing problem. ha2.
I am writing this normal javascript function with jQuery function reading xml file. How do I assigned value to the prodPrice variable declared on the top? the script keep returning 0 value, but if I alert the value within the jQuery function, I managed to get the value that I wanted.
Thank you guys.
function getPrice(valprodID)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
return false;
}
});
}
})
return prodPrice;
}
That's because $.ajax is performed asynchronously.
And it is a great chance for you to learn how to work with $.Deferred
function getPrice(valprodID)
{
var prodPrice=0;
return jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml"
}).pipe(function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
return jQuery(this).find('prodPrice').text();
}
});
});
}
Now you call your getPrice() function in this way:
getPrice(someid).done(function(prodPrice) {
// do what you need with prodPrice
});
Here is an example on jsfiddle: http://jsfiddle.net/zerkms/9MgsX/1/
you can do asynchronous as reported by #xdazz, as #zerkms indicated with Deferred, or anonymous functions:
function getPrice(valprodID, fn)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
fn(prodPrice);
}
});
}
})
}
getPrice(1, function(prodPrice) {
/* your code */
})
You need to set the async option to false, or you should do your work in the callback function.

Categories