0

here is my php code which would return json datatype

$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;


function rJSONData($sql,$result){
    $sJSON=array();
    while ($row = mysqli_fetch_assoc($result))
    {
        $sRow["id"]=$row["ID"];
        $sRow["fn"]=$row["posts"];
        $sRow["ln"]=$row["UsrNM"];
        $strJSON[] = $sRow;
    }
    echo json_encode($strJSON);
}

this code would return

 [{"id":"1","fn":"hi there","ln":"karan7303"},
 {"id":"2","fn":"Shshhsev","ln":"karan7303"},
 {"id":"3","fn":"karan is awesome","ln":"karan7303"},
 {"id":"4","fn":"1","ln":"karan7303"},
 {"id":"5","fn":"asdasdas","ln":"karan7303"}]

But how can I access this data in html, that is, I want particular data at particular position for example i want to show 'fn' in my div and 'ln' in another div with another id

Before trying anything else I tried this

$.ajaxSetup({ 
  url: 'exm1.php', 
  type: 'get', 
  dataType: 'json',
  success: function(data){
    console.log(data);          
  }
});

but it shows that data is undefined I don't know what I am doing wrong

Phil
  • 157,677
  • 23
  • 242
  • 245

2 Answers2

0

What you've got should kind-of work if you swapped $.ajaxSetup (which is a global configuration method) with $.ajax. There are some significant improvements you could make though.

For example, your PHP does some odd things around the value returned by rJSONData. Here's some fixes

function rJSONData($result) {
    $sJSON = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $sJSON[] = array(
            'id' => $row['ID'],
            'fn' => $row['posts'],
            'ln' => $row['UsrNM']
        );
    }
    return json_encode($sJSON);
}

and when you call it

header('Content-type: application/json');
echo rJSONData($result);
exit;

Also make sure you have not output any other data via echo / print or HTML, eg <html>, etc


In your JavaScript, you can simplify your code greatly by using

$.getJSON('exm1.php', function(data) {
  console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
  console.error(jqXHR, textStatus, errorThrown);
});
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Its giving parse error parsererror" SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at m.parseJSON (jquery.min.js:4) at Pc (jquery.min.js:4) at x (jquery.min.js:4) at XMLHttpRequest.b (jquery.min.js:4) (anonymous) @ exm.php:35 j @ jquery.min.js:2 fireWith @ jquery.min.js:2 x @ jquery.min.js:4 b @ jquery.min.js:4 – Sahil Verma Apr 12 '17 at 00:28
  • Also I could not use your rJSONData function because it was giving error on sJSON=[]; line So i used mine rJSONData function the previous one – Sahil Verma Apr 12 '17 at 00:29
  • 1
    That worked I found out error was in my php where I used at the beginning and at – Sahil Verma Apr 12 '17 at 00:39
  • @SahilVerma sounds like you're running with a *very* old version of PHP if it doesn't support array literals. I've updated my answer to use the older syntax – Phil Apr 12 '17 at 00:56
  • Actually I am new to all this JSON Ajax PHP stuff So dont really know about the new and old things – Sahil Verma Apr 12 '17 at 01:17
-1

Use $.ajax instead of $.ajaxSetup function.

Here is a detailed answer from another SO post how to keep running php part of index.php automatically?

<script>

$.ajax({
    // name of file to call
    url: 'fetch_latlon.php',

    // method used to call server-side code, this could be GET or POST
    type: 'GET'

    // Optional - parameters to pass to server-side code
    data: {
        key1: 'value1',
        key2: 'value2',
        key3: 'value3'
    },

   // return type of response from server-side code
   dataType: "json"

    // executes when AJAX call succeeds
    success: function(data) {
        // fetch lat/lon
        var lat = data.lat;
        var lon = data.lon;

        // show lat/lon in HTML
        $('#lat').text(lat);
        $('#lon').text(lon);
    },

    // executes when AJAX call fails
    error: function() {
        // TODO: do error handling here
        console.log('An error has occurred while fetching lat/lon.');
    }
});


</script>
Community
  • 1
  • 1
Hamza Rashid
  • 1,329
  • 15
  • 22