How to GET data From Ajax Jquery serializeArray() in PHP?

I have try to Process Form array with jquery ajax json to php.

my code tesJSONarray.php

<script src='jquery.js'></script>
<script>
  $(document).ready(function(){

      $('.SAVE').click(function(e){
         e.preventDefault(); 

        var str = JSON.stringify($("#COBA").serializeArray());

         alert(str);


           $.ajax({

              type:"POST",
              dataType:"json",
              url:"tesJSONarray2.php",
              data:str,
              success: function(data) {
                   $("#data").html(data);


               },

           });      

      });

  });


</script>

<!--div id='data'></data-->

<form id='COBA' method="post">
  <input type='text' name='NAME[]' class='NAME' value="septiyo"><br>
  <input type='text' name='NAME[]' class='NAME' value="naf'an"><br>
  <input type='submit' value='SAVE' name='SAVE' class='SAVE'>
</form>

And my action file tesJSONarray2.php

$name = $_POST['NAME'];
foreach ($name as $x) {
    echo json_encode($x);
}

header('Content-type: application/json');

but it not work. How Can I process the variable on PHP.?

Usually if I use serialize() I know value from PHP with

echo json_encode($variable);

but with serializeArray() not working.

anyone can help me?

thanks in advance.

Answers 1

  • You can change data :

    <script type='text/javascript'>
        data:{'str':str}
    </script>
    
    <?php
       print_r($_POST) // in json 
       print_r(json_decode($_POST['str'],true)) //for array
    ?> 
    

Related Articles