Amoeba
Amoeba

Reputation: 1583

POST for textual data and a file

I was trying to submit a HTML form that includes text fields and an image file using AJAX and jQuery. So it turns out you cannot do file upload using AJAX. Are there any nice ways to submit text form data along with a file? I'm aiming for broad browser compatibility, particularly with older IE versions.

One way I've tried is to eliminate using AJAX and simply use normal POST (although AJAX is the preferred way). After the POST another page loads. I can redirect the browser to load another page from my PHP using

header("Location: new_page.html");

but after this, how can I send the JSON response to the JavaScript script on new_page.html. If I do something like this, will the response now go to the JS script on new_page.html?

header("Location: new_page.html");
$data = json_encode(response);
echo $data

Upvotes: 0

Views: 54

Answers (1)

Quentin
Quentin

Reputation: 944147

So it turns out you cannot do file upload using AJAX.

That isn't true

I can redirect the browser to load another page from my PHP using

The Location HTTP header accepts an absolute URI only. Most browsers will silently recover from that error, but you shouldn't let that be a reason to make it.

after this, how can I send the JSON response to the JavaScript script on new_page.html.

You don't. You generate that page programatically and build it in the state that the JavaScript would have put it in if you had run it after the page had loaded.

Loading a page that immediately fetches data with JSON to update itself is just cutting corners. You end up with the flash-of-default-content problem that used to plague Twitter (before they started building pages server side on initial load and using Ajax only to update them when the view changed).

Upvotes: 2

Related Questions