Search code examples
phpjqueryjsonpmodx

JSON—Unexpected Identifier


I've built a search for a site I'm working on using JSONP. My code is below:

$(document).ready(function() {

function pSearch() {
    var url = "/pq2";

    $.getJSON(url + "?callback=?", $("#searchform").serialize(), function(data) {
        $("#searchResults").empty();
        console.log(data);
        $.each(data, function(index, value) {
            $("#searchResults").append('<a href="[[~' + value.id + ']]"><h2>' + value.pagetitle + '</h2></a>');
        })
    })
}

$("select").change(pSearch);

});

Users select terms from a multi-select box and a list of pages that meet those terms is returned. Some of the terms work perfectly, others throw the following error in Chrome:

Uncaught SyntaxError: Unexpected identifier

I'm confused as to what would cause some results to work, and others to throw this error. Thank you for your help!

Edit—Generating JSONP the PHP file generates an array and the following line generates JSONP (CMS is MODX):

$final = array();
foreach ($collection as $c) {

      $allowedTvNames = array('tv_names');
      $templateVars = $modx->getCollection('modTemplateVar', array('name:IN' => $allowedTvNames));

      $a = $c->toArray();

      foreach ($templateVars as $tv) {
          $a[$tv->get('name')] = $tv->renderOutput($c->get('id'));
      } 

      $final[] = $a;
}

echo $_GET['callback'] . '(' . json_encode($final) . ')';

Solution

  • Use dev tools in your browser to see the JSONP response, to determine if it is either valid or perhaps throwing up some kind of PHP warning/error.

    In Chrome, go to View > Developer > Developer Tools, open the Network tab, then initiate your JSONP request. Then select "/pq2" in the left-hand pane, and click the "Preview" or "Response" tabs on the right to see what the response was.

    Post it back here if it isn't then obvious what the problem is.