Do you have a PHP variable $ _POST that is set to an array?

I use AJAX to host some data in my database. I use JSON to send data to a PHP page. I am using a POST request. Can you set one of the POST variables as an array? Below I have a full AJAX request, but here is the part where I set the two pieces of data as arrays:

"content[]" : testContentArray,
"content_attr[]" : testContentAttributes,

Below is my full AJAX (using jQuery):

$.ajax({
                type: "POST",
                url: "../includes/create_test_main.ajax.php",
                data:   {"tags" : $('#testTags').val(),
                                         "title" : $('#testTitle').val(),
                                         "subject" : $('#testSubject').val(),
                                         "description" : $('#testDescription').val(),
                                         "content[]" : testContentArray,
                                         "content_attr[]" : testContentAttributes,
                                         "user_id" : user_id},
                success: 

                                     function(testId) {//redirect Page
                                        window.location.href = "http://localhost/nvr_forget/public_html/test/" + testId + "/";
                                     }
            });
        };

If this is the way to do this, how will I handle it on the PHP side? treat the $ _POST variable as a regular array?

+3
source share
4 answers

data $.ajax, name[]=value. $.param, :

jQuery.param({'foo': [1, 2, 5]})
// "foo%5B%5D=1&foo%5B%5D=2&foo%5B%5D=5"

%5B %5D uri. . PHP , :

var_export($_POST['foo']);
// array ('1', '2', '5')

, $_POST['content'] $_POST['content_attr'] . , , , .

. PHP.

+3

, - ( ), . JSON, .

, JSON:

var data = {
    'a': 'test123',
    'b': [
        'x',
        'y',
        'z'
    ],
    'c': {
        'testing': 'abc',
        'blah': 'qwerty'
    }
}

$_POST :

  • $_POST['a'] - test123,
  • $_POST['b'] - (array('x','y','z')),
  • $_POST['c'] - , (array('testing'=>'abc','blah'=>'qwerty')),
0

You can send an object from JS (JSON) and json_decode on the server (PHP) using json_decode.

0
source

Maybe you can do it, but you should do it completely manually:

{
    "content[0]": "a",
    "content[1]": "b",
    "content[2]": "c",
    "content[multi][0]": "d"
}

$_POST['content'] will look like this:

Array(
    0 => "a",
    1 => "b",
    2 => "c",
    multi => Array(
        0 => "d"
    )
)

It would be much simpler:

{
    "blob" : JSON.stringify(data_or_array_or_whatever)
}

In PHP you can get it:

$data = json_decode($_POST['blob'], true);

This requires the json2.js library for older browsers.

I would go after the latter, as in the first you are likely to write your own serializer: P - that is why we have JSON.

0
source

All Articles