SyntaxError: Unexpected end of input (jQuery) - javascript

I know this is usually an issue of unbalanced parens and curly braces, however after carefully sifting through my syntax, I have, to the best of my ability, confirmed the correct parity of each of these scope delimiters and have no other recourse except to allow my fellow S.O. pundits to take a gander at the following:
$.ajax({
url: "/application/get_programs_for_center",
type: "POST",
data: formdata,
success: function(response){
var options = $("#school_application_program_name");
var result = JSON.parse(response);
console.log(result);
$.each(result, function() {
options.append($("<option />").val(this.id).text(this.name));
});
}
});
N.B. the error is being thrown in the middle of the line var result = JSON.parse(response); specifically immediately after JSON.

The problem you have is that what you parse isn't JSON.
And the reason it's not JSON, is that the response argument you receive is already parsed from JSON by jQuery. Don't parse it again.

If you parse JSONArray, jQuery will not parse it into Object directly, you have to use JSON.parse(response)
However, if you parse a JSONObject, it will be identified and parse into Object automatically
So keep it in mind, that will help you!

Related

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

JSON.parse() not working

I have a json from my server which is -
{"canApprove": true,"hasDisplayed": false}
I can parse the json like this -
var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove); //shows true.
At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject -
//response function
function(jsonObject){
//here jsonObject contains the same json - {"canApprove":true,"hasDisplayed": false}
//But without the surrounding single quote
//I have confirmed about this by seeing my server side log.
var msg = JSON.parse(jsonObject); // this gives the error
}
But now I got the following error -
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
Can anyone tell me why I am getting the error?
Your JsonObject seems is a Json Object. The reasons why you can't parse Json from a String:
the String is surround by " ". and use \" escape inside. Here is an example:
"{\"name\":\"alan\",\"age\":34}"
when you try to parse above string by JSON.parse(), still return the a string:{"name":"alan","age":34}, and \" is replace by ". But use the JSON.parse() function again, it will return the object you want. So in this case,you can do this:
JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))
Your string use ' instead of " . example:
{'name':'alan','age':34}
if you try to parse above string by JSON.parse(), may cause error
I dont think you should call JSON.parse(jsonObject) if the server is sending valid JSON as it will be parsed automatically when it retrieves the response. I believe that if You set the Content-type: application/json header it will be parsed automatically.
Try using jsonObject as if it was already parsed, something like:
console.log(jsonObject.canApprove);
Without calling JSON.parse before.
This answer might help someone who's storing JSON as a string in SQL databse.
I was storing the value of following
JSON.stringify({hi:hello})
in MySQL. The JSON stored in SQL was {"hi":"hello"}
Problem was when I read this value from db and fed it to JSON.parse() it gave me error.
I tried wrapping it in quotes but didn't work.
Finally following worked
JSON.parse(JSON.stringify(jsonFromDb))
This worked and JSON was parsed correctly.
I know the storing mechanisim might not be appropriate however those were client needs.
Its already an object, no need to parse it. Simply try
alert(jsonObject.canApprove)
in your response function.
Json.parse is expecting a string.
Your jsonObject seems already parsed, you need to test if this is the case.
function(jsonObject){
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
It's also possible that your call back is empty, it's generates the same error if you try to parse an empty string. So test the call back value.
function(jsonObject){
if(jsonObject) {
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
}
var text = '{"canApprove": true,"hasDisplayed": false}';
var parsedJSON = JSON.parse(text);
alert(parsedJSON.canApprove);
This works. It is possible that you use " instead of ' while creating a String.
Here is an example of how to make an ajax call and parse the result:
var query = {
sUserIds: JSON.stringify(userIds),
};
$.ajax({
type: "POST",
url: your-url,
data: JSON.stringify(query),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
var your_object = JSON.parse(response.d);
},
failure: function (msg) {
alert(msg);
},
error: function (a, b, c) {
}
});
I faced similar problem and now it's solved. I'm using ASP.Net MVC to send value to .js file. The problem was that I was returning JsonResult from the Action method, because of this JSON.parse was failing in .js file. I changed the return type of Action method to string, now JSON.parse is working fine.
As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.
var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)
This will work.

Parsing JSON returned via an AJAX POST formating issue

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.

Parse ajax response properly

I get data from the server with Ajax.
Data returned (from firebug):
{"users":[{"name":"some name", "age":17},{"name":"some name2", "age":25}]}
When I try
$.post('server.php', function(data){
var users = eval(data).users;
alert(users[0].name);
});
I get on firebug:
Uncaught SyntaxError: Unexpected token )
Any help?
Please do not use eval - it's evil
Instead, simply use a parameter of "json".
$.post('server.php', function(data) {
alert(data.users[0].name);
}, "json");
If your headers are proper, you don't even need the json parameter, but it forces jQuery to want to receive and parse it as JSON.
encode data in brackets with single quotes
$.post('server.php', function(data){
var users = eval('('+data+')');
alert(users[0].name);
});
You have to surround the json string with brackets
$.post('server.php', function(data){
var users = eval('('+data+')').users;
alert(users[0].name);
});
DEMO
I don't get the point on eval() but maybe I don't know the function well...
With this works:
var data = {"users":[{"name":"some name", "age":17},{"name":"some name2", "age":25}]};
alert(data.users[0].name);
​You also may loop with:
$.each(data.users, function (i, user_obj){
alert(user_obj.name);
});
Take a look at this demo.
It's better to add the dataType: "json" to your ajax request so it's properly parsed.

Error on my jquery ajax json function, wont return data

Hi iv got this error on my ajax function using json on retrieving data. It wont return any data. Here's my code below
$.ajax({
url: "php/getCategory.php?action=getyear",
cache: false,
dataType: "json",
success: function(data){
$.each(data.items, function(i,item){
$("#catYear").append('<option value="'+item.id+'">'+item.name+'</option>');
});
}
});
When i try to remove dataType: "json" it will pass into success: function. I think the problem is on my json. I also echo the output of my getCategory.php and i think their is no problem on it. Below is the output of my php json_encode.
{items:[{"id":"1","name":"2010"},{"id":"2","name":"2011"}]}
Thanks!
from jquery documentation :
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
so jour json string has element items which is not double quoted try something like that :
{"items":[{"id":"1","name":"2010"},{"id":"2","name":"2011"}]}

Categories

Resources