0x1234 0x1234 - 3 months ago 8
PHP Question

How to retrieve echoed data from php when posting form data via jquery ajax?

I want to pass a file from a file input form to a php script via ajax and process the message my php script echoes.

This is my html form:

<form id="fileUploadForm" method="POST" enctype="multipart/form-data">
<input name="fileToUpload" id="fileToUpload" type="file">
<button type="submit" name="submit" id="submit">Upload</button>

my js code:

$('#submit').click(function() {
var file_data = $('#fileToUpload').prop('files')[0];
var form_data = new FormData();
form_data.append('fileToUpload', file_data);
url: 'form.php',
dataType: 'text',
data: form_data,
processData: false,
contentType: false,
type: 'post',
success: function(data) {

and my (simplified) php script:

//some code
echo "Your file is too large!";
echo "Your file has been uploaded";

What I want to achieve is the the user gets a message if the file was uploaded successfully or it was too big/ had wrong extension without reloading the page.


<button type="submit" name="submit" id="submit">Upload</button> change type to button

  1. Because the type is submit and it is in form it is doing the default function of a button type submit not the ajax one