1

I need to create an array of associative arrays for sending the same to php script as ajax post. How do I do that?

To be a little more specific, I have rows of two inputs named "First Name" and "Last Name". When I press submit button, this should generate an array like:

var name_array = [{"first_name" : string1, "last_name" : string2},
 {"first_name" : string3, "last_name" : string4},
 .
 .
 .]

I will then send this array to php through ajax post. If the above construct is made then what should be the syntax for sending name_array as data to the php script?

2

1 Answer 1

0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
    var hold_data = {};
    $(document).on('click','#submit',function()
    {
        $("#myform .field").each(function()
        {
            hold_data[$(this).attr('name')] = $(this).val();
         });
        var json_data = JSON.stringify(hold_data);
        alert(json_data);

         $.ajax(
         {
             url:'', //url location for where you want to submit the data
             type:'post',
             data:{form_data:json_data},
             success:function(res)
             {
                 alert("Successfully sent and your response "+res);
              }
          });
      }); 
});
</script>
</head>

<body>
<form id="myform" action="">
  First name: <input type="text" class="field" name="FirstName"  value="Tom"><br>
  Last name: <input type="text" class="field" name="LastName" value="Raze"><br>
  <input type="button" id="submit" value="Submit">
</form>
</body>

Incase if you are posting to a php page then you can decode the json data as shown below.

The temp value being echoed will be shown as the response res data in ajax

<?php

if(isset($_POST['form_data']))
{
    $temp = json_decode($_POST['form_data']);
    echo temp;
}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. This work just the way I wanted. Thanks again Wilson

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.