Reputation: 261
I have a form that has both text and file fields. I am trying to submit the whole thing to a php script hosted on the server, and return a validation message. My form looks like this:
<form id="ambassador" method="post" enctype="multipart/form-data">
<label for="name">Name: </label>
<input type="text" id="name"> <br />
<label for="age">Age: </label>
<input type="number" id="age"> <br />
<label for="igram">Instagram Account: </label>
<input type="text" id="igram"> <br />
<label for="photo">Photograph Upload: </label>
<input type="file" id="photo"><br />
<label for="why">Why should you represent Drip Cold Pressed Juice?</label>
<textarea id="why" width="300px"></textarea>
<button type="submit" class="btn">Apply!</button>
</form>
And my jQuery looks like:
jQuery("#ambassador").submit(function(event) {
event.preventDefault
var server = "http://getdripped.com/dev/ambassador.php";
var form = document.getElementById('#ambassador');
var formData = new FormData(form);
alert(formData);
jQuery.ajax({
url: server,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The php contains just a print_r
statement for the $_FILES
array and another for the $_POST
array. However both returned arrays are empty.
Upvotes: 1
Views: 681
Reputation: 1561
Ignore the downvote, and
Set async to true!
You set the async to false. This means that your success callback won't wait for the reply and finishes therefor long before PHP answers.
Also look at this SO Question as there is an answer already if you get into more trouble.
From the jQuery Documentation:
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Quentin was right about the serialize, I deleted the serialize option after further reading.
Upvotes: 0
Reputation: 944538
You have two problems.
document.getElementById('#ambassador');
The getElementById
method takes an id but you are passing it a selector. You need to remove the #
. Currently you are passing null
to new FormData
(because there is no matching element so gEBId returns null
).
<input type="number" id="age">
Form controls can only be successful if they have a name
attribute and none of yours do.
Once you correct the ID, you populate the form data object with all the successful controls in the form: but there aren't any.
You need to add a name attribute to each of your inputs.
Upvotes: 1
Reputation: 21681
I would use an iframe as the target of the form.
<form id="ambassador" method="post" enctype="multipart/form-data" target="form_iframe" >
<iframe name="form_iframe" id="form_iframe" ></iframe>
See also How to make Asynchronous(AJAX) File Upload using iframe?
Upvotes: 0