Upload File Using Ajax With Code Examples

  • Updated
  • Posted in Programming
  • 6 mins read

Upload File Using Ajax With Code Examples

This article will reveal by way of examples tips on how to resolve the Upload File Using Ajax error .

// add jquery
// <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="nameless"></script>
$(doc).prepared(operate() {
  $("#type").on('submit', (operate(e) {
      url: $(this).attr('motion'),
      kind: "POST",
      information: new FormKnowledge(this),
      contentType: false,
      cache: false,
      processData: false,
      success: operate(response) {
        $("#type").set off("reset"); // to reset type enter fields
      error: operate(e) {

The similar downside Upload File Using Ajax might be fastened by using an alternate methodology, which shall be mentioned in additional element together with some code samples under.

$('#add').on('click on', operate() {
    var file_data = $('#sortpicture').prop('information')[0];   
    var form_data = new FormKnowledge();                  
    form_data.append('file', file_data);
        url: 'add.php', // level to server-side PHP script 
        dataType: 'textual content',  // what to anticipate again from the PHP script, if something
        cache: false,
        contentType: false,
        processData: false,
        information: form_data,                         
        kind: 'submit',
        success: operate(php_script_response){
            alert(php_script_response); // show response from the PHP script, if any
**1. index.php**
    <span id="msg" type="shade:purple"></span><br/>
    <enter kind="file" id="picture"><br/>
  <script kind="textual content/javascript" src="jquery-3.2.1.min.js"></script>
  <script kind="textual content/javascript">
        var property = doc.getElementById('picture').information[0];
        var image_name = property.identify;
        var image_extension = image_name.break up('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid picture file");

        var form_data = new FormKnowledge();

if($_FILES['file']['name'] != ''){
    $check = explode('.', $_FILES['file']['name']);
    $extension = finish($check);    
    $identify = rand(100,999).'.'.$extension;

    $location = 'uploads/'.$identify;
    move_uploaded_file($_FILES['file']['tmp_name'], $location);

    echo '<img src="'.$location.'" peak="100" width="100" />';
$(".submitbtn").on("click on", operate(e) {

    var type = $("#Form");

    // you may't cross Jquery type it must be javascript type object
    var formData = new FormKnowledge(type[0]);

    //should you solely have to add information then 
    //Grab the File add management and append every file manually to FormKnowledge
    //var information = type.discover("#fileupload")[0].information;

    //$.every(information, operate() {
    //  var file = $(this);
    //  formData.append(file[0].identify, file[0]);

    if ($(type).legitimate()) {
            kind: "POST",
            url: $(type).prop("motion"),
            //dataType: 'json', //unsure however works for me with out this
            information: formData,
            contentType: false, //that is requireded please see solutions above
            processData: false, //that is requireded please see solutions above
            //cache: false, //unsure however works for me with out this
            error   : ErrorHandler,
            success : successHandler
var formData = new FormKnowledge($("#YOUR_FORM_ID")[0]);
    url: "add.php",
    kind: "POST",
    information : formData,
    processData: false,
    contentType: false,
    beforeSend: operate() {

    success: operate(information){

    error: operate(xhr, ajaxOptions, thrownError) {
       console.log(thrownError + "rn" + xhr.statusText + "rn" + xhr.responseText);
$information = array();
    //test together with your logic
    if (isset($_FILES)) {
        $error = false;
        $information = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $information[] = $uploaddir . $file['name'];
            } else {
                $error = true;
        $information = ($error) ? array('error' => 'There was an error importing your information') : array('information' => $information);
    } else {
        $information = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);

    echo json_encode($information);

We have demonstrated, with a plethora of illustrative examples, tips on how to deal with the Upload File Using Ajax downside.

Can we add file utilizing AJAX?

html file via a browser, the consumer will be capable of add a file to the server utilizing Ajax and pure JavaScript.27-Dec-2021

What are the methods for AJAX file add?

AJAX File Upload – Quick Tutorial & Time Saving Tips

  • Setting up an XMLHttpRequest occasion.
  • Setting up numerous handlers on the XMLHttpRequest object.
  • Setting up a again finish to just accept information from the AJAX request.
  • Validating the shape.
  • Setting up an environment friendly suggestions loop for the viewers.

Can we add picture utilizing AJAX?

You can use jquery. type. js plugin to add picture by way of ajax to the server.18-Oct-2013

How add AJAX file to MVC?

//string filename = Path. GetFileTitle(Request. Files[i]. FileTitle);File Upload Through JQuery AJAX In ASP.NET MVC

  • FormKnowledge.
  • FormKnowledge.
  • FormKnowledge.
  • FormKnowledge.
  • FromData.has(): It returns a Boolean worth whether or not a given secret’s current inside object.

How do I add an HTML file?

The <enter kind=”file”> defines a file-select discipline and a “Browse” button for file uploads. To outline a file-select discipline that enables a number of information to be chosen, add the a number of attribute. Tip: Always add the <label> tag for finest accessibility practices!

What is an AJAX file?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it’s the usage of the XMLHttpRequest object to speak with servers. It can ship and obtain info in numerous codecs, together with JSON, XML, HTML, and textual content information.19-Sept-2022

What is AJAX in JavaScript with instance?

AJAX permits net pages to be up to date asynchronously by exchanging information with an online server behind the scenes. This signifies that it’s attainable to replace components of an online web page, with out reloading the entire web page.

Can we use AJAX in JavaScript?

AJAX simply makes use of a mixture of: A browser built-in XMLHttpRequest object (to request information from an online server) JavaScript and HTML DOM (to show or use the info)

What is the extension of AJAX file?

Ajax (programming)

How can I add a file with out type?

It is sort of a “multipart/form-data” add with out a type. You also can add the file instantly as content material contained in the physique of the POST request utilizing xmlHttpRequest like this: var xmlHttpRequest = new XMLHttpRequest(); var file = file deal with var fileName = file name27-Oct-2013

Leave a Reply