I have a jQuery app where the user can add items to a list from an input field. I want to put all items in an array when you submit the form so I can manipulate them with php later. Is this the right way to do it?
jQuery:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});
PHP:
$items = $_POST["items"];
foreach($items as $item){
//Something here
}
The idea is sound. What it not very clear is that your example populates items
now, but the submit
handler will of course be called at some point in the future. Is it possible that the list items may have changed by that time?
If so, you need to move the "pack the items" code inside the submit
handler, e.g.:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With