0

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.

Community
  • 1
  • 1
jameshwart lopez
  • 2,993
  • 6
  • 35
  • 65
  • If you can't/won't use the `
    ` **tag**, use the `form` **property**.
    – al'ein Oct 06 '15 at 13:31
  • im afraid to do it since i already had many codes for the system im making that doesn't use form tag.i cant afford to redo all my codes before – jameshwart lopez Oct 06 '15 at 13:33
  • http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – epascarello Oct 06 '15 at 13:35
  • Why 'using jquery ajax'? Firstly, you should explain that as soon as you've asked the question. And secondly, if your question changed, open a new question, or, at least, put it as 'UPDATE: I need to use jquery ajax' – Buzinas Oct 06 '15 at 13:37

1 Answers1

1

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);
    }
  });
});
Buzinas
  • 11,597
  • 2
  • 36
  • 58