-1

Alright, I'm trying to get form values via jQuery serialize. Here's my jQuery code.

$("#add_cus_button").click(function(e){
    e.preventDefault();
    //
    $.ajax({
        type: 'POST',
        url:'ajax.php?requestid=14',
        data:{postdata:$("form#addnew").serialize()},
        success: function(response)
        {

        }
    })
});

Here's my PHP :-

$postdata = explode('&', $_POST['postdata']);
var_dump($postdata);

This results into this :-

enter image description here

Now if I try to access a field called customer_name, I do this.

echo $postdata['requestid'];

But this throws undefined index error. How do I overcome this?

Akshay
  • 2,244
  • 3
  • 15
  • 34
  • 2
    Akshay, either turn `xdebug` off, or please post the output as HTML. The `alert` is worthless. Just show us what's there in the Network tab? – Praveen Kumar Purushothaman Dec 03 '15 at 16:28
  • Is 'requestid' really the way to access your customer_name? It sounds like your PHP is getting an undefined index error because it should be `$postdata['customer_name']` – Adam Konieska Dec 03 '15 at 16:32

3 Answers3

1

.seriliaze() will return you a string like a=something&b=whatever... and which works in a GET Request, and not a array or object which you need in a POST request.

To make it return an array use .serializeArray() but even serializeArray wont work in a POST request. So you need to use something like .serializeObject().

Something like this:

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};
void
  • 36,090
  • 8
  • 62
  • 107
0

Just use this:

data: $("form#addnew").serialize()

This already is a serialized version. You don't need to add {key: serialized_value}. Or if you really wanna use a data object, use serializeArray() and send it to the PHP, but in the PHP, don't use the below line:

$postdata = explode('&', $_POST['postdata']); // Don't use this.
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

1st: you need to use

data:$("form#addnew").serialize(),

2nd: if this serialize looks like this

"varname=val&var2=val2"

in php

<?php
   echo $_POST["varname"];
   echo $_POST["var2"];
 ?>

take a look at How do I PHP-unserialize a jQuery-serialized form?

Community
  • 1
  • 1
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28