Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from PHP array via AJAX and jQuery

Tags:

I have a page as below:

<head> <script type="text/javascript" src="jquery-1.6.1.js"></script> <script type="text/javascript"> $(document).ready( function() { $('#prev').click(function() {   $.ajax({   type: 'POST',   url: 'ajax.php',   data: 'id=testdata',   cache: false,   success: function(result) {     $('#content1').html(result[0]);   },   }); }); }); </script> </head> <body> <table> <tr> <td id="prev">prev</td> <td id="content1">X</td> <td id="next">next</td> </tr> </table> </body> 

and a php file ajax.php to handle ajax requests as;

<?php $array = array(1,2,3,4,5,6); echo $array; ?> 

But when I click, I am getting A instead of array[0]. How can I fix this?

like image 650
Alfred Avatar asked Jun 18 '11 11:06

Alfred


People also ask

How to pass array to ajax call in JavaScript?

This question already has answers here:ajax({ type: "POST", url: "index. php", success: function(msg){ $('. answer'). html(msg); } });

What is array in ajax?

An Array is used to store multiple values in a single variable. This can be used to pass the group of related values as data to the $. ajax for processing and get the response. E.g. pass all checked checkboxes values, selected values from the list.


1 Answers

you cannot access array (php array) from js try

<?php $array = array(1,2,3,4,5,6); echo json_encode($array); ?> 

and js

$(document).ready( function() {     $('#prev').click(function() {         $.ajax({             type: 'POST',             url: 'ajax.php',             data: 'id=testdata',             dataType: 'json',             cache: false,             success: function(result) {                 $('#content1').html(result[0]);             },         });     }); }); 
like image 160
genesis Avatar answered Sep 23 '22 11:09

genesis