How to upload image or file using php and ajax

How to upload image or file using php and ajax, Php tutorial

For upload image using php and ajax Step : 1 , for example index.php file is as below

<!--script src="https://code.jquery.com/jquery-2.1.4.js"><!--/script>
<!--form id="upload-form" method="post" enctype="multipart/form-data" onSubmit="return upload(this);">
 <!--input id="upload-form-file" name="userfile" size="27" type="file" />
 

<!--input type="submit" name="submit" value="OK" /> <!--/form>

Step:2 ajax script as below

 <!--script>
 
 function upload(form) {
            $form = $('#upload-form');
            fd = new FormData();
            console.log();
            fd.append('userfile',jQuery('#upload-form-file')[0].files[0]);
            fd.append('name','rj');
           
            jQuery.ajax(
                'uploader.php?action=uploadimg',
                {
                type: 'post',
                processData: false,
                contentType: false,
                data: fd,
                dataType: "json",
                success: function(data) {
                    alert( data.message );
                    console.log(data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert( "ERROR" );
                    alert( textStatus );
                    alert( errorThrown );
                }
            });
            return false;
        }
 <!--/script>
 

Step 3: for handle ajax request below is sample php file uploader.php

if(isset($_REQUEST['action']))
{
  $textUpload = "";

  if ($_FILES['userfile']):
      $uploadfile = __DIR__ . '/uploads/image.jpg';
    if (move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)) {
      $textUpload = "File is uploaded";
    } else {
      $textUplaod = "Upload fail";
    }
  endif;
  exit();
}
?>

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0