ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

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

user-image
تم إضافة السؤال من قبل Shameer Ahmed , Software developer , Callystro infotech pvt.ltd
تاريخ النشر: 2013/10/28
Ihab Yaktine
من قبل 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
من قبل 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..

 

المزيد من الأسئلة المماثلة