0

I use the below code to send data for image file with js and they works great but when I add

 var image = document.getElementById("img_book").files[0];
 var form = new FormData(); 
 form.append("image", image);

I get error with append.

This my code

$("#publish").click(function() {
   var x = event.target.responseText;
   document.getElementById("book_id").setAttribute("value",x);
   var image = document.getElementById("img_book").files[0];
   var form = new FormData(); 
   form.append("image", image);

   var title = document.getElementById("title").value;
   var desc = document.getElementById("desc").value;
   var cat = document.getElementById("cat").value;
   var sub_cat = document.getElementById("sub_cat").value;
   var tags = document.getElementById("tags").value;
   var lang = document.getElementById("lang").value;
   var privacy = document.getElementById("privacy").value;
   var id = document.getElementById("book_id").value;
   //if((title !== "") && (desc !== "") && (cat !== "") && (sub_cat !== "") && (lang !== "") && (privacy !== "")) {
     $.ajax({
       url: "ajax/upload/publish.php",
       method  : "POST",
       data : {'form' : form ,'title' : title,'desc' : desc, 'cat' : cat , 'sub_cat' : sub_cat , 'tags' : tags , 'lang' : lang , 'privacy' : privacy , 'id' : id},
       cache: true,
       success : function(data) {
         if(data.status == 'success'){
          window.location.replace("http://localhost/book/book.php?id=" + id);
        }else if(data.status == 'error'){
          alert("Error on query!");
        }
      }
    });
   //}
 });
4
  • What error do you get? Commented Jun 17, 2016 at 14:56
  • 1
    Post html please. If the structure is what I think it is you have made your code overly complicated. Commented Jun 17, 2016 at 14:57
  • @ksealey my html code just inputs and form Commented Jun 17, 2016 at 15:01
  • @MouradKa I understand, but if all your elements you are getting the values from are in the form, you are writing quite a bit of extra code. I'm trying to save you some time and debugging frustrations in the future. Commented Jun 17, 2016 at 15:04

1 Answer 1

1

You have to append all the parameters to the formdata object, or more easily pass the form containing the data to the from data constructor.

Then pass the formdata object alone in the request, also contentType and processData has to be set to false.

Sign up to request clarification or add additional context in comments.

2 Comments

In your ajax call add the properties processData: false, contentType: false,
If all the data is in a form just do var form = new FormData($("#formid")[0]); then data: form,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.