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 : //........
    }); 
});
1

2 Answers 2

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));
           }
        }
      }); 
    });
Sign up to request clarification or add additional context in comments.

2 Comments

thanks ...How can I print it on the table or div ? This means that for each variable in a special section can print
take look at here stackoverflow.com/questions/4189365/… @Toprex
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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.