Kresten
Kresten

Reputation: 838

How to access form data as an array of a JSON object in PHP

I have jQuery Ajax sending form data to a WordPress function.

The PHP function gets the data as a string, like "navn=A&navn2=B", and I use the explode() function to access individual form elements.

I think there is a better way where I can access the form data as an array of JSON objects directly. But I can't figure that out.

How can I fix it?

This is my HTML/jQuery:

<form id='minForm' method="post" action="">
  <input type="text" name="navn" value="A">
  <input type="text" name="navn2" value="B">
  <button>Send</button>
</form>

<script>
  jQuery(document).ready(function($) {
    var form = $('#minForm');
    $(form).submit(function(event) {
      event.preventDefault();
      var formData = $(form).serialize();
      $.ajax({
        type: "POST",
        url: '/wp-admin/admin-ajax.php',
        data: {
          action     : 'my_ajax_action',
          formData   : formData,
        },
        success:function(data) {
          console.log(data);
        },
      });
    });
  });
</script>

This is my PHP:

add_action('wp_ajax_my_ajax_action', 'my_ajax_action_callback');

function my_ajax_action_callback() {
  $form_data = $_POST['formData'];
  $form_data_array = explode('&', $form_data);

  foreach ($form_data_array as $i) {
    echo explode('=', $i)[1] . '<BR>';
  }
  wp_die(); // Required. to end Ajax request.
}

Upvotes: 0

Views: 1442

Answers (1)

C&#233;sar Ferreira
C&#233;sar Ferreira

Reputation: 681

Serialize your form as an array. Then pass it in the Ajax request.

In the client side:

jQuery(document).ready(function($) {

      var form = $('#minForm');
      $(form).submit(function(event) {
        event.preventDefault();
        var formData = $(form).serializeArray();
        $.ajax({
          type: "POST",
          url: '/wp-admin/admin-ajax.php',
          dataType: 'json',
          data: {
            action     : 'my_ajax_action',
            formData   : formData,
          },
          success:function(data) {
            console.log(data);
          },
        });
      });
    });

On the server side:

add_action('wp_ajax_my_ajax_action', 'my_ajax_action_callback');

function my_ajax_action_callback() {
  $response = ["success" => true];
  $form_data = json_decode($_POST['formData']);
  error_log(print_r($form_data, 1)); // Log to see the array properties.
  if (empty($form_data) {
      $response["success"]  = false;
  }
  echo json_encode($response);
  //wp_die(); // required. to end AJAX request.
}

Note: The $(form).serializeArray() will give you the form as an array of objects, and it might not be what you expect in the server side to extract data. You can handle the form array before sending to the server by convert it to a simple object:

var formData = $(form).serializeArray().reduce(function(obj,item){
     obj[item.key] = item.value;
     return obj;
}, {});

Upvotes: 1

Related Questions