JSON

Permalink
I'm calling a tools file using JQuery the tool is running an sql query which returns a JSON object formed by the array of results from the query.

the php script from the tools file looks like this
$db = loader::db();
      $res = $db -> Execute('select description, isbn from btBookList where title = ?', array($title));
      $count = $res->RecordCount();
      if($count > 0)
      {
         $output = array();
            foreach($res as $row)
            {
               $output['isbn'] = $row['isbn'];
               $output['desc'] = $row['description'];
            }
         echo json_encode($output);
      }
      else
      {


If I output the JSON string it looks like this
{
"isbn":"9780553573404",
"desc":"The King needs a new hand and only Lord Eddard Stark will do. Winter is Coming"
}


which is a legal string as far as I can tell. The following code should then post the corresponding isbn value

$.get(url, data, function(response){
      if(response == 'invalid')
      {
            alert('no such book title');
      }
      else
      {
            alert(response.isbn);
      }
    })


but all I get is "undefined"

 
JohntheFish replied on at Permalink Best Answer Reply
JohntheFish
Some ideas.

1. Output a json header

2. 'exit;' the tool immediately after echoing the json.

3. Look at the Network tab of the developer console and check the response there.

4. Add console.log(response) and see what it says in the developer console log

5. Use the higher level jQuery getJSON method

6. concrete5 has a json helper that is more portable than the php json_encode (though that is a bit of an out of date argument these days)

7. concrete5 has an AJAX helper (added in 5.6.1, see release notes and code).
JohntheFish replied on at Permalink Reply
JohntheFish
Ajax helper (pull accepted and now closed, incorporated into 5.6.1, but no documentation yet)

https://github.com/concrete5/concrete5/pull/783...
ShadowDancer replied on at Permalink Reply
John, you are, as always, a leg-end. Outputting the JSON header fixed the whole thing.