samedi 27 juin 2015

Send array from php to js with ajax and json

I am trying to send an array from php (that i have taken from a mysql table to js).Although there a lot of examples out there i can't seem to make any of them work. The code that i have reached so far is:

php_side.php

<!DOCTYPE html>
<html>
<body>

<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");

$con = mysqli_connect("localhost","root","","Tileiatriki"); 
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);


/*while($row = mysqli_fetch_array($result)) {
     echo $row['User1_number'];
     echo "<br/>";
     echo $row['User2_number'];
         echo "<br/>";
     echo $row['canvas_channel'];
         echo "<br/>";
}*/
echo json_encode($result);

    mysqli_close($con);
    ?>
    </body>
    </html>  

test_ajax.html

    $(document).ready(function(){
      $.getJSON('php_side.php', function(data) {
        $(data).each(function(key, value) {
            // Will alert 1, 2 and 3
            alert(value);
        });
     });
   });

This is my first app that i use something like this, so please be a little patient. Thank you!

Aucun commentaire:

Enregistrer un commentaire