user1628206
user1628206

Reputation: 55

Only 1 character instead of the whole word being returned in a PHP array after retrieving from javascript

In Javascript I'm creating an array for a user side list

var dataArr = [];
 $("#sortable li").each(function(idx, elem) {
    dataArr[idx] = $(elem).html();
});
alert(dataArr[0]);

This is working as expected and will alert the first item in the list. "Frank" or whatever it may be.

$.ajax({
url: "fiddle.php",
type: "POST",
data: "dataArr="+dataArr,
success: function(response) {
alert(response);}

I send this array over to PHP and the ajax test confirms its retrieved from a var_dump on the other side.

echo ($_POST['dataArr'][1]);

The problem occurs here when trying to output a particular item, in this case the 2nd item which may be "John" it'll instead output the 2nd character in the first item "r". This is appearing in the Ajax test window. I'm looking for the whole word instead. Is it a syntax error or a problem with how the data is passed?

Upvotes: 0

Views: 180

Answers (2)

Mithun Satheesh
Mithun Satheesh

Reputation: 27855

It is because your array is getting converted to string form.

do JSON.stringify() at client side and json_decode at server side

like

in the ajax call

data: "dataArr="+JSON.stringify(dataArr),

and in the php code

$dataArr = json_encode($_POST['dataArr']);
var_dump($dataArr);

Upvotes: 1

Bavell
Bavell

Reputation: 500

I think the problem is related to how you are sending your data in the ajax call.

Try this:

JS

var dataArr = [];
 $("#sortable li").each(function(idx, elem) {
    dataArr[idx] = $(elem).html();
});


$.ajax({
    url: "fiddle.php",
    type: "POST",
    data: dataArr, //Send just the array
    success: function(response) {
        alert(response);
    }
});

PHP

var_dump($_POST['dataArr']);

Upvotes: 2

Related Questions