Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript - javascript

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.

Related

Cannot read property '0' of undefined using ajax to get json data

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?

shift() and pop() is not a function

So i was making a random quote generator machine project for learning purposes and encountered a error.
I tried looking for it in other answers but couldn't understand/solve it.
here is the JS code:
$('#new').on('click', function(e) {
e.preventDefault();
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback',
success: function(data) {
console.log(data);
var post = data.shift(); // The data is an array of posts. Grabbing the first one.
$('.author').text(post.title);
console.log(post.title);
$('.quote').html(post.content);
console.log(post.content);
},
cache: false
});
});
For the first console.log it shows data in form of array, So I tried pop and shift functions to extract the data. here is the format of data:
/**/mycallback([{"ID":1640,"title":"Scott Belsky","content":"<p>To envision what will be, you must remove yourself from the constant concern for what already is.<\/p>\n","link":"https:\/\/quotesondesign.com\/scott-belsky\/","custom_meta":{"Source":"<a href=\"http:\/\/the99percent.com\/book\">book<\/a>"}}])
It gave undefined for the next 2 console.log() .
Here is the error:
Uncaught TypeError: data.shift is not a function
and it gave errors on both functions. any help would be appreciated.
Two things:
Don't define the callback function. Leave that to $.ajax by replacing the explicit function name to ?
Set the data type to jsonp
$.ajax( {
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?',
dataType:'jsonp',
cache: false,
success: function(data) {
console.log(data);
var post = data.shift();
console.log(post);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

Ajax can success() handle two type of return?

Working in a C# ASP.NET project with JavaScript/Jquery/jqGrid.
New task is to have a page to i) accept an Excel input file, ii) use the column ID to look up additional information, and iii) generate a new Excel file using some columns from input file and all columns returned from database.
I have completed that, but just want to do a bit more error handling. In the stored procedure, if everything works fine, it returns a data table (or in Oracle term, a CURSOR). If there is an error, I have added a catch block and return an error message.
I modify the AJAX call. Beside adding dataType as 'text', I expect the return as XML.
$.ajax({
// POST
// URL: url to call that stored procedure
dataType: text,
success: function (response) {
// now the response is XML (don't know why...
// specify dataType as 'text', but get XML...)
// If response contains 'string' tag, report error.
},
failure: ...
})
Here is what I used to do. I don't specify the dataType but somehow that works.
$.ajax({
// POST
// ... rest is same but without the dataType
success: function (response) {
Download( response )
// The file is already and placed in Download directory.
// Call 'Download()' will actually make the download happen
// But here response is just a path to the Download directory +
// download file name.
And Download() is:
function Download(url) {
document.getElementById('my_iframe').src = <%=ResolveUrl("~/")%> +url;
return false
};
How can I have the success function handle both type of response?
(Just for your information: The front-end page is ASP.NET. Button click will call a JavaScript function. The function calls a web service function via $.ajax(). As there are many rows, the web service function calls a function in a database class many times - each time pass in just one ID. The function will in return call stored procedure.)
Edit: Thanks for solution from Mustapha Larhrouch. Here are some points that I have to adjust:
Add dataType.
If response is XML, check if error.
If not XML, just download.
And here is my code:
$.ajax({
// POST
// URL
dataType: "text",
success: function (response) {
if (isXML(response)) {
var xmlDoc = $.parseXML(response);
$xml = $(xmlDoc);
var errMsg = $xml.find("string").text();
if (errMsg != "" ) {
// pop up a dialog box showing errMsg
}
}
else {
Download(response);
}
you can check if the response is an xml if it's parse it, if not the response is a string. and you can use this function to check if the response is an xml :
function isXML(xml){
try {
xmlDoc = $.parseXML(xml); //is valid XML
return true;
} catch (err) {
// was not XML
return false;
}
}
$.ajax({
// POST
// ... rest is same but without the dataType
success: function (response) {
if(isXML(response){
Download( response )
}
else{
//report as error
}

AJAX request in ColdFusion

How can I do a AJAX request in ColdFusion?
I have my javascript:
function getdata(){
var formElements=document.getElementById("CFForm_1").elements;
var data=[];
for (var i=0; i<formElements.length; i++){
if(formElements[i].name == 'customersid')
data.push({'customersid':document.getElementById("customersid").value});
if(formElements[i].name == 'customerstoid')
data.push({'customerstoid':document.getElementById("customerstoid").value});
}
$.ajax(
{
type: "get",
url: "components/BillingCalc.cfc",
data: {
method:"ajaxGetTotalCost",
data: data.join()
},
dataType: "json",
success: function( objResponse ){
}
});
}
My component:
component displayName="Calc" {
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
I am getting the error: JSON parsing failure at character 2:'o' in [object Object],[object Object]
Does anyone knows how to do AJAX request in CF?
This function:
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
WriteDump(data); abort;
}
is not complete. It's at the stage where you have to call it from a ColdFusion page, not with javascript. That will enable you to see the results of the writedump(data) command to ensure it's what you expect. You have to add more code to the function to get it to produce a variable javascript can receive, and then return that variable to whatever is calling the function.
The issue is related to dataType attribute you are passing with $.ajax() method. dataType: "json" indicates your AJAX request is expecting JSON data as a response. But in your case you are simply returning DUMP of the deserialized JSON, which is HTML not JSON. So if you want it to work properly, then you need to return JSON data from your ColdFusion function. You can try this and see if it works.
remote function ajaxGetTotalCost(data){
data = deserializeJSON(arguments.data);
return serializeJSON(data));
}

Can I use jquery ajax response for Autocomplete

It's 3am. I've been banging my head against the wall for hours on this and just don't get it.
I'm trying to use jQuery autocomplete with the source data coming from an ajax request.
Ajax seems to be working great, but I can't seem to use the response for the source data.
Anonymous function fetches data on ready. Success calls test(response) passing the data to the function with autocomplete. The response looks exactly like the sample code. And when I paste my response from the console it works perfectly. But it will not let me use the variable 'albums' for the source.
$(function(){
$.ajax({
dataType: 'text',
type: 'POST',
url: '/albums/fetch_albums',
success: function(response){
console.log(response); // logs ["Italy","Hawaii"] -as expected
test(response);
}
});
});
function test(data){
var albums = data;
console.log(albums); // logs ["Italy","Hawaii"] - as expected
console.log(typeof albums); //logs string - as expected
$('#autocomplete').autocomplete({
source: albums, //this is what I want... errors out.
//source: ["Italy","Hawaii"] // pasted response if un-commented works fine.
});
}
Here is the error message.
GET http://journal.localhost.com/[%22Italy%22,%22Hawaii%22]?term=h 403 (Forbidden)jquery-2.1.1.min.js:4 n.ajaxTransport.k.cors.a.crossDomain.sendjquery-2.1.1.min.js:4 n.extend.ajaxjquery-ui.min.js:7 e.widget._initSource.e.isArray.string.options.source.sourcejquery-ui.min.js:7 e.widget._searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 e.widget.searchjquery-ui.min.js:6 (anonymous function)jquery-ui.min.js:7 (anonymous function)jquery-ui.min.js:6 i
There has to be a way to fetch data from the database and feed it to this function.
Help me Obiwan!
$(function(){
$.ajax({
dataType: 'text',
type: 'POST',
url: '/albums/fetch_albums',
success: function(response){
console.log(response); // logs ["Italy","Hawaii"] -as expected
var arrResponse = JSON.parse(response); //convert json object to array
test(arrResponse);
}
});
});

Categories

Resources