

Here, you’re making a post request to imageUpload.php. onload event listener for the xhr object, so it’ll notify the user on the HTML page about the uploading outcome. Going back to the current script, set up an. The backend script will take care of further file processing. Set up an AJAX request with the new XMLHttpRequest() object, and open a POST connection to imageUpload.php. onsubmit event handler, which is the main function in this script, since it waits for a user to submit the form.ĭefine a form object and add a simple validation step to check if the file type is an image. The script starts by saving all the form elements and status into the respective variables using this DOM’s method. Set up a handler for when the task for the request is complete Xhr.open('POST', '/uploadHandling.php', true)

StatusP.innerHTML = 'The file selected is not an image.' įormData.append('fileAjax', file, file.name)

Select only the first file from the input array Var statusP = document.getElementById('status') Var myFile = document.getElementById('fileAjax') // Our HTML files' ID Copy and paste this code: var myForm = document.getElementById('formAjax') // Our HTML form's ID Creating an AJAX scriptĬreate an imageUpload.js file in your AJAX-test project’s folder. Even though we’re pointing the form’s action to the PHP script, we’ll also create a JavaScript that will intercept form submissions and provide asynchronous feedback. In this form, we don’t need to specify the enctype attribute, because it’s only required for text input management (e.g., replacing blank spaces with ‘+’ symbols before sending the string via POST to the server).Īlso, we need to set an id for the input fields, because we’ll refer to this in our AJAX script. The method of sending data to a server is POST. The action form points to a PHP script that processes image file uploading.

It is a straightforward form with a file select input and a submit button:
#Php jquery file upload example code
Creating an HTML formĬreate a folder for the project (e.g., AJAX-upload) in your website’s root directory ( (usually it’ll be something like public_html, htdocs, or Copy & paste the following file-uploading code into your newly created file. Local htdocs folder for AJAX file uploader Step 1. Without further introduction, let’s create an AJAX upload example.
