0

I am using Javascript to do a GET request on a php page, but when I try to parse the php page as JSON, I get the following error:

Uncaught SyntaxError: Unexpected token < 

I imagine because at the bottom of the PHP page, the following comment exists:

<!-- url here compressed/chunked Tue Sep  4 17:15:42 PDT 2012 -->
ChocoDeveloper
  • 14,160
  • 26
  • 79
  • 117
egidra
  • 8,537
  • 19
  • 62
  • 89
  • 1
    I don't recall seeing this phenomenon before. What causes this comment to happen? – Christian Sep 05 '12 at 00:31
  • "PHP page" is confusing. Pages are in HTML, that can be generated by your PHP script, and sent as a HTTP response to your HTTP request. So when you try to parse it in Javascript, it doesn't matter how the response was generated. This shouldn't be tagged as 'php'. – ChocoDeveloper Sep 05 '12 at 01:13
  • Well, due to the nature of the question, I think it might be ssome specific PHP + web server configuration that adds the comment the O.P. asks about. I would tend to re-insert `php` as a tag, even if to migrate the question to serverfault.com – jsbueno Sep 10 '12 at 18:01

2 Answers2

1

The comment in the PHP file is a HTML comment and should not be sent within a JSON response (it should only contain plain JSON)

You can either

a) remove the comment from the PHP file completely or

b) put it within a PHP section (using PHP-style comments)

<?php /* url here compressed/chunked Tue Sep  4 17:15:42 PDT 2012 */ ?>

<?php
// url here compressed/chunked Tue Sep  4 17:15:42 PDT 2012
?>

I don't think, you'll need this information in the JSON, do you?

Mark
  • 6,033
  • 1
  • 19
  • 14
  • I think that "how to remove" said comment is exactly what the O.P. asks for - and it does not look like it is explicit in his PHP source file. – jsbueno Sep 10 '12 at 18:03
-1

Assuming you have no control over the data provider. Also, it is poor form to put HTML comments in a json response. Any meta definitions like that should be in the actual header information.

In JS just split the string at the index of

function(data){

      var jsonString = data.substring( 0, data.indexOf("<!"));    
      var jsonObject = JSON.parse( jsonString);

}

In the case of < being a valid character in the data, do a regex for HTML comments. see this post.

Community
  • 1
  • 1
FlavorScape
  • 13,301
  • 12
  • 75
  • 117