JQuery, add value to array in each loop

I have a jQuery application in which a user can add items to a list from an input field. I want to put all the elements in an array when you submit the form so that later I can process them with php. Is this right to do?

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
}
+5
source share
1 answer

The idea is sound. It is not entirely clear what your example is filling out itemsnow, but the handler submit, of course, will be called at some point in the future. Is it possible that list items could have been changed by this time?

, "pack the items" submit, :

$("#form").submit(function(){
    var items = [];
    $("#items li").each(function(n){
        items[n] = $(this).html();
    });

   $.post(
      "process.php", 
      {items: items}, 
      function(data){
          $("#result").html(data);
      });
});
+13

All Articles