I am trying to upload a file through AJAX and PHP. I have an HTML form as shown below:
<form method="post" id="sectiononeform" name="sectiononeform" enctype="multipart/form-data"> <div class="clearfix"> <input type="text" name="customHeading1" id="customHeading1" class="span10" value=""/> </div> <div class="clearfix"> <textarea id="elm1" name="elm1" rows="15" class="xxlarge" cols="80" style="width: 80%"> </textarea> </div> <div class="clearfix"> <input type="file" name="file1" id="file1" class="span10" /> </div> <div class="clearfix"> <div class="actions"> <input type="submit" id="saveSection1" name="saveSection1" value="Submit" /> <input type="reset" name="resetSection1" value="Reset" /> </div> </div> </form>
My jquery code is as follows:
$(document).ready(function(){ $("#saveSection1").click(function(e){ e.preventDefault(); var 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"; } var len = document.getElementById("file1").files.length, img, reader, file; for (var i = 0 ; i < len; i++ ) { file = document.getElementById("file1").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) { alert("form data"); formdata.append("customHeading1", document.getElementById("customHeading1").value); formdata.append("elm1", document.getElementById("elm1").value); formdata.append("custsection1", 1); formdata.append("venue_id", document.getElementById("venue_id").value); formdata.append("images[]", file); alert(formdata); } } } var params = $("form#sectiononeform").serialize(); //alert("params" + params); params = params + "&custsection1=1&venue_id=" + $("#venue_id").val() + "&formdata=" + formdata; //alert(params); $.ajax({ type: 'POST', url: 'saveCustomSectionData.php', data: formdata, success: function(data){ alert(data); } }); }); });
My problem is that when I do not use the file input type, I can just serialize the form values and submit it via AJAX. Since I use the file input type, I use formdata and add information to it. This is the right way to send data. I am not getting any response from php and I am not seeing any request in firebug. Instead, I get some foggy error like "Illegal operation on a WrappedNative prototype object". Any suggestions?
source share