Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

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

user-image
Question added by Shameer Ahmed , Software developer , Callystro infotech pvt.ltd
Date Posted: 2013/10/28
Ihab Yaktine
by 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
by 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 :) !!

Deleted user
by Deleted user

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