Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send image to PHP file using Ajax?

my question is that is it possible to upload an image to a server using ajax(jquery)

below is my ajax script to send text without page reload

$(function() {
//this submits a form
$('#post_submit').click(function(event) {
event.preventDefault();
var great_id = $("#post_container_supreme:first").attr("class");
var poster = $("#poster").val() ;
    $.ajax({
        type: "POST",
        url: "my php file",
        data: 'poster='+ poster + '&great_id=' + great_id,
        beforeSend: function() {
            $("#loader_ic").show();
            $('#loader_ic').fadeIn(400).html('<img src="data_cardz_loader.gif" />').fadeIn("slow");
        },
        success: function(data) {
            $("#loader_ic").hide();
            $("#new_post").prepend(data);
            $("#poster").val('');
        }

    })
})
})

is it possible to modify it to send images?

like image 818
Dev Man Avatar asked Jan 16 '14 14:01

Dev Man


People also ask

How to show image in AJAX jQuery?

You can append the imagen using jQuery, for example with the first index of array: $('#container'). append('<img src="' + result[0]. file_name + '" />');


1 Answers

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
  });
    
});
like image 74
AleVale94 Avatar answered Sep 17 '22 17:09

AleVale94