2

I have an array stored in php: $cv1 = array('a','b');

As you can see in the code below, I am trying to get the respective data from the array then delegate it to two separate functions.

But the data returned from the php callback function is: 'Array' instead of 'a','b'; and result[0] gets 'A' result[1] gets 'r' etc.

Thanks for help!

js:

$('a').on('click',function(){
  var cv = $(this).data('cv');
  var url= '_php/myphp.php';
  $.post(url,{contentVar:cv},function(data) {
    result=data;
    return result;
  }).done(function() {
    alert(result[0]);
    $('#myDiv').html(result[1]);
  });
});

php:

$cv1 = array("a","b");

$contentVar = $_POST['contentVar'];

if($contentVar == "cv1")
{
    echo json_encode($cv1);
}
BryanK
  • 1,211
  • 4
  • 15
  • 33

3 Answers3

3

It's common in PHP for you to get "Array" instead of an actual array when it accidentally gets cast to a string. That's not what you're doing here though; we can test:

> $cv1 = array("a","b");
array(2) {
  [0] =>
  string(1) "a"
  [1] =>
  string(1) "b"
}
> json_encode($cv1);
string(9) "["a","b"]"

$cv1 gets encoded correctly.

You must be treating it like a string somewhere else:

> (string)array("a","b")
! Array to string conversion
string(5) "Array"

Also, why do you have two success callbacks in $.post? The 3rd argument is a success callback, which works the same as .done. Use one or the other (I recommend done) but not both.

You may also consider passing json as the last argument (dataType) so that jQuery knows what to expect and will properly decode the result.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
0

Try to do something like this:

$.post(url,{contentVar:cv}
   function(response)
   {
      alert(response[0]);
   },'json'
);
fagace
  • 116
  • 3
0

You need to convert the json string format to a javascript object/array.

var result = $.parseJSON(data);

see this question jQuery ajax request with json response, how to? for more detail.

But there is something strange that, if is returning 'Array', the php is not converting the array to json, what happens if the ($contentVar == "cv1") return false? If you will return an array to javascript you need to convert to a string (and the json format is perfect for this).

Community
  • 1
  • 1
Guilherme
  • 1,980
  • 22
  • 23