How do I send an array from PHP to jQuery?
I have many <input type = "text" id = "search_term" />. How can I send this data to jQuery?
<head>
<script>
$(document).ready(function(){
$('#button1').click(function(){
var search_val=$("#search_term").val();
$.post("ajax.php",
{ search_term : search_val },
function(data) {
$("#search_results").html(data);
}
);
});
});
</script>
</head>
<body>
<input type = "text" id = "search_term" />
<input type = "text" id = "search_term" />
<input type = "text" id = "search_term" />
...
<input type = "button" id = "button1" value = "test" />
</body>
Gert Grenander
17.1k6 gold badges42 silver badges43 bronze badges
asked Aug 6, 2010 at 9:01
lolalola
3,82120 gold badges65 silver badges99 bronze badges
2 Answers 2
You must use JSON.
PHP SCRIPT
echo json_encode($array);
JQuery
$.post("ajax.php", {search_term : search_val},
function(data){
var data=$.parseJSON(data); //Now "data" contains the php array
});
});
answered Aug 6, 2010 at 9:05
mck89
19.3k17 gold badges93 silver badges111 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
The easiest way is to use JSON. From your php, you do json_encode($output) where $output is your array, and in jQuery you use either getJSON() method, or use $.ajax with the option dataType: 'json'.
answered Aug 6, 2010 at 9:06
Bogdan Constantinescu
5,3864 gold badges42 silver badges51 bronze badges
Comments
default