0

i got an ajax function that calls a php who returns an array:

<?php
$testing = array("one","two","three", "four");   
echo json_encode($testing);        
?>

i call it with this ajax call;

$.ajax({
url:"ajax_response.php",
type:"POST",   
success:function(msg)
{
  var array = msg;    
  var test = array[2];      
  alert(test);
}
});

the problem is that i want to get array[1] as "one" and im geting 1 character on every array position ex: array[0] = "o", array[1] = "n", array[2] = "e". Its like the json encode or semething is spliting my array variables into characters.

Any help ??

Thanks in advance

Erwin Moller
  • 2,375
  • 14
  • 22
Albert Prats
  • 786
  • 4
  • 15
  • 32

2 Answers2

2

You have to parse your answer. Easiest way would be to put a dataType to your AJAX call:

$.ajax({
    url: "ajax_response.php",
    dataType: 'json', // add the dataType
    type: "POST",   
    success: function(msg) {
        var array = msg;    
        var test = array[2];      
        alert(test);
    }
});

Or you can parse it "by hand". This is sometimes necessary:

success: function(msg) {
    var array = JSON.parse(msg); // or parse it manually
    var test = array[2];      
    alert(test);
}
Bruno Schäpper
  • 1,262
  • 1
  • 12
  • 23
-2

your response is in string format try this at your success function

success:function(msg)
{
  var array ;
 eval('array ='+msg );  
  var test = array[2];      
  alert(test);
}
Rupesh Patel
  • 3,015
  • 5
  • 28
  • 49