jameshwart lopez
jameshwart lopez

Reputation: 3131

send file using ajax with other type of input

i already had a form which uses ajax to save the the data to the database. so i have this sample

Html code

<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>

Javascrip Code

$("#btnSave").click(function(){
    p_name = $("#product_name").val();
    p_des = $("#product_description").val();
    p_image = $("#product_img").prop('files')[0];
    data = {
       'product_name':p_name,
       'product_description':p_des
    }

   $.post('url_here',data,function(response){
       console.log(response);
   });
});

i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.

Upvotes: 0

Views: 75

Answers (1)

Buzinas
Buzinas

Reputation: 11725

You can use FormData:

document.getElementById('btnSave').addEventListener('click', function() {
  var fd = new FormData();
  fd.append('product_name', document.getElementById('product_name').value);
  fd.append('product_description', document.getElementById('product_description').value);
  fd.append('product_name', document.getElementById('product_img').files[0]);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'url_here');

  xhr.addEventListener('load', function(e) {
    console.log(xhr.responseText);
  });

  xhr.send(fd);
});

UPDATE

Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:

$('#btnSave').click(function() {
  p_name = $('#product_name').val();
  p_des = $('#product_description').val();
  p_image = $('#product_img').prop('files')[0];

  var data = new FormData();
  data.append('product_name', p_name);
  data.append('product_description', p_des);
  data.appned('product_img', p_image);


  $.ajax({
    url: 'url_here',
    data: data,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(response){
      console.log(response);
    }
  });
});

Upvotes: 1

Related Questions