I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.
Related
In a webpage that uses javascript, I pass data to a hidden input field using
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
and then later access that data using
waypts_input = $.parseJSON($("#waypt_sel").val())
This works, except that sometimes it gives a
Uncaught SyntaxError: Unexpected end of input
. I tracked the error to this line with the json parsing. but I am baffled because this works sometimes but sometimes it doesn't for the same, identical string.
I checked the values that are passed to the html inputs and it works and doesn't work for the same values.
Here's an example of the json string I am passing:
"[{\"location\":\"8.3353156, 80.3329846\",\"stopover\":true}, {\"location\":\"8.0326424, 80.7446666\",\"stopover\":true}, {\"location\":\"7.9577778, 80.667518\",\"stopover\":true}, {\"location\":\"7.953208, 81.006675\",\"stopover\":true}, {\"location\":\"7.885949, 80.651479\",\"stopover\":true},{\"location\":\"7.2905425, 80.5986581\",\"stopover\":true},{\"location\":\"7.300322, 80.386362\",\"stopover\":true}]"
Here's the structure of the code I use.
$(document).ready(function() {
$.ajax({
url: "aa.php",
type: "POST",
data: {
id: selected_i
},
success: function(result) {
itins = $.parseJSON(result);
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
}
});
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function(result) {
locations = $.parseJSON(result);
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
waypts_input = $.parseJSON($("#waypt_sel").val());
waypts_json_input = $.parseJSON(waypts_input);
//other code
}
}
});
And here is the detailed error message I get on firefox developer edition browser.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
calculateAndDisplayRoute() map.js:366
initializeMap() map.js:290
.success() map.js:62
m.Callbacks/j() jquery-1.11.3.min.js:2
m.Callbacks/k.fireWith() jquery-1.11.3.min.js:2
x() jquery-1.11.3.min.js:5
.send/b() jquery-1.11.3.min.js:5
Thanks in advance.
"\" is unnecessary when deserialize json string in javascript .
what json tools you used?
you serialize in one tool , and deserialize with other , may get this scene .
The issue was that I was using an asynchronous ajax request to retrieve json data. by the time the data had been retrieved and pasted to the html, the execution of the code that used the html data had happened, and thus gave an error. I used a callback function for the ajax query and this did the job.
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
and in the code where this is called:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
Alternatively you may also try async: false in the ajax query parameters. But this can cause browser freezing and is not recommended.
I'm trying to parse the following JSON response:
{
"AgApplyTableE*!": [
{
"Index": 1,
"StringVal": "Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"
}
]
}
Here's my code:
$('#applyfailreason').click(function (){
var t = $(this);
var DeviceName = $('.DeviceName').val();
var Username = $('.Username').val();
var Password = $('.Password').val();
$.ajax({
method: 'GET',
url: 'http://' + DeviceName + '/config/AgApplyTable',
headers: {
"Authorization": "Basic " + btoa('' + Username + '' + ":" + '' + Password + '')
},
dataType: 'json',
contentType: 'application/json',
success: function(data) {
var test = JSON.stringify(data);
console.log(test);
},
statusCode: {
406 : function() {
alert('There is an unexpected string in your data.\nFix the error and try again.');
},
401 : function() {
alert('Wrong username or password.');
}
},
});
});
I get the following on the console (which is ok):
{"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]}
But I want to print only the "StringVal" out of the JSON response.
Tried:
var test2 = JSON.stringify(data.StringVal);
console.log(test2);
Gives:
undefined
I also tried the following (with dataType: 'jsonp',):
var test4 = JSON.parse(data.StringVal);
But then Chrome sends a GET request to a strange URI (which actually gives 200OK):
config/AgApplyTable?callback=jQuery111306132095118518919_1436256387242&_=1436256387244
And I get the following error:
Uncaught SyntaxError: Unexpected token :
Any idea how to print to console only "StringVal" out of the JSON response?
Thanks.
Your response is an object containing one property named "AgApplyTableE*!", which is an array that contains one element, which is an object that contains the property "StringVal".
So you'd have to access it by data["AgApplyTableE*!"][0].StringVal.
Use console.log(data['AgApplyTableE*!'][0].StringVal)
In your response, there is no such thing as StringVal as direct suboridnate of data. The property StringVal is inside the internal object AgApplyTableE*! therefore data.StringVal is undefined.
Also, another problem I see here is that you're stringifying the response and then trying to access the property StringVal.
If you stringify, you test variable will be a string and string doesnt have a property StringVal (unless you set that in your proto)
EDIT:
Added missing [0] index.
Try
var test2 = data["AgApplyTableE*!"][0].StringVal;
console.log(test2);
test ={"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]};
console.log(test["AgApplyTableE*!"][0]["StringVal"]);
Demo
I think that is because you have two levels here, not only one. In order to get that value out, you probably would need something like
var test2 = JSON.parse(data);
console.log(test2["AgApplyTableE*!"][0].StringVal);
Altough I'm not sure AgApplyTableE*! is a really good identifier here. Probably you can change something else, and then you can also use . notation to reach the members.
I'm using php json_encode to send a bunch of values to a client, where jquery
{"data":{"application":{"basics":{"email":"jepp#mily.com","name_first":"Step","name_last":"Bob","phone":"9210938102938","occupation":"unemployed","website":"wwwcom"},"application":{"title":"Default title","guid":"9as8ua9sd8ua9sdu","language":"sv"},"job":{"title":"joburl","url":"joburl"},"letter":{"letter":"abadbabkbakbakbakbakbakbabk"},"work-experiences":[{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"}],"educations":{"title":"Default Education","url":"ixi","date_from":"1970-01-01","date_to":"1999-12-31"},"skills":{"title":"Defailt SKILL","url":"wwwsdcom","date_from":"ixi","date_to":"ixi"},"work-samples":{"title":"A sample of my work","url":"wwwsdcom","date_from":"ixi","date_to":"1999-12-31"}}},"error":[],"warning":[]}
If I try to parse this with $.parseJSON in a script I get no object. However, if I copy/paste it directly into the console (and add ' in the beginning and end), it works. There are no error codes and I can see no linebreaks. JSON lint-tools returns no errors...
I have set the correct content type and tried the different json parsers that jquery provides.
What have I missed?
The code was cut/pasted from the jQuery tutorials. I tried some different examples but they all failed.
var jqxhr = $.getJSON( "application_controller.php", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function(data) {
console.log( "complete" );
application = data;
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});
});
It's true, I decoded it in the console. this is a snippet that does in in-script (it also won't work):
$.ajax({
dataType: "json",
contentType: "application/json",
url: 'application_controller.php',
data: '{id:id}',
success: function( data ) {
application = data.responseText;
application = $.parseJSON(application);/* < string */
},
fail: console.log("fail"),
complete: function(data) {
console.log(data.responseText);
application = data.responseText;
}
});
Answering my own question:
To solve this error I had to change all my php files from "utf8" encoding to "utf8 without BOM". Then it worked.
When a file without utf8 encoding was included (low in the hierarchy of course) it tainted all the other files and corrupted the output.
use JSON.parse(jsonString) function.
var jsonString = '{"data":{"application":{"basics":{"email":"jepp#mily.com","name_first":"Step","name_last":"Bob","phone":"9210938102938","occupation":"unemployed","website":"wwwcom"},"application":{"title":"Default title","guid":"9as8ua9sd8ua9sdu","language":"sv"},"job":{"title":"joburl","url":"joburl"},"letter":{"letter":"abadbabkbakbakbakbakbakbabk"},"work-experiences":[{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"}],"educations":{"title":"Default Education","url":"ixi","date_from":"1970-01-01","date_to":"1999-12-31"},"skills":{"title":"Defailt SKILL","url":"wwwsdcom","date_from":"ixi","date_to":"ixi"},"work-samples":{"title":"A sample of my work","url":"wwwsdcom","date_from":"ixi","date_to":"1999-12-31"}}},"error":[],"warning":[]}';
var myData = JSON.parse(jsonString);
Fiddle
I'm trying to get weather data from openweathermap. This url works with coordinates I put in, and I can download the JSON when I input the url the in the browser bar. I'm trying to get this working in my page. When I run this code, in Firebug I can see the HTTP request got the 200 success code, but it's not printing the response for some reason. Am I not using getJSON properly?
var url = "http://api.openweathermap.org/data/2.5/forecast?lat="+ position.coords.latitude +"&lon=" + position.coords.longitude;
$.getJSON(url, function(res) {
console.log(res);
});
You are trying to read cross domain JSON in a function which reads JSONP.
Cross domain JSON reading is not possible.
Try a JSONP request instead;, by appending a callback
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" +
position.coords.latitude +"&lon=" + position.coords.longitude + "&callback=?" ;
$.getJSON(url, function(res) {
console.log(res);
});
JSON response is like this :
{ 'a':22 }
JSONP response is like :
myFunction({'a':22} ) , where myFunction was the value passed as callback
jQuery does not need the name of the callback function, however needs callback to be mentioned in the URL so that it can indentify it as a JSONP request.
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
Append this ?callback=? to the url and try again like:
$.getJSON(url + '?callback=?', function(res) {
console.log(res);
});
Try this
function buildQuery() {
var str = "http://api.openweathermap.org/data/2.5/forecast?lat=27.175009&lon=78.041849";
return "select * from json where url ='" + str + "' ";
}
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
data: {
q: buildQuery(),
format: "json"
},
dataType: "jsonp",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
consol.log(data);
}
});
working Demo :-
http://jsfiddle.net/HWuDk/1/
Ok this is my JavaScript
<script type="text/javascript" language="JavaScript">
function manageCart(task,item) {
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
}
function reportError(request) {
$F('cartResult') = "An error occurred";
}
And this is HTML
<p>
Add to cart
</p>
This script doesn't work in Firefox, I've ran a few Firefox JS debuggers but they displayed no errors. I'm not so good in JavaScript so please help me if you can :)
This script actually uses Prototype library if it will make things clearer.
For this type of Ajax call do not use Ajax.Updater as that is designed to update a specific element with the contents of the ajax response. I believe that you want to just make a simple single ajax call so using Ajax.Request would be what you want to use.
Original Code using Ajax.Updater
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
Code using Ajax.Request
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Request(url,
{
method: 'get',
parameters: params,
onFailure: reportError,
onSuccess: function(){
console.log('It Worked');
}
});
I put a success handler in this call just to confirm that it worked for you - and it should output to your console. You can remove it or comment the console.log() when you are satisfied it works
I've spent more time in FireBug and found the error.
Timestamp: 03.04.2013 10:36:38
Error: ReferenceError: invalid assignment left-hand side
Source File: http://www.example.com/index.php
Line: 413, Column: 18
Source Code:
('cartResult') = "An error occurred";
Firefox desperately wanted for the statement to look like this:
('cartResult') == "An error occurred";