Upload a File using Jquery Ajax code

Upload a File using Jquery Ajax code

JavaScript| How to upload a File using Jquery Ajax code step by step:

Step 1:

Include https://code.jquery.com/jquery-2.2.4.min.js in the page where you want to use it.

Step 2:

Configure below code.

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Step 3:

Create a simple Form with few fields.

<form action="upload.php" method="post" enctype="multipart/form-data" id="upload_new_file_frm">
  <p>
    <label>Name</label>
    <input type="text" name="name" value="" />
  </p>
  <p>
    <label>Attach File</label>
    <input type="file" name="attach_file" value="" />
  </p>
  <p>
    <input type="submit" value="Submit Form" />
  </p>
</form>

Step 4:

Adding jQuery Ajax method code as below.

<script language="javascript">
$(document).ready(function(){

  $("form#upload_new_file_frm").submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser

    var formData = new FormData(this);
    var form = $(this);

    // Adding spinner while submitting form.
    $("form#upload_new_file_frm").after('<div class="form_submit_loader">Please wait submitting...</div>');

    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: formData,
      enctype: 'multipart/form-data',
      processData: false,  // Important!
      contentType: false,
      cache: false
    }).done(function(response) {
      $(".form_submit_loader").remove();
      if(response.status == "success") {
        // On success response do your stuff here...
      } else {
        // On error response do your stuff here...
      }
    }).fail(function(data) {
      $(".form_submit_loader").remove();
      console.log("call failed");
    });
  });
});
</script>

Step 5:

Here is server side PHP code to move and upload physical file in a particular folder location.

Create a file upload.php and add below code.
<?php
// new filename
$filename = 'pic_'.date('YmdHis') . '.jpeg';

$url = '';
if( move_uploaded_file($_FILES['attach_file']['tmp_name'],'upload/'.$filename) ){
  $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/upload/' . $filename;
}

// Return image url
echo $url;
?>

Complete code in one shot as below.

<form action="upload.php" method="post" enctype="multipart/form-data" id="upload_new_file_frm">
  <p>
    <label>Name</label>
    <input type="text" name="name" value="" />
  </p>
  <p>
    <label>Attach File</label>
    <input type="file" name="attach_file" value="" />
  </p>
  <p>
    <input type="submit" value="Submit Form" />
  </p>
</form>

<script language="javascript">
$(document).ready(function(){

  $("form#upload_new_file_frm").submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser

    var formData = new FormData(this);
    var form = $(this);

    // Adding spinner while submitting form.
    $("form#upload_new_file_frm").after('<div class="form_submit_loader">Please wait submitting...</div>');

    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: formData,
      enctype: 'multipart/form-data',
      processData: false,  // Important!
      contentType: false,
      cache: false
    }).done(function(response) {
      $(".form_submit_loader").remove();
      if(response.status == "success") {
        // On success response do your stuff here...
      } else {
        // On error response do your stuff here...
      }
    }).fail(function(data) {
      $(".form_submit_loader").remove();
      console.log("call failed");
    });
  });
});
</script>

<?php
// new filename
$filename = 'pic_'.date('YmdHis') . '.jpeg';

$url = '';
if( move_uploaded_file($_FILES['attach_file']['tmp_name'],'upload/'.$filename) ){
  $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/upload/' . $filename;
}

// Return image url
echo $url;
?>

Any query? Please share your thoughts in the comments below. Glad to help you!
Thanks!

Was this page helpful? Do not forget to share this post!

Leave a Reply

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