2

I have this jquery code:

        var myarr = ["aa","ss","dd"];

        $.ajax({
            url: "proces.php",
            data: "arr="+myarr,
            type: "POST",
            success: function () {
                alert("data is send");
            }
        });

I see message data is send but in proces.php file I have this code

$str = '';
foreach ($_POST['arr'] as $k=>$v) {
    $str = $str.$v;
}

$hand = fopen("t.txt","w+");
fwrite($hand,$str);

and in file t.txt nothing is written, please tell where I wrong ?

0

2 Answers 2

5

You can send it as:

$.ajax({
    url: "proces.php",

    data: 'arr=' + JSON.stringify({arr: myarr}),

    type: "POST",
    success: function () {
        alert("data is send");
    }
});

And on the server side, you can read it as:

$arr = jsondecode($_POST['arr']);

foreach($x in $arr->arr) {
   // stuff
}
Sign up to request clarification or add additional context in comments.

1 Comment

The output of JSON.stringify is a string, not an array.
3

If you stringify an array and append it to arr= then you get:

arr=1,2,3

but the standard way of sending an array of data over HTTP is:

arr=1&arr=2&arr=3

PHP has an extra requirement. It expects the name to end in []

arr[]=1&arr[]=2&arr[]=3

Don't try to build the form encoded data yourself. Let jQuery do it. It defaults to generating PHP style key names for arrays and will take care of any escaping needed due to characters which have special meaning in URIs (e.g. if your data included a &).

Change:

data: "arr="+myarr,

to

data:{ "arr": myarr },

Then in PHP $_POST['arr'] will be an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.