0

I've built this custom form where users can click on buttons to configure their own product. This data is then sent with AJAX to my PHP backend (Wordpress) where it is processed and stored in the database. I'd like to allow users to upload files as well, but how can I send this file and the JSON data I have right now with the same POST request to the backend?

configurationData is an array that stores the selected components. detailsFormData contains name, email etc. in the same format.

Javascript that handles the AJAX request:

$.post(
    stac.ajax_url, {
      'action': 'add_configuration',
      'nonce': stac.nonce,
      'configurationData': configurationData,
      'detailsFormData': detailsFormData,
    },
    function( response ) {
      if( response.success ) {
        // do some fancy things
      } else {
        // more stuff
      }
    }
  );

This works fine, but obviously it doesn't let users upload a file yet. I've tried a bunch of tutorials but those only allow a file upload and nothing else, so no json data. Also tried some stuff with var formData = new FormData(this); and adding some settings (processData: false, contentType: false and cache: false), but that posts a single javascript object and I'm not sure how to handle that in the backend.

EDIT: I've seen the links, but they do not explain how I can add this to the data that's being sent: 'action': 'add_configuration', 'nonce': stac.nonce, 'configurationData': configurationData, 'detailsFormData': detailsFormData,

EDIT2: Can just append these in the same way that formData is appended. Should work now, haven't handled it in the backend yet though.

Pharetra
  • 302
  • 4
  • 17
  • Does it have to be the in the same post? – user2085143 Nov 29 '16 at 11:02
  • Yeah, I want to send the data and the file at the same time. – Pharetra Nov 29 '16 at 11:03
  • 2
    Possible duplicate of [jQuery AJAX file upload PHP](http://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Peon Nov 29 '16 at 11:06
  • post your formData tries as it is the way you will be going for uploading data mixed with files – leoap Nov 29 '16 at 11:07
  • please check this link,may it will help you visit http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – aditya mukkawar Nov 29 '16 at 11:17
  • @DainisAbols I saw that post earlier, but didn't think it worked because I didn't see where the other data would be added. Apparently I could just append it in the same way as formdata is appended. Thanks! – Pharetra Nov 29 '16 at 11:52

0 Answers0