5

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
}
0

1 Answer 1

14

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);
      });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah! I made a mistake, I actually have it inside the submit function in my original code. It's corrected now. I just wanted to know if this is the most efficient way to deal with it. I'm pretty new to jquery and php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.