Issue in getting a property in a JSON file using jQuery GET - javascript

I ma using jQuery get to retrieve a simple property on a JSON file.
With the following script I get undefined.
What am I doing wrong here?
<script>
$(document).ready(function() {
var urlOriginal = 'http://xxx.com/xxx/xxx/xxx/resources.js';
var urlResource = 'proxy_dr3.php?proxy_url=' + encodeURIComponent(urlOriginal);
$.get(urlResource, function(data) {
console.log(data); // I can see all the content from the JSON FILE
console.log(data.urlPage); // undefined - PROBLEM HERE
var urlHTML = data.urlPage;
/*$.get(urlHTML, function(data) {
$('#result').html(data);
});*/
});
});
</script>
content for resource.js is json
{
"urlPage": "http://xxx.com/xxx/xxx/xxx/article_517d960f0cf2fe38916a2f9d.html"
}
The result type in Network is text/html. After loading resource.js

$.get won't guess it's JSON as the mime type your server gives is wrong.
You could parse the provided value (which is probably a string) using JSON.parse but you should use $.getJSON, so that the callback receives a parsed value.
$.getJSON(urlResource, function(data) {
console.log(data);
console.log(data.urlPage);
});

you can use any one method which is best suitable for your app.
$.ajax({
type: "GET",
data: "ur data",
url: "ur url",
contentType: "application/json; charset=utf-8",
success: function(data) {
}
});
or you can use $.getJSON function

Related

Access to object after ajax function

I have this ajax jquery code:
$("#serial_number").submit(function(e) {
var url = "/getVoucher"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#serial_number").serialize(),
dataType: "json",
success: function(data)
{
console.log(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
and I get this fron console.log:
How I can access to object Code element?
I try with: data.Code also try data.Description but browser give me error... How to access inside success function in ajax code?
When you console.log a variable, the output in the console are it's contents, so if you are still seeing:
Object{ data: Object }
That means that the variable data has a key data inside of it. Try:
console.log( data.data.Code );
To access the object's contents.

How to loop each JSON value after is retrieving its data through AJAX

var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/

GeoJson "Not Well Formed" message in console, and appears undefined

Ive included the very end of my script below, where I'm trying to put a JSON file into a website using Ajax callback function. When I inspect the page, I'm seeing that the JSON file is not well formed and I can't seem to find an answer. The webpage is also just showing that the JSON file is "undefined".
function debugCallback(response){
var mydata;
$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
};
function debugAjax(){
var mydata;
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
//mydata = response;
debugCallback(mydata);
}
});
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(mydata));
};
//$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
if(typeof mydata === 'undefined') {
console.log("undefined data")
} else {
console.log("not undefined")
}
$(document).ready(debugAjax());
Avoid defining several functions and try just using this:
$(document).ready(function(){
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(response));
}
});
});
Note that after we get response/data from ajax call, we proceed formatting as JSON.
You are using var mydata and it is not defined so it is showing correct message undefined when you are passing it as value.
You should probably modify your code like this.
$(document).ready(function(){
$.ajax({
url: "data/MegaCities.GeoJSON",
method: 'GET' ,
aysnc: false,
success: function(response){
$("#mydiv").append('GeoJSON data:' +response);
}
});
});

Passing php string as json to be received by jquery

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

Can't get JSON data from jQuery AJAX API call

My API URL returns the following JSON:
[{"_id":{"$id":"529c759d361ae724088b4568"},"name":"1877","soundcloud_url":"","genres":["rock","electro"]}]
Here is my jQuery AJAX call:
$.ajax({
url: gigniteAPI,
dataType: "jsonp",
complete: function (data) {
var ParsedObject = JSON.stringify(data);
alert(ParsedObject);
}
});
In chrome I can see the script call and that the data that is sent back. However when I JSON.stringify the result all I get is:
{"readyState":4,"status":200,"statusText":"success"}
Why is it not outputting my API data?
Is it to do with the square brackets in my response?
UPDATE:
Perhaps someone can get this jsfiddle to output the 'name' key from the json response? http://jsfiddle.net/T85eB/
The complete function receives the XHR object as a response. I believe you should be using .done(function...) to get the data:
This is taken from here: http://api.jquery.com/jquery.ajax/
$.ajax({
url: gigniteAPI,
dataType: "jsonp")
})
.done(function (data) {
var ParsedObject = JSON.stringify(data);
alert(ParsedObject);
}
})
;

Categories