I could not retrieve data to jquery div element but i can see ajax response in firebug.
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})
this is my response.for example my url contains data productCount:64 ,I should extract productCount from ajax success and display it in html div id result
When you parse out the JSOn data you use it like so:
var parsed_data = JSON.parse(JSON_DATA);
$('#result').html(parsed_data.key);
So if your parsed_data is somewhat like:
{name:"test",age:12}
then you use it like:
$('#result').html(parsed_data.name); //it will give you test
if you really want to print out the whole data use JSON.stringify(obj) like so:
$('#result').html(JSON.stringify(parsed_data));
In your code you are returning a json and you are trying to insert ino the div it, into the div you can only insert html code instead json.
Try to inspect the json you are returning and in case you need to insert each element into the div, do it, but don't do for all.
The html() method doesn't know what you want to assign, it only insert an html.
You need to iterate over your json data in returnData. You are not able to put json directy into html. You need to convert / parse / iterate it before. So, for example:
$.each(returnedData, function (index, value) {
// do stuff with it, e. g.:
// $('#result').html($('#result').html() + value);
});
https://jsfiddle.net/m8udusps/
The code here actually works. However it says there is a problem when it is parsing the JSON. You needed to add crossDomain: true, to allow it to actually get the results.
Having received a supposed JSON struct like:
{
"Field1": "value1",
"Field2": "value2"
}
This code gets the values of the keys (just first key in this example). Result is an alert message with Data: value1:
$.ajax({
'url' : './localurl',
'type' : 'GET',
'success' : function(data) {
alert("Data: "+data.Field1);
},
'error' : function(request,error) {
alert("Error in response: "+JSON.stringify(data));
}
});
In this case Field1 is the key received and it is directly accesible through data variable, so it is not necessary to do the JSON.parse(data) (in fact this JSON.parse produce an error)
Related
I'm trying to access some JSON data that I got through an ajax call. I'm not sure how to access this data now though. I want to extract the "test" portion out of the json. Could someone please help me out with this
Image of current output
code sample:
$(".test").on("click", function() {
var dialogID = $(this).attr("id");
console.log(dialogID);
$.ajax({
type: "GET",
url: "test.php?id=" + dialogID,
dataType: "json",
success: function(data) {
console.log(data);
},
error: function() {
console.log("error");
}
});
Assuming the ajax data is stored in a variable called 'data'
data['DATA'][0][0];
If you look at the developer console, you'll notice that 'test' in an item in array at index 0. That array is at index 0 of another array called DATA. DATA is an array in the object returned by the AJAX call.
You can see all the data types next to the variable names in the developer console, i.e 'COLUMNS: Array[1]' on the second line tells you that COLUMNS is an array of length 1.
I'm trying to use this minecraft server API (JSON), to show in my webpage, something like... Right now there are (players) connected.
The JSON file looks like this (external):
{
"status": true,
"players": {
"online": 534,
"max": 900
},
"cache": 1442690473 }
I want to fetch the data players (online) and display it on a html paragraph.... Using JavaScript or Jquery. I searched some solutions, using getJSON, but I couldn't make it work..
I tried using AJAX to make a request...
// AJAX Request to JSON
$.ajax({
url: "https://mcapi.ca/query/mythalium.com/players",
// Handle as Text
dataType: "text",
success: function(data) {
// Parse JSON file
var json = $.parseJSON(data);
//Store data into a variable
// Display Players
$('#players').html('Currently there are: ' + json.players.now ' users');
}
});
And then display it using:
<span id="results"></span>
Why is not working? Nothing is being showed...
You should change your AJAX success callback to:
success: function(data) {
// Parse JSON file
var json = $.parseJSON(data);
//Store data into a variable
// Display Players
$('#results').html('Currently there are: ' + json.players.online' + users');
}
The problems are you're selecting the wrong span element - #players instead of #results and you're referencing the wrong JSON property - json.players.now instead of json.players.online like in the sample response you provided.
Datatype should be JSON.
Check this video here: https://www.youtube.com/watch?v=fEYx8dQr_cQ
You should be fine then.
Hey guys I would like to know how can I get json data with ajax call.
I tried this but seems won't work :P
First I created a JavaScript file to put inside my json data elements :
var food = [
{'name':'bread', 'price':'7,25'},
{'name':'fish', 'price':'9,00'}
];
I saved it as food.js.
Then I tried to make an ajax call from an another file, this is my code :
$(document).ready(function(){
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food.name;
alert(result);
});
}});
});
Any ideas?
Thanks in advance ;)
Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.
In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:
success: function(data) {
var result = data.food[0].name; // = "bread"
alert(result);
});
try this
$(document).ready(function() {
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food[0].name;
alert(result);
}
});
});
You need to loop through the returned data since it's an array:
$.each(data,function(i,val) {
alert(data[i].name);
});
I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.
Then you can access data.food[0].name;
In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).
Your code is mucth better when you request directly json files.
You probably want to use the getJSON function in jquery : http://api.jquery.com/jquery.getjson/
$.getJSON( "food.json", function( data ) {
//here your callback
}
It will set the datatype to json and the method to GET by default.
You should also use the .json extension and not the js extension for you jsons. And format it like a proper json :
{
"food": [
{
"name": "bread",
"price": 7.25
},
{
"name": "fish",
"price": 9.00
}
],
}
You can use this website to help you format jsons : http://www.jsoneditoronline.org/
The way you are trying to call your element won't work. The data you obtain is an array. In the callback, you can try this :
console.log(data)
console.log(data.food)
console.log(data.food[0])
console.log(data.food[0].name)
console.log(data.food[0].price)
Finally, note that you formatted your numbers with a coma, this is not the way you format numbers in javascript. Use a dot, that way you'll be able to manipulate it as a number.
"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there
I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.