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?

  • Possible duplicate of [Dynamically creating keys in JavaScript associative array](http://stackoverflow.com/questions/351495/dynamically-creating-keys-in-javascript-associative-array) – Jacques Koekemoer Mar 18 '16 at 12:27
  • You are using jQuery, right? http://stackoverflow.com/a/20150474/2191572 – MonkeyZeus Mar 18 '16 at 12:28

1 Answers1

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

?>
Vijay Wilson
  • 516
  • 7
  • 21