I am using AJAX to put some data in my database. I am using JSON to submit the 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 the full AJAX request, but here is the part where I am setting two parts of the 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 that is the way to do it, how would I handle it on the PHP side? do I handle the $_POST variable as a normal array?
When you pass an array within a
dataobject to$.ajax, it is parsed out intoname[]=valueformat. This is done using$.param, so I’ll illustrate using that:%5Band%5Dare uri-encoded square brackets. This is a common way of sending multiple values for the same key to a server. PHP parses it into an array, so in this case:So in your code,
$_POST['content']and$_POST['content_attr']should both be arrays. The square brackets that you’ve used are unnecessary, but won’t break anything.See the PHP manual on the subject.