JSON Parse Error: unexpected end of data in row 1 of column 1 of JSON data

I have database web pages, analyt.php and index.php. Analysis.php receives data from the database, sorts it according to the required template, and then echoes json_encode($array); in a div with credentials. I am trying to get JSON data and parse it on the index.php page.

However, I am getting an error. SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

I try to get this data every time the user selects a parameter from the selection window.

My jQuery code:

 $(document.body).on('change', '.select' , function () { var identification = $(this).val(); var JSONText = $(this).closest('div[id|="module"]').find('p[id="JSON"]'); JSONText.load('analysis.php?data=' + identification + ' #data'); console.log("JSON Imported: '" + identification + "'"); var obj = jQuery.parseJSON(JSONText.text()); console.log(JSONText.text()); }); 

EDIT: As you can see, I have a console.log(JSON.text()); fragment console.log(JSON.text()); . The JSON result that I get is correct. The only problem that I think may be that quotation marks are all " instead of JSON quotes other than external quotes.

+3
source share
2 answers

jQuery.load is asynchronous, you are trying to parse JSON before it actually loads. Using jQuery.getJSON loads the content, parses and provides a callback that you can bind to.

jQuery.load loads the content as HTML and sets the innerHTML of the selected element, you can also bind the complete handler, but you may run into problems loading the content in HTML and then using text to extract it from the DOM, as some parts of your JSON may be interpreted as HTML elements.

Better use this:

 $(document.body).on('change', '.select' , function () { var identification = $(this).val(); $.getJSON( 'analysis.php?data=' + identification + ' #data', function (data) { console.log(data); } ); }); 
+6
source

In addition to solving LJ_1102, here is a way to fix your current fragment:

 JSONText.load('analysis.php?data=' + identification + ' #data', function() { console.log("JSON Imported: '" + identification + "'"); var obj = jQuery.parseJSON(JSONText.text()); console.log(JSONText.text()); }); 
+2
source

Source: https://habr.com/ru/post/980621/


All Articles