In this article, we will explain how to allow the user to upload an image to the server with jQuery, Ajax, and PHP without having to reload the page and without using third-party plugins.

In the working example, we have a form that contains an image, the field to select a file, and a button to upload. The user can upload an image in png, jpg, or gif format. The image is uploaded to the server and is previewed on the screen without reloading the page after pressing the “Upload” button.

How do we get it?

I’ve been looking for a code like this for a long time that greatly simplifies the process, using fewer resources and with a similar effect. It turns out that it is very simple. We are going to explain it using the example we have created for this tutorial.

Visual appearance or design

The interface or visual aspect is as follows:

upload an image

Achieved without much effort thanks to Bootstrap 4 technology.

JavaScript code required

In the header or within the tag of your page you have to add the jQuery library and the event call:

< script src = "https://code.jquery.com/jquery-3.2.1.js" > </ script > 
< script > 
$ ( document ) . ready ( function ( )  { 
    $ ( ".upload" ) . on ( 'click' ,  function ( )  { 
        var formData =  new FormData ( ) ; 
        var files = $ ( '#image' ) [ 0] . files [ 0 ] ; 
        formData. append ( 'file' , files ) ; 
        $. ajax ( { 
            url :  'upload.php' , 
            type :  'post' , 
            data : formData , 
            contentType :  false , 
            processData :  false , 
            success :  function ( response )  {
                if  ( response ! =  0 )  { 
                    $ ( ".card-img-top" ) . attr ( "src" , response ) ; 
                }  else  { 
                    alert ( 'Bad image format.' ) ; 
                } 
            } 
        } ) ; 
        return  false ; 
    } ) ; 
} ) ; 
</ script >

The above code can also be embedded just before the closing tag.

We are just waiting for the button containing the “upload” class to be clicked to obtain the selected file from the computer to pass it to the “upload.php” file so that it can be processed on the server. Once the image has been processed on the server, if the response is different from 0, the src attribute of our image will be changed to the response. Otherwise, show an error alert.

The key to the issue is in the use of the FormData class.

FormData objects allow you to compile a set of key/value pairs to send using XMLHttpRequest. They are primarily intended for submitting form data but can be used independently to transmit keyed data. The transmitted data will be in the same format that the form submits () method uses to submit the data if the form’s encoding type is set to “multipart / form-data.”

In the example, we are creating an object of type FormData to add the image to it. We pass the FormData object to the PHP file using the Ajax technique. In this way, in the PHP file, we will have the necessary information to process the image.

This code can also be useful for uploading other types of files, just by making some adjustments.

HTML code that you must add inside the body of your page

In the body or within the tag we add the form that allows uploading files:

< form  method = "post"  action = "#"  enctype = "multipart / form-data" > 
    < div  class = "card"  style = "width: 18rem;" > 
        < img  class = "card-img-top"  src = "images / default-avatar.png" > 
        < div  class = "card-body" > 
            < h5  class = "card-title" > Upload a photo <
             class = "card-text" > Upload an image ... < / p > 
            < div  class = "form-group" > 
                < label  for = "image" > New image < / label > 
                < input  type = "file"  class = "form-control-file"  name = "image"  id = "image" > 
            < / div > 
            <input  type = "button"  class= "btn btn-primary upload"  value = "Upload" > 
        < / div > 
    < / div > 
< / form >

It is a simple form that uses the enctype = »multipart / form-data» attribute to allow file uploading and uses Bootstrap technology for design. We only have a default image, the field to select an image from the computer, and a button that allows the upload action to the server.

PHP code running on the server

The “upload.php” file that we use to process the image contains the following:

<? php 
if  ( ( $ _FILES [ "file" ] [ "type" ]  ==  "image / pjpeg" ) 
    ||  ( $ _FILES [ "file" ] [ "type" ]  ==  "image / jpeg" ) 
    | |  ( $ _FILES [ "file" ] [ "type" ]  ==  "image / png" ) 
    ||  ( $ _FILES [ "file" ] [ "type" ]  ==  "image / gif " ) )  {
    if  ( move_uploaded_file ( $ _FILES [ "file" ] [ "tmp_name" ] ,  "images /" . $ _FILES [ 'file' ] [ 'name' ] ) )  { 
        // more code here ... 
        echo  "images /" . $ _FILES [ 'file' ] [ 'name' ] ; 
    }  else  { 
        echo  0 ; 
    } 
}  else  { 
    echo  0 ; 
}

We simply check that the file you are trying to upload is of the correct type. In this case, we just want you to upload images .png, .jpg, or .gif and then use the function move_uploaded_file () of PHP to deposit the selected file in the place we want. We save it with the same upload name.

After this action, many more processes could be carried out, such as registering something in the database or sending an email. Remember that all this can be done without reloading the page.

As an answer, we use the echo function of PHP to return a 0 in case of error or the path of the uploaded file to deposit it in the src as you can see in the success of the Ajax call.

Conclusions

The effect we achieve with this example code can be achieved with countless third-party plugins that are around the Web, but we think that this code can be very useful in extreme cases in which it is necessary to use the least possible resources to make it work or in cases where something simple is needed to allow the user to upload an image. The fact is that third-party plugins usually have an infinite number of options that are not finally used, which makes them very complex and large in size to have them deposited on the server.

Leave a Reply

Your email address will not be published. Required fields are marked *