Communiquez avec les autres et partagez vos connaissances professionnelles

Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.

Suivre

How to pass array of values from php to JS using Ajax and json?

user-image
Question ajoutée par Shameer Ahmed , Software developer , Callystro infotech pvt.ltd
Date de publication: 2013/10/28
Ihab Yaktine
par Ihab Yaktine , Head of Software Development , Inimoney

in your ajax call, you need to specify the data type; for example:

$.ajax({ url:url, type:"POST", data:data, dataType:"json", success:function(){...}})and in your php file, make sure to json_encode your response (note that you might need to set your response headers to application/json)

Muhammad Majid Saleem
par Muhammad Majid Saleem , Senior PHP Developer / Project Manager , SwaamTech

It is very simple to pass a PHP array to JS using Ajax and Json. You can send an array from PHP using JSON_ENCODE function from PHP and get it using JSON_DECODE function in JS.

 

Here is a simple example:

JS

$.post("example.php", { user_id:10 } , function( data ){       

    alert( data.user_info.user_id );

    alert( data.user_info.user_name );

   // Do something as per your logic.}, "json");

 

exmple.php

<?php

$q = "SELECT * FROM users WHERE user_id = ".$_POST['user_id'];

$r = mysql_query( $q  );

$user_info = mysql_fetch_array( $r, MYSQL_ASSOC );

echo json_encode( array( "user_info" => $user_info ));

?>

 

Enjoy coding :) !!

Instead of using an array, you should use an object literal (~= assoc array in php).

You can email me the code if need more help I will have a look and feel then we will suggest you something better..

 

More Questions Like This

Avez-vous besoin d'aide pour créer un CV ayant les mots-clés recherchés par les employeurs?