how to upload image using ajax jquery code example

Example 1: ajax file upload jquery

$('#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
        }
     });
});

Example 2: upload image ajax demo

$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        fd.append('file',files);

        $.ajax({
            url: 'upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    $("#img").attr("src",response); 
                    $(".preview img").show(); // Display image element
                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
});

Example 3: jquery ajax upload image

$(function() {
            $("#imagepicker").change(function(e) {
                e.preventDefault();
                var file_data = $(this).prop('files')[0];
                var form_data = new FormData();

                form_data.append('file', file_data);
                form_data.append('action', 'ajax_image_upload');

                $.ajax({
                    url: 'upload.php',
                    type: 'post',
                    contentType: false,
                    processData: false,
                    data: form_data,
                    success: function(response) {
                        console.log(response);

                    },
                    error: function(response) {
                        console.error(response.responseText);
                    }

                });
            });
        });

Example 4: Upload image via ajax (jquery)

var form = new FormData();
form.append('varName','data');
$.ajax({
  type:'POST',
  url: $(this).attr('action'),
  data:formData,
  cache:false,
  contentType: false,
  processData: false,
  success:function(data){
    //function here
  },
  error: function(data){
    //function here
  }
});