简体   繁体   中英

Most efficient way for JSON or JS object to be passed along with Form Data via AJAX POST to PHP

On the face, it may appear that this is a repeat question. Please note that I have read through all the related posts and did not find any definite answer and/or the issue here is very different. Even some direction to some post or material clarifying the issues with specificity would be helpful. I am not looking for spoon feeding.

Here is the issue:

I have a form and I have some other meta-data (for lack of a better term) to be sent to the server which consists of configuration parameters. These are required along with the form data to be processed by a PhP back-end and return some complex JS and HTML markup.

Admittedly I am not a regular user of JSON but my reading pointed to using JSON for the non-form data and have the form data serialized separately and assign it to another property, as in:

var ser_data = $(form_selector).serialize();

var meta_data = { //Just for example
    name: 'John Doe',
    age:    62,
    address: '22 Park Avenue'
};

And then pass the data in .ajax as:

data_sent = data_sent = {'meta_data':meta_data, 'form_data':ser_data};

some_promise = $.ajax({
       url : '../php/json_test.php', 
       dataType: 'json',
       type : 'POST',
       cache    : false,
       data : data_sent
});

On the PhP side, I have to navigate $_POST[] at multiple levels to get to the data. Also, the form data loses the implicit URL decoding.

Of course, one way could be to manually construct the serialized string to be appended to the form serialized string as in

form_data_serialized...&name='John doe'&age=62... 

Am I on the wrong track all together? Is there an approach that is better and simpler? THANKS!

Why not do this the other way around? Create your metadata as a JSON string and add it to a hidden input field in your form, then POST that. Your form data is decoded into $_POST and you can extract and decode your JSON metadata from there.

.serialize simply creates a param string, for example, foo=bar&foobar=2 . with this in mind, adding your additional params is basic string concatenation.

var data_sent = $.param(meta_data) + "&" + ser_data;

Convert meta_data into a param string, then append your serialized form data to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM