1

Is it possible to push additional values into a seriazlized $_POST array before sending an AJAX request with jQuery?

This is the scenario:

$('#ajax-preview').on('click', function(e) {
    e.preventDefault();
    var formData = $('#advertiser-edit-form').serialize();
    $.ajax({
       type: 'post' ,
       url: 'ajax-action.php',
       data: formData,
       success: function(data, status, jqXHR) {
           console.log(data);
       }           
    });
});

formData is a serialized $_POST array from a page with multiple key/value pairs. I need to add another pair programmatically, namely ajax: true.

I tried to pass this data set to the AJAX:

var previewData = {
    formData: $('#advertiser-edit-form').serialize(),
    ajax: true
};

Unfortunately, it changes the structure of data that is passed to the PHP script and, in consequence, the data cannot be processed as expected.

luqo33
  • 8,001
  • 16
  • 54
  • 107
  • Cannot you `unserialize` your data, add your pair `ajax: true`, then `serialize` it back? – D4V1D Mar 27 '15 at 16:29
  • Note that checking for an ajax call this way is not very reliable as the user can manipulate it. Checking on the server-side - for example by seeing if a variable in your environment is set - would be more secure. – jeroen Mar 27 '15 at 16:38
  • 1
    See also [Can I add data to an already serialized array?](http://stackoverflow.com/q/14102732/218196) – Felix Kling Mar 27 '15 at 16:38

1 Answers1

2

the $(form).serialize() just return a string so you can simply concat with the value you want to add. Example :

var formData = $('#advertiser-edit-form').serialize();
// Be sure that formData is not empty, if it's you don't need the "&"
formData += '&foo=bar';

https://api.jquery.com/serialize/

Tit-oOo
  • 208
  • 1
  • 9
  • Then use the .serializeArray() function, then push the content you want to add to it. You can call the toString function after having pushed the value to have it as a string https://api.jquery.com/serializeArray/ – Tit-oOo Mar 30 '15 at 07:33
  • This is the right answer, thank you. I also introduced another check to determine if the current request is AJAX with `$_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'` so now I'm checking for the presence of a value in `$_POST` array as well as `$_SERVER`. – luqo33 Mar 30 '15 at 07:53