Tuesday, March 5, 2019

Ajax: Simplest json call

The simplest of all:

var url = 'http://test.com/php/getnews.php';

  $.getJSON(url, function(result) {
    console.log(result);
    $.each(result, function(i, field) {
      console.log(i + ':' + field.title);
    });
  });

and the corresponding php on the server:

$query = "SELECT * FROM news";
  $rows = array();

  if($result = mysqli_query($link, $query)) {
      while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
      }
   
      header('Content-Type: application/json');
      print json_encode($rows,
      JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_FORCE_OBJECT );
   
  }

No comments:

Post a Comment