How to send image to PHP file using Ajax? How to send image to PHP file using Ajax? ajax ajax

How to send image to PHP file using Ajax?


Use JavaScript's formData API and set contentType and processData to false

$("form[name='uploader']").on("submit", function(ev) {  ev.preventDefault(); // Prevent browser default submit.  var formData = new FormData(this);      $.ajax({    url: "page.php",    type: "POST",    data: formData,    success: function (msg) {      alert(msg)    },    cache: false,    contentType: false,    processData: false  });    });


Here is code that will upload multiple images at once, into a specific folder!

The HTML:

<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php"><input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" /><button type="submit" id="btn">Upload Files!</button></form><div id="response"></div><ul id="image-list"></ul>

The PHP:

<?php$errors = $_FILES["images"]["error"];foreach ($errors as $key => $error) {if ($error == UPLOAD_ERR_OK) {    $name = $_FILES["images"]["name"][$key];    //$ext = pathinfo($name, PATHINFO_EXTENSION);    $name = explode("_", $name);    $imagename='';    foreach($name as $letter){        $imagename .= $letter;    }    move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" .  $imagename);}}echo "<h2>Successfully Uploaded Images</h2>";

And finally, the JavaSCript/Ajax:

(function () {var input = document.getElementById("images"),     formdata = false;function showUploadedItem (source) {    var list = document.getElementById("image-list"),        li   = document.createElement("li"),        img  = document.createElement("img");    img.src = source;    li.appendChild(img);    list.appendChild(li);}   if (window.FormData) {    formdata = new FormData();    document.getElementById("btn").style.display = "none";}input.addEventListener("change", function (evt) {    document.getElementById("response").innerHTML = "Uploading . . ."    var i = 0, len = this.files.length, img, reader, file;    for ( ; i < len; i++ ) {        file = this.files[i];        if (!!file.type.match(/image.*/)) {            if ( window.FileReader ) {                reader = new FileReader();                reader.onloadend = function (e) {                     showUploadedItem(e.target.result, file.fileName);                };                reader.readAsDataURL(file);            }            if (formdata) {                formdata.append("images[]", file);            }        }       }    if (formdata) {        $.ajax({            url: "submit_image.php",            type: "POST",            data: formdata,            processData: false,            contentType: false,            success: function (res) {                document.getElementById("response").innerHTML = res;            }        });    }}, false);}());

Hope this helps


Post both multiple text inputs plus multiple files via Ajax in one Ajax request

HTML

<form class="form-horizontal" id="myform" enctype="multipart/form-data"><input type="text" name="name" class="form-control"><input type="text" name="email" class="form-control"><input type="file" name="image" class="form-control"><input type="file" name="anotherFile" class="form-control">

Jquery Code

$(document).on('click','#btnSendData',function (event) {    event.preventDefault();    var form = $('#myform')[0];    var formData = new FormData(form);    // Set header if need any otherwise remove setup part    $.ajaxSetup({        headers: {            'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')        }    });    $.ajax({        url: "{{route('sendFormWithImage')}}",// your request url        data: formData,        processData: false,        contentType: false,        type: 'POST',        success: function (data) {            console.log(data);        },        error: function () {        }    });});