jQuery AJAX file upload PHP

ajax form submit with file upload in php
ajax file upload jquery example
upload image using ajax in php example
javascript ajax file upload example
upload image ajax jquery, php mysql
how to insert image in database using ajax in php
jquery post file upload
uploading both data and files in one form using ajax?

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.

This is my HTML part:

<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>

and this is my JS jquery script:

$("#upload").on("click", function() {
    var file_data = $("#sortpicture").prop("files")[0];   
    var form_data = new FormData();
    form_data.append("file", file_data);
    alert(form_data);
    $.ajax({
        url: "/uploads",
        dataType: 'script',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(){
            alert("works"); 
        }
    });
});

There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".

When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?

Can someone help my finding out whats wrong?

Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running in the browser) sends the form data to the server, then a script on the server handles the upload. Here's an example using PHP.

Your HTML is fine, but update your JS jQuery script to look like this:

$('#upload').on('click', function() {
    var file_data = $('#sortpicture').prop('files')[0];   
    var form_data = new FormData();                  
    form_data.append('file', file_data);
    alert(form_data);                             
    $.ajax({
        url: 'upload.php', // point to server-side PHP script 
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',
        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that runs on the server and directs the file to the uploads directory:

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

    // this is where the file is temporarily stored on the server when uploaded
    // do not change this
    $_FILES['file']['tmp_name'],

    // this is where you want to put the file and what you want to name it
    // in this case we are putting in a directory called "uploads"
    // and giving it the original filename
    'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
    $_FILES['file']['tmp_name'],
    'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

AJAX Image and File Upload in PHP with jQuery, In this article, I will show you how you can add PHP file upload functionality on your website using jQuery, AJAX and MySQL. How to Create Image and File Upload in PHP with jQuery AJAX Prerequisites. The Process of File Uploading in PHP. Create the HTML Form. Using jQuery & AJAX for File Upload Form. Configure and Connect MySQL Database With PHP. Create PHP Script for File Uploading. Check if there are any errors in

var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
    url: "upload.php",
    type: "POST",
    data : formData,
    processData: false,
    contentType: false,
    beforeSend: function() {

    },
    success: function(data){




    },
    error: function(xhr, ajaxOptions, thrownError) {
       console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});

Ajax File Upload with Form Data using PHP, I use jQuery AJAX to implement image upload. There is a form with file input field and a submit button. On submitting the form with the selected  The upload.php file is called by the Ajax request to handles the file upload process with PHP. Retrieve the file information from posted data using the PHP $_FILES method. Upload the file to the server using move_uploaded_file() function in PHP.

**1. index.php**
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

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

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
    $test = explode('.', $_FILES['file']['name']);
    $extension = end($test);    
    $name = rand(100,999).'.'.$extension;

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

    echo '<img src="'.$location.'" height="100" width="100" />';
}

PHP AJAX Image Upload, Are you looking for Ajax file upload PHP script? Uploading a file through Ajax is trending stuff nowadays. In this article, we show you how to  File Upload Handling – AJAX jQuery Add below jQuery, AJAX code immediate after the jQuery library inside <head/> section of the HTML page. We call the server side PHP script using AJAX technique and show message accordingly whether success or failure.

and this is the php file to receive the uplaoded files

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

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

    echo json_encode($data);
?>

Ajax File Upload With PHP And jQuery, Introduction. File can be uploaded using page submit in PHP. Sometimes we need to upload using jQuery and AJAX. This blog post helps to upload file using​  PHP File Upload Using jQuery and Ajax When we upload the files in PHP it means we move the files from one location to another. Generally, if we talk about the PHP file upload, then we know that in every request of the client to the server, the server returns the response with the required data.

Use pure js

async function saveFile() 
{
    let formData = new FormData();           
    formData.append("file", sortpicture.files[0]);
    await fetch('/uploads', {method: "POST", body: formData});    
    alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)

Simple file upload using AJAX and PHP, Learn here to upload images using Ajax and PHP without page refresh. This file upload tutorial is very helpful to implement the upload functionality. Ajax File Upload with Form Data using PHP Create Database Table. To store the file name and other form field’s data, Database Configuration (dbConfig.php) The dbConfig.php file is used to connect and select File Upload Form with Ajax Request (index.html) Initially, an HTML form is

Ajax Image Upload using PHP and jQuery, Use this Ajax file upload PHP script on your website. The jQuery form plugin makes it possible to upload files without a desired page refresh. Tag: php,jquery,ajax,file-upload I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms over the past few days. I have come to a problem with file uploads however when trying to upload images.

Ajax file upload PHP / jQuery Tutorial, I will show you how to upload a file using PHP, AJAX and jQuery without page refresh. This file upload tutorial example is very helpful to implement the upload  How to upload Image file using AJAX and jQuery 1. HTML. Create a <form > element where added <img >, file element and a button. 2. CSS. Hide the img element. 3. PHP. Create an upload.php file and upload directory for storing image files. 4. jQuery. On the upload button click get the selected file

AJAX File Upload using PHP, jQuery, With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers. FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+ For more detail, see MDN link. improve this answer. edited Apr 30 '14 at 4:17.

Comments
  • Please read this first : stackoverflow.com/questions/166221/…
  • Everything works for me, maybe it's your PHP code?
  • there is nothing else "connected" with this form. what do you mean with my php code?
  • What I mean is, your code works, maybe the problem is in your server side code.
  • Are you getting an 500 error code upon executing the AJAX script? That would indicate that it is a server side error. Also: make sure that while debugging, you output the PHP file's response to the console. That way, if your PHP code throws an error, you know what's going on.
  • hey BloodyKnuckles! thanks, i think this was one big thing, i misunderstood. So i added the php file, and now i am a little closer. The second alert also pops up! but the folder is still empty.
  • Ah, the form input name "sortpic" is changed to "file" in the form_data.append function. So I changed the PHP script to reflect the new form input name. I also pulled the PHP script response into the ajax success alert to help with debugging.
  • Buddy, it give me error undefined index file at $_FILES['file']
  • @partho , the code prop('files')[0] accesses the local file intended for upload to the server. If you need more explanation look up jQuery function "prop" and "html5 file upload".
  • I resolved this issue.The reason for it was the filesize was too large.
  • What is the if (true) doing? Is always evaluating to true, so is useless, isn't it? Also you have an extra end-curly.
  • I fixed it for you. :)