-2

If I understood correctly, then the following will send the formData to test.php silently in the background.

var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php');
xhr.send(formData);

However, I would like to have the same behavior as if one submits a form with a target="_blank" attribute. So to open test.php with the post data in a new tab.

Daniel
  • 3,383
  • 4
  • 30
  • 61
  • then don't use ajax – slash197 Mar 03 '18 at 09:48
  • @slash197 Thanks. So what could I use instead? I am trying to send form data from a file input with the `multiple` attribute set but want to send each file to a new tab rather than all on one. So I thought I could grab the files and send them via ajax... – Daniel Mar 03 '18 at 09:53
  • why do you want to use ajax then? the whole point of using ajax is to make the page load event invisible and make asynchronous call. – Md. Tazbir Ur Rahman Bhuiyan Mar 03 '18 at 09:55
  • @TazbirBhuiyan Because I don't know of any other client side (javascript) method to send a file via post. Any pointers much appreciated. – Daniel Mar 03 '18 at 09:57

1 Answers1

0

You could use jQuery serialize to serialize the form and then curl the data to your PHP script. Make sure to disable posting the form by disabling your buttons default function, see this post..

Jason
  • 21
  • 4
  • Thanks. However, in the jQuery serialize documentary you refer to it says explicitly that "Data from file select elements is not serialized." Not sure how this is supposed to work then. – Daniel Mar 03 '18 at 18:23
  • 1
    You can try having a variable in your script to store the Blob of the file. On form validation, check to make sure that it is a valid Blob, if valid, append it to your FormData object. To get the Blob from an input element see https://gist.github.com/nolanlawson/62e747cea7af01542479 – Jason Mar 04 '18 at 21:20