Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery, add value to array in each loop

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
}
like image 535
elclanrs Avatar asked Mar 22 '11 00:03

elclanrs


1 Answers

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);
      });
});
like image 56
Jon Avatar answered Oct 19 '22 05:10

Jon