Can't retrieve jQuery serialized form data wit

2019-07-15 06:50发布

问题:

Using Ajax jQuery function $.post(), I'm sending jQuery serialized() form data to a PHP function which successfully receives it in $_POST[] yet individual $_POST['form_field'] variables are empty.

In my PHP function, print_r($_POST) successfully displays the form data:

Array ( [action] => send_message [data] => modal_name=olivier&modal_email=olivier%40hotmail.com&modal_message=Hello+world )

Yet $_POST['modal_name'], $_POST['modal_email'] and $_POST['modal_message'] are empty. Why?

HTML:

<form id='contact'>
  <input type='text' name='modal_name' id='modal_name' />
  <input type='email' name='modal_email' id='modal_email' />
  <textarea name='modal_message' id='modal_message'></textarea>
</form>

JS:

$('#contact').on('submit', function(e) {
  e.preventDefault();
  if (modal_name && modal_email && modal_message) {
    var data = {
      action: 'send_message',
      data: $(this).serialize()
    };
    $.post(WPaAjax.ajaxurl, data, function(response) {
      $('.modal').append(response);
    });
  }
});

回答1:

use $(this).serializeArray() instead of $(this).serialize()

Reference:- https://api.jquery.com/serializeArray/

The difference between both:-https://stackoverflow.com/a/10430571/4248328

You need to do like below:-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id='contact'>
  <input type='text' name='modal_name' id='modal_name' />
  <input type='email' name='modal_email' id='modal_email' />
  <textarea name='modal_message' id='modal_message'></textarea>
  <input type="submit" value = "submit">
</form>

<script type="text/javascript">
$('#contact').on('submit', function(e) {
  e.preventDefault();
  if (modal_name && modal_email && modal_message) {
     var data = $(this).serializeArray();
     data.push({name: 'action', value: 'send_message'});
     $.post('query.php', data, function(response) {
      $('.modal').append(response);
    });
  }
});
</script>

And in php:-

<?php

if(!empty($_POST)){
    echo "<pre/>";print_r($_POST);
}
?>

It will output like this:-

<pre/>Array
(
    [modal_name] => sdsadsa
    [modal_email] => a@gmail.com
    [modal_message] => sadada
    [action] => send_message
)

Note:- if you want to use serialize()only then do like below:-

<script type="text/javascript">
$('#contact').on('submit', function(e) {
  e.preventDefault();
  if (modal_name && modal_email && modal_message) {
     var data = $(this).serialize()+ '&action=send_message';
     $.post('query.php', data, function(response) {
      $('.modal').append(response);
    });
  }
});
</script>


回答2:

You should use $_POST['data']['modal_name'], $_POST['data']['modal_email'] and $_POST['data']['modal_message'] instead. Also use $.serializeArray() from jQuery.

The reason is that you send form data as param called data.