Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving serialize data in a PHP file called using AJAX

Tags:

jquery

ajax

php

Form sending AJAX code:

var str = $("form").serialize();
alert(str);
// var uns=@unserialize(str);
//alert(uns);
$.ajax({
    type: "POST",
    url: "update.php",
    data: "box1="+str,
    success: function(value)
    {
        $("#data").html(value);  
    }

HTML Form:

<form>
  <input type=checkbox name=box[] value='1'/><input type=checkbox name=box[] value='2'/>
</form>  

In my PHP:

$box=$_POST['box1'];    

How can I access each of the box variable values in PHP side?

like image 388
MAK Avatar asked Feb 24 '12 12:02

MAK


3 Answers

Provided that your server is receiving a string that looks something like this

    $("form").serialize();
   "param1=someVal&param2=someOtherVal"

...something like this is probably all you need:

    $params = array();
    parse_str($_GET, $params);

$params should then be an array modeled how you would expect. Note this works also with HTML arrays.

See the following for more information: http://www.php.net/manual/en/function.parse-str.php

Hope that's helpful. Good luck!

like image 114
user3230699 Avatar answered Nov 08 '22 12:11

user3230699


Your js should be like this:

var str = $("form").serializeArray();
$.ajax({  
    type: "POST",  
    url: "update.php",  
    data: str,  
    success: function(value) {  
            $("#data").html(value);
    }
});

With php you should loop your result array.

$box = $_POST['box'];
foreach ($box as $x) {
    echo $x;
}

Edit: You have to use serializeArray function in jQuery. Then it will work with this code.

like image 33
rasmusx Avatar answered Nov 08 '22 13:11

rasmusx


your JS should be like this -

var str = $( "form" ).serializeArray();
    var postData = new FormData();
     $.each(str, function(i, val) {
                postData.append(val.name, val.value);
 });
$.ajax({
           type: "POST",
           data: postData,
           url: action,
           cache: false,
           contentType: false,
           processData: false,
           success: function(data){
              alert(data);
          }
    });

Now do this in your php script -

print_r($_POST);

you will get all form data in alert box.

like image 23
Sujit Verma Avatar answered Nov 08 '22 13:11

Sujit Verma