2

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.

2
  • tried echo json_encode($name);? btw: header should be before any output. Commented Mar 22, 2016 at 6:33
  • I hve tried your advice but stil not work. Any advice? Commented Mar 22, 2016 at 6:44

1 Answer 1

2

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

4 Comments

You should not access the superglobal $_POST array directly, use a filter function instead e.g. $str = filter_input(INPUT_POST, 'str');
@Paramjeet I have try it but still now Show My variabel?
@Uchsun it can't show 'NAME' it is undefined because you are using ajax post that's why you only access jquery ajax datastring not your form data
@Paramjeet so how can I access that 'NAME' variable? can i Acces it with forceach or something?

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.