JSON SyntaxError: Unexpected end of input - javascript

I have the following ajax call where I am passing the data in JSON format and when this code gets executed I get the error shown below,I showed the Console.log(data_cp) below and I validated it in http://jsonlint.com/ and it is a validated input?what am I missing here?how to fix this error?I looked at other posts like json parsing error syntax error unexpected end of input but couldnt figure out...
$.ajax({
dataType: "json",
type: "POST",
contentType: "application/json",//note the contentType defintion
url: "scripts/cherrypick.py",
data: JSON.stringify(data_cp),
//data: data_cp,
error : function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
},
success: function(message){
console.log("cherypick sucess");
}
Serverside python script:-
#!/usr/bin/python
import os
import sys
import json
print "Content-type: application/json\n\n"
...............
...............
def main():
result = {'success':'true','message':'The Command Completed Successfully'}
cherrypicklist = []
cherrypickfaillist = []
myjson = json.load(sys.stdin)
gerritlist = myjson['gerrits']
resource = r'buildserver'
buildlocation = r'cd /local/mnt/workspace/user/buildlocation ; '
for gerrit in gerritlist:
cmd = buildlocation
project,ref = fetchgerritproject(gerrit, connection=None)
proj_path = getprojectpath(project)
cmd += 'cd ' + proj_path + ' ;'
new_cmd = ' gknife am-or-cp ' + gerrit
pick_cmd = cmd + new_cmd
errorlist =''
errorlist = cherrypick(resource,pick_cmd)
if len(errorlist) <= 2:
cherrypicklist.append(gerrit)
else:
chk_cmd = cmd + ' git checkout -f'
connection = ssh_connect(resource)
errorlist = execute_command(connection,chk_cmd)
cherrypickfaillist.append(gerrit)
for gerrit in cherrypicklist:
cmd = buildlocation
project,ref = fetchgerritproject(gerrit, connection=None)
proj_path = getprojectpath(project)
cmd += ' cd ' + proj_path + ' ;'
errorlist = resetgerrit(resource,cmd)
errorlist = execute_command(connection,chk_cmd)
print json.dumps(result)
#return
if __name__ == "__main__":
main()
Error:-
SyntaxError: Unexpected end of input
Console.log(data_cp) output:-
{"gerrits":["1258565","1279604"]}

As per definition of error method from Jquery docs, you get error from server side or if call is not successful.
So it means you are getting error from server. Check the server code.
Definition of Error method from JQuery
error Type: Function( jqXHR jqXHR, String textStatus, String
errorThrown ) A function to be called if the request fails. The
function receives three arguments: The jqXHR (in jQuery 1.4.x,
XMLHttpRequest) object, a string describing the type of error that
occurred and an optional exception object, if one occurred. Possible
values for the second argument (besides null) are "timeout", "error",
"abort", and "parsererror". When an HTTP error occurs, errorThrown
receives the textual portion of the HTTP status, such as "Not Found"
or "Internal Server Error." As of jQuery 1.5, the error setting can
accept an array of functions. Each function will be called in turn.
Note: This handler is not called for cross-domain script and
cross-domain JSONP requests. This is an Ajax Event.

Related

jQuery AJAX does not detect success

I have the following code.
$(".likeBack").on("click", function(){
var user = $(this).attr("user");
var theLikeBack = $(this).closest(".name-area").find(".theLikeBack");
$.ajax({
type: "POST",
dataType: "json",
url: "processes/rewind-knock.php",
data: "user="+user+"&type=likeback",
success: function(json){
alert("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
alert("XHR: " + jqXHR + " | Text Status: " + textStatus + " | Error Thrown: " + errorThrown);
}
});
});
Here, everything is functional. Network tab shows request and response well received as required. However, the success part is not getting executed. I tried adding beforeSend and complete and both are getting executed but success part (nothing inside the success blog is getting executed). I don't understand the reason why.
UPDATE
Add error part. It returns:
XHR: [object Object] | Text Status: parsererror | Error Thrown: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
UPDATE 2
Screenshot
give data in ajax like this and check,
data : {'user':user,'type':'likeback'},
In your Php code when you return the data, place all data in a array then use this,
echo json_encode($arr); //return the array in json form
now in your success function use
console.log(JSON.parse(json));
hope may help you. Thank you

Cordova app has internet connection via emulator, but not on device [update: ajax problem]

I am trying to build a small app via cordova that sends data to a PERL-Script on a server. The debug and release build work fine on the genymotion emulator, however sending the data from Android phones does not work. There is no error message from the app (either, which is supposed to show up when the connection fails).
Running USB debugging, I do get the follwoing invoke error message (the savedataLastpage funtion is supposed to send the data):
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.3.min.js:4)
at Ac (jquery-2.1.3.min.js:4)
at Function.n.param (jquery-2.1.3.min.js:4)
at Function.ajax (jquery-2.1.3.min.js:4)
at Object.saveDataLastPage (index.js:631)
at Object.renderLastPage (index.js:461)
at Object.recordResponse (index.js:597)
at HTMLButtonElement.<anonymous> (index.js:357)
at HTMLButtonElement.dispatch (jquery-2.1.3.min.js:3)
at HTMLButtonElement.r.handle (jquery-2.1.3.min.js:3)
The pertaining code is the following:
index.js:631
saveDataLastPage:function() {
$.ajax({
type: 'post',
url: '/URL/',
data: localStore,
crossDomain: true,
success: function (result) {
var pid = localStore.participant_id, snoozed = localStore.snoozed, uniqueKey = localStore.uniqueKey, pause_time=localStore.pause_time;
localStore.clear();
localStore.participant_id = pid;
localStore.snoozed = snoozed;
localStore.uniqueKey = uniqueKey;
localStore.pause_time=pause_time;
$("#question").html("<h3>Thank you, your responses have been sent.</h3>");
},
error: function (request, error) {
console.log(error);
$("#question").html("<h3>Error: Please check your internet connection.</h3><br><button>Send again</button>");
$("#question button").click(function () {app.saveDataLastPage();});
}
});
},
index.js:461
else {
var datestamp = new Date();
var year = datestamp.getFullYear(), month = datestamp.getMonth(), day=datestamp.getDate(), hours=datestamp.getHours(), minutes=datestamp.getMinutes(), seconds=datestamp.getSeconds(), milliseconds=datestamp.getMilliseconds();
localStore[uniqueKey + '.' + "completed" + "_" + "completedSurvey" + "_" + year + "_" + month + "_" + day + "_" + hours + "_" + minutes + "_" + seconds + "_" + milliseconds] = 1;
app.saveDataLastPage();
}
As stated before, on the genymotion emulator the ajax script works fine without the error and sends the data to the script.
I'm not sure why the emulator would work just fine but the error Uncaught TypeError: Illegal invocation suggests that it is a problem with the ajax post call. Specifically, the default setting of processing the data into a query string likely fails.
From the ajax documentation:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
That means you can either turn off the processing processData: false which will post the data in the body of the request or you have to transform the localStore data into a proper object (from whatever it was before).
If it is like an object you can do the following:
var data = {};
for (var elem in localStore) {
data[elem] = localStore[elem];
}
or possibly in brief:
var data = {};
localStore.each(function(elem) { data[elem.name] = elem.value; });

Status 200 OK, same domain, valid JSON data and no response (Ajax)

Here's my ajax call:
$.ajax({
url : hostGlobal + "site/modulos/prefeitura/acoes-jquery.php",
type: "POST",
dataType : "JSON",
data: {
acao: "filtrarCidades",
estado_id: $(".estados:chosen").val()
},
success: function(json) {
console.log("worked");
$(".cidades").html('');
var options = "<option value=\"\"></option>";
$.each(json, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$(".cidades").html(options);
if (!filterThroughCEP) {
$(".cidades").trigger("chosen:updated");
}
},
error: function(e) {
console.log(e.responseText);
}
});
Here's the php action:
if ($acao == 'filtrarCidades') {
$estado_id = $_POST['estado_id'];
$cidade->where = "estado_id = '".$_POST['estado_id']."'";
$cidade->LoadFromDB();
for ($c=0; $c<count($cidade->itens); $c++) {
$cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome;
}
echo json_encode($cidades);
die();
}
json_encode($cidades) is valid json data (UTF8), here's one example using debug:
{"1778":"Bras\u00edlia"}
This {"1778":"Bras\u00edlia"} goes as e.responseText (Error), even with Status OK, and the URL is on the same domain (No need for JSONP). I have no idea why I can't reach success.
EDIT: I've set the contentType:
contentType: "application/json",
And the call still can't "reach" success. Here's the third error argument:
SyntaxError: Unexpected token
at parse (native)
at ajaxConvert (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7608:19)
at done (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7363:15)
at XMLHttpRequest.<anonymous> (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9)
It is indeed related to unicode characters inside the strings that come from the database.
EDIT2: I wrote the whole thing again, and now it's clearer:
function getCitiesByState() {
$.ajax({
url : hostGlobal + "site/estrutura/ajax.php",
type: "POST",
dataType : "text",
data: {
action: "getCitiesByState",
state_id: $(".estados option:selected").val()
},
success: function(json, textStatus, jqXHR) {
console.log($.parseJSON(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
PHP:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
Output:
[{"id":"1778","estado_id":"7","nome":"Brasília","cep":"","loc_no_abrev":"Brasília"}]
Error:
Uncaught SyntaxError: Unexpected token
I think that the problem is the object property
{"1778":"Bras\u00edlia"}
means an object with an invalid property name, thus json decoding fails;
to prove if this is right try either
use plain text as dataType and log it, it should work [but of course you will not be able to convert it to json]
changeLoadFromDB method so that property name is valid [starts with letter, _ or $], you will have a valid JSON response, but you will need to change the way you use it
it 1778 is an ID, a proper structure should be
{id:"1778",property:"Bras\u00edlia"} and work flawless
give it a try and let us know
EDIT:
as jcaron kindly suggested, i have to fix, this answer: the "1778" is indeed a valid property name, but invalid identifier if dot notation is used.
Since I don't know how jQuery manage this i would suggest to test as above, and see if one of the tests gives results.

Error in Jquery Ajax request, it always executes the error block

I am sending an ajax call to my server, where parameter is "general" or any text, for a search query, why is it always giving error. The response is in JSON, and I have already mentioned it, any issues with the code below? Any help will be highly appreciated
$.ajax({
url : "${kb_endpoint_url}",
dataType : 'json',
data : { search_query : queryValue }, // queryValue = general
success : function(data) {
console.log("success");
},
error: function ( xhr, status, error) {
console.log( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error );
}
This prints: xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined
Edit: I tried changing the type to application/json and now the console prints
xhr.responseText: undefined //status: No conversion from text to application/json //Error: undefined
xhr.responseText: undefined //status: SyntaxError: JSON.parse: unexpected character //Error: undefined
I think ; this error means that the response coming back from your URL is not JSON, there's an error attempting to parse it as such.
Either look in your network panel (easier), or adjust your error handler to see what response your server is actually returning, by looking at the responseText
If the server is returning the text undefined, this is not valid JSON and cannot be parsed.
Only null is valid in JSON format, so trying to parse undefined will give this error.
For examples:
JSON.parse("undefined"); // Throws an error, "Unexpected token u"
JSON.parse("null"); // Returns null
If you comment dataType : 'json', your ajax runs properly. Your response is not in JSON format.
$.ajax({
url : "${kb_endpoint_url}",
dataType : 'json',
type : 'post',
data : { search_query : queryValue }, // queryValue = general
success : function(data) {
console.log("success");
},
error: function ( xhr, status, error) {
console.log( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error );
}
});
Another file (mentioned url )
<?php
echo json_encode($_POST);
?>

Different errors with different browsers in ajax call

What is the reason for this error? How do I fix?
error with Google Chrome :
An error has occured: [object Object] parsererror SyntaxError:
Unexpected token ILLEGAL
error with opera:
An error has occured: [object Object] parsererror SyntaxError:
JSON.parse: Unable to parse value:
error with ie9:
An error has occured: [object Object] parsererror SyntaxError:
Invalid character
and ...
js code:
$('#hotel').keypress(function () {
var dataObj = $(this).closest('form').serializeArray();
$.ajax({
url: 'http://localhost/mehdi/admin/tour/search_hotel',
data: dataObj,
dataType: 'json',
success: function (data) {
$("#suggestion_tab").html('');
$.each(data.suggestions, function (a, b) {
$("#suggestion_tab").append('<li>' + data.b + '</li>');
});
// Display the results
///alert(data);
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
php:(CI_Controller)
function search_hotel(){
$searchterm = $this->input->post('search_hotel');
$result = $this->model_tour->search_hotel($searchterm);
while($row = mysql_fetch_assoc($result))
{
$output[] = $row;
}
echo json_encode(array('suggestions' => $output));
}
CI_Model
function search_hotel($searchterm)
{
return mysql_query("select * from hotel_submits where name LIKE '".$searchterm."'");
}
Your JSON contains invalid syntax.
You need to look at the actual JSON and fix the error.
Also make sure, that your response is in UTF.
This can happen due to session timeout.
Try using http://jsonlint.com/ to see if the JSON packet is valid. It looks to me like you need to json_encode every one of the rows from the database, and then add those encoded packets to another JSON array?

Categories