0

I have this code which should convert it's results to json. I want to get the array with js and print it.

$db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
$statement=$db->prepare("SELECT * FROM myfeilds");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

How can I do this ?

$(document).ready(function() {
    $.ajax({
        type : 'POST',
        url : 'server.php',
        success : //........
    }); 
});
kent
  • 6,286
  • 4
  • 27
  • 32
Toprex
  • 155
  • 1
  • 9
  • 3
    Possible duplicate of [How to pass an array using PHP & Ajax to Javascript?](http://stackoverflow.com/questions/7263052/how-to-pass-an-array-using-php-ajax-to-javascript) – Farzher Feb 14 '17 at 08:50

2 Answers2

3

You have to echo the something in server side to return the ajax

PHP:

    $db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
    $statement=$db->prepare("SELECT * FROM myfeilds");
    $statement->execute();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    $json=json_encode($results);
     echo $json;

    ?>

Ajax :

$(document).ready(function() {
      $.ajax({
        type : 'POST',
        url : 'server.php',
        dataType:"json",
        success : function (data) {

            alert(JSON.stringify(data));
           }
        }
      }); 
    });
JYoThI
  • 11,977
  • 1
  • 11
  • 26
  • thanks ...How can I print it on the table or div ? This means that for each variable in a special section can print – Toprex Feb 14 '17 at 10:07
  • take look at here http://stackoverflow.com/questions/4189365/use-jquery-to-convert-json-array-to-html-bulleted-list @Toprex – JYoThI Feb 14 '17 at 10:30
1

Ok so you seem to have got enough downvotes but I am also guessing you're fairly new so here's my little help:

PHP:

$db = new PDO('mysql:host=localhost;dbname=Contact', 'root', '');
$statement=$db->prepare("SELECT * FROM myfeilds");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

return $json; // Return this back to your browser
?>

Javascript / jQuery:

$(document).ready(function() {
  $.ajax({
    type : 'POST',
    url : 'server.php',
    dataType:"json",
    success : function (data) {
       for ( var d in data ) {
          var column1 = data[d].column1;
       }
    }
  }); 
});

You might want to have a look at the documentation on ajax...

Morgs
  • 1,558
  • 3
  • 19
  • 34