I have a site where users can order items. I am currently sending various bits of information to the PHP script so they can be added to the database from there:
$.ajax ({
type: "POST",
url: "./pay.php",
dataType: "json",
data: {
"firstName" : firstName,
"lastName" : lastName,
"email" : email,
"price" : price
}
});
This is working well. Now I would like to send over two arrays that contain the id's and quantities of products that were ordered. Since I don't know how many products there are at any given point or what their id is, I cannot add them as individual items as I have done above. Currently I have the product ID's and their corresponding quantities in separate arrays as such:
productIds: ["6", "1"]
quantities: ["1", "4"]
I would like to send these arrays to the PHP script along with the rest of the variables so I can loop through those arrays and insert the information into the database.
Can I do that like this?
$.ajax ({
type: "POST",
url: "./pay.php",
dataType: "json",
data: {
"firstName" : firstName,
"lastName" : lastName,
"email" : email,
"price" : price,
"productIds" : productIds,
"quantities" : quantities
}
});
The non-array variables I am currently able to access like this in the PHP script:
$email = $_POST['email'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$price = $_POST['price'];
I would like to loop through the productIds array in the PHP script something like this, but I think I am missing something:
$i = 1;
foreach ($_POST['productIds'] as $value) {
$sql = 'INSERT INTO orders SET
product_id = "'.$_POST['productIds'][$i].'",
quantity = "'.$_POST['quantities'][$i].'"';
$result = $conn->query($sql);
$i++;
}
How can I send a javascript array to a PHP script using Ajax along with other non-array data?
$
at the beginning of$i
in the subscripts. – Barmar Apr 14 '13 at 2:02print_r($_POST['productIds'])
to see what's in there? – FluffyJack Apr 14 '13 at 2:04var_dump($_POST)
. – Barmar Apr 14 '13 at 2:04