For this line of code :
var result = eval('('+result+')');
In this context:
function saveUser(){
alert(url);
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
How do i fix the error?
what does Uncaught SyntaxError ... mean?
It means that eval cannot parse the input (as JavaScript) because it contains a < where there shouldn't be one. FWIW if the response is HTML, JSON.parse wouldn't help either.
How do i fix the error?
You either have to treat the response how it is expected to be treated, e.g. don't pass it through eval if it's HTML.
Or you fix the server side and return the repsonse that the client side expects, e.g. JSON.
Related
So I try to parse json response from ajax request with JSON.response, but it doesn't work
the example of the json response from my api looks like this :
{"cn":"3335621215844","status":5,"proxy":"207.154.231.213:8080","error":"Received HTTP code 400 from proxy after CONNECT"}
here's the error from the broswer debug :
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
here is my code :
function cn_doCheck() {
var proxy_counter = 0;
var cn_list = $("#cn_input").val().split('\n');
var proxy_list = $("#proxy_input").val().split('\n');
var i=0;
if (cn_list!="" && proxy_list!="") {
$.each(cn_list, function(index, value){
if (i>proxy_list.length) {
i=0;
}
$.ajax({
type : 'post',
data : {
cn: value,
proxy: proxy_list[i]
},
url : 'api_test.php',
async : true,
beforeSend: function(response){
$("#loader").empty();
$("#loader").append("Checking "+cn_list.length+" in total");
},
success: function(response){
},
complete: function(response){
var result = JSON.parse(response);
$("#cn_live").append(result.cn+"|"+value+"|"+proxy_list[i]+"\n");
i++;
}
});
});
}else{
alert("Card/Proxy list can't be empty!");
}
}
Seems like response is already a JavaScript object not a string, you do not need to parse that again.
Update: Ajax success() only gets called if your web server responds with a 200 OK HTTP header - basically when everything is fine. Where as, complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - complete() will still get called.
Please execute your code inside success call back to avoid unwanted scenario.
Problem
It appears that the response is already in JSON format.
Parsing the response:
complete: function(response){
var result = JSON.parse(response);
$("#cn_live").append(result.cn+"|"+value+"|"+proxy_list[i]+"\n");
i++;
}
Response:
{
"cn": "3335621215844",
"status": 5,
"proxy": "207.154.231.213:8080",
"error": "Received HTTP code 400 from proxy after CONNECT"
}
If you try to use JSON.parse with an object that is already in JSON format, it will give you the error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Solution
So I think you do this instead:
var result = response
I have an error in my ajax:
Cannot read property '0' of undefined
dmpConnectInstance.hl_readCpxCard(getCpsPinCode(), function (a) {
var path = "cpx";
$.ajax({
type: "POST",
url: path,
data: a,
success: function (data) {
//
$("#res").html("okyou" + data.PracticeLocations[0].s_practiceLocationName);
console.log('yooo' +
data.PracticeLocations[0].s_practiceLocationName);
}
,
error: function () {
console.log('ko');
}
});
});
Here is the json format:
{
"PracticeLocations":[
{
"s_practiceLocationActivity":"SA07",
"s_practiceLocationHealthcareSettings":"SA07",
"s_practiceLocationName":"CABINET M. INFIRMIER3681"
}
],
"i_remainingPinCodeInputs":3,
"s_given":"ALAIN",
"s_internalId":"00B6036814",
"s_name":"INFIRMIER3681",
"s_profession":"60",
"s_professionOid":"1.2.250.1.71.1.2.7",
"s_speciality":"",
"s_status":"OK"
}
I think I have a problem with the data, when I debug data I got empty message.
Otherwise if I put directly into the function:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
I got the result.
The JSON content you display in your post, is that what is going in or coming out, and how did you confirm the result if indeed the case? The nature of the error is saying that data.PracticeLocations is null and doesn't contain anything at position 0. If data came back as a truly empty result, then that would make sense and including the code that returns your response would help.
Your subsequent statement in the post was:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
This has a.PracticeLocations, not data.PracticeLocations, which variable a is not referenced anywhere. I presume that is a typo?
i am writing page in html and i have server/database on parse.com .
parse provides login function which checks if username and password is matched in a database. i have done this part but when i get success it is not redirecting into other page. here is the code :
$("#login").click(function(event)
var name = $(#name).val();
var pass = $(#password).val();
Parse.User.logIn(name, pass, {
debugger
success: function(user){
window.location="login/login.html";
console.log("everything OK")
}, error: function(user, error){
console.log("Log in Error:"+error.message);
}
});
});
i have searched for redirecting the page and found out the window.location but it is not working. what is the error please help me.
By the way i got error message at this line var name = $(#name).val(); with error message :
Uncaught SyntaxError: Unexpected token ILLEGAL
You have a couple of problems in your code which is stopping it from running. Unexpected token ILLEGAL is the browser's way of telling you that it doesn't understand your code.
1) You're missing the opening brace in the first function
2) In the jQuery selectors, you need to wrap the selectors in quotes - $("#name").val() and $("#password").val()
3) Your debuger statement is misplaced. You've put it inside an object definition, and it doesn't make sense there. Move it to inside the function below. (It's also spelt debugger with 2 g's :) )
$("#login").click(function(event) { // 1) include brace
var name = $("#name").val(); // 2) include quotes
var pass = $("#password").val();
Parse.User.logIn(name, pass, {
success: function(user){
debugger; // 3) move debugger statement to a valid location
window.location="login/login.html";
console.log("everything OK")
},
error: function(user, error) {
console.log("Log in Error:"+error.message);
}
});
});
You need to pass both of your selectors in quotes
var name = $("#name").val();
var pass = $("#password").val();
That will stop the error and should work.
This is riddled with errors and missing semicolons and parantheses. Try this
$("#login").click(function(event) {
var name = $("#name").val();
var pass = $("#password").val();
Parse.User.logIn(name, pass, debuger);
success: function(user){
window.location="login/login.html";
console.log("everything OK")
}, error: function(user, error){
console.log("Log in Error:"+error.message);
}
});
});
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 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.