vendredi 28 septembre 2018

How to specify data field in JQuery AJAX form submission?

I need my HTML form data to arrive at the server via a JQuery AJAX POST request in exactly the same format as if the form had been submitted by a normal submit. I've tried using $.serialize() and $.serializeArray(), and neither gives the simple

$('#booking-form').on('submit', function(e) {
   var formdata = $(this).serialize();
   // process data and send ajax request
   console.log(formdata);

   $.ajax({
       headers: { 'X-CSRF-TOKEN': $('#booking-form > input[name="_token"]').val() },
       type: 'POST',
       url: 'book',
       data: { data: formdata },
       success: function (data)
           {
           // Redirect to booking confirmation page:
           if(data.response == 'ok') window.location.replace(data.url);
           else alert('Card payment failed)
           },
       error: function (data) // Server error
           {
           console.log('Error:', data.responseText);
           }
       });

    // Prevent form submit.
    return false;
});

Backend is Laravel (5.4) but I think this is not a Laravel-specific issue. Logging a normal form submit gives:

array (
  'code' => '2ZSSAVGXAHMOOKGOC0SC',
  'ownername' => 'My Name',
  'housestreet' => '12 Any street, London',
  'city' => 'London',
  'ownerpcode' => 'ZipCode Here',
  'phone' => '1234567890'
)

That's the structure I'm after. But code above gives:

array (
  'data' => 'code=BUH1HGXDWW84SWGWSO84&ownername=My+Name&housestreet=12+Any+street%2C+London&city=London&ownerpcode=Zipcode+here&phone=1234567890')

or using $.serializeArray() gives:

array (
  'data' => 
  array (
    0 => 
    array (
      'name' => 'code',
      'value' => 'CC22DPHQ2F40G0GCKKK0',
    ),
    2 => 
    array (
      'name' => 'ownername',
      'value' => 'My Name',
    ),
    3 => 
    array (
      'name' => 'housestreet',
      'value' => '12 Any street, London',
    ),
etc.

How to get the data in the right format on the server over AJAX (using JQuery or plain JS)? I can't hand code the form fields into the data: parameter in the $.ajax call as some of them are dynamically generated on the server and some by JS on the front end, and include array fields for PHP to parse (e.g. form field name="item[0][extra][]")

Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NbMuG2
via IFTTT

Aucun commentaire:

Enregistrer un commentaire