I have a page as below;
When you do echo $array;
, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.
You might actually need
echo json_encode($array);
This should get you what you want.
EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)
When you echo $array;
, the result is Array
, result[0]
then represents the first character in Array
which is A
.
One way to handle this problem would be like this:
ajax.php
<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
echo $a.",";
?>
jquery code
$(function(){ /* short for $(document).ready(function(){ */
$('#prev').click(function(){
$.ajax({type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data){
var tmp = data.split(",");
$('#content1').html(tmp[0]);
}
});
});
});
quite possibly the simplest method ...
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
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]);
},
});
});
});
you cannot access array (php array) from js try
<?php
$array = array(1,2,3,4,5,6);
echo implode('~',$array);
?>
and js
$(document).ready( function() {
$('#prev').click(function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data) {
result=data.split('~');
$('#content1').html(result[0]);
},
});
});
});