GetJSON parser cannot handle JSON output from PHP file

I have a php script that returns the following json from my SQL Server:

<?php $server = "DEVTEST-PC\\SRVCLT"; $options = array("UID"=>"sa","PWD"=>"1234","Database"=>"Test"); $conn = sqlsrv_connect($server, $options); if ($conn === false) die("<pre>".print_r(sqlsrv_errors(), true)); //echo "Successfully connected!"; $result = sqlsrv_query($conn,"SELECT Currency, USDRate FROM Pax.CurrencyRate WHERE GBPRate BETWEEN 80 AND 800;"); if($result === false) { die( print_r( sqlsrv_errors(), true) ); } while( $row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC) ) { $myArray['paxcurjson'][] = $row; } echo json_encode($myArray); ?> 

The output is as follows:

 {"paxcurjson":[ {"Currency":"AFN","USDRate":49.5}, {"Currency":"ALL","USDRate":103.567}, {"Currency":"BDT","USDRate":77.562}, {"Currency":"DZD","USDRate":79.6146}]} 

I use jquery to parse it, but for some reason it does not understand. My code is as follows:

 <script type = "text/javascript" language = "javascript" > var url = 'CurrencyQuery.php'; $.getJSON(url, function(data){ for (i = 0; i < data.paxcurjson.length; i++) { console.log(data.paxcurjson[2].Currency); }; }); </script> 

The only error message I get from the console is:

08: 52: 52.661 item not found1 CurrencyQuery.php: 24: 4

This basically refers to my PHP script returning json. I have no idea why this is not working. I checked JSON with an online validator, and it seems like OK and jQuery, everything should be fine. Can someone give me a hint?

+5
source share
2 answers

Thanks to everyone, I understood the solution. I had to wrap the JSON encoded data from my php script in a callback function. Then I could get the data. I'm not sure if this is the best way to deal with this problem, but for now it works :)

0
source

You need to tweak the PHP outputs a bit to handle it using Javascript or JQuery

 <?php //just set a header before output header('Content-Type:application/json;'); echo json_encode($myArray); 

it always works for me.

one more thing when you need to use PHP output as a JSON API for parsing in jQuery etc. I suggest you set the error handling to false, because errors displayed by PHP can cause json output to not be read by jQuery

0
source

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


All Articles