Display returned JSON [duplicate] - javascript

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

Related

Trying to make ajax compare its last data to the latest but it doesn't work

I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}

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>

Javascript json object parsing [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
$(document).ready(function () {
var oOpenOrders = new Array();
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: 'http://192.168.19.22/test.php',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
debugger;
for(var i=0; i<data.length; i++){
alert(typeof(data.id));
oOpenOrders.push(data);
}
var obj = jQuery.parseJSON(data);
debugger;
this code snippet i am using and want to parse it(want to use lat, long) even data.length say correct length 4 for following json, following json is coming from ajax call.:
[{"id":"3037","latitude":"28.617422000","longitude":"77.381180000"},
{"id":"3036","latitude":"28.617422000","longitude":"77.381180000"},
{"id":"3035","latitude":"28.617422000","longitude":"77.381180000"},
{"id":"3034","latitude":"28.617422000","longitude":"77.381180000"}]
any idea ?
Try this
alert(typeof data[i].id);

"Unexpected token o" when using $.parseJSON [duplicate]

This question already has answers here:
JSON+Node.js - Unexpected token o
(2 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
The following ajax call gives the following result:
$.ajax({
type: "POST",
url: //**My full URL goes here**,
data: {sources: sources},
dataType: "json",
success: function(data) {
alert(data);
alert(data.length);
for (var i = 0; i < data.length; i++)
{
alert(data[i]);
}
}
});
Result:
data:
[objject object],[objject object],[objject object]
length:
3
in loop:
[objject object]
[objject object]
[objject object]
and the following code , in which I just added:
var data = $.parseJSON(data);
$.ajax({
type: "POST",
url: //**My full URL goes here**,
data: {sources: sources},
dataType: "json",
success: function(data) {
var data = $.parseJSON(data);
alert(data);
alert(data.length);
for (var i = 0; i < data.length; i++)
{
alert(data[i]);
}
}
});
The above code gives me the following error:
Uncaught Syntax Error: Unexpected token o
Why is that? Am I doing something wrong? How can I fix it?
The data is already a parsed object since you are passing dataType: 'json', so there is no need to parse it again.
Again to debug and inspect the value of data, use console logging instead of alert(), like console.log(data)
Stop use alert to debug, use console.log instead.
success: function(data) {
// in the browser console, you will see the data structure.
// then do what you want
console.log(data);
// ...

javascript cannot set value inside ajax [duplicate]

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"
}
});

Categories