Reputation: 33
I develop mobile app using PhoneGap and wanna ask if there is a way to upload a file to server (php) using jQuery's ajax. I use ajax because I want to avoid redirection from a web page (Of course, I want to redirect to my own page). So, here is some of my code:
$.ajax({
url: url,
data: $("#myform").serialize(),
type: "post",
dataType: "json"
});
and I've tried these combinations below but nothing works. Any idea ?
contentType: false
cache: false
processData: false
contentType: "multipart/form-data"
Upvotes: 2
Views: 8733
Reputation: 22425
<script>
$(document).ready(function(){
$('#button').click(function(){
var formData = new FormData($('form')[0]);
alert(formData)
$.ajax({
url: '/testupload2/', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(data){
alert('Done')
},
error: function(jqXHR, textStatus, errorThrown){
alert("Some Error!")
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
</script>
HTML body part:
<body>
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" id ="button" value="Upload" />
</form>
<progress>
progressHandlingFunction()
</progress>
</body>
Upvotes: 1
Reputation: 4541
You'll probably have to use PhoneGap's FileTransfer class.
Documentation and some example code is here: http://docs.phonegap.com/en/2.0.0/cordova_file_file.md.html#FileTransfer
Upvotes: 1
Reputation: 4331
You cannot upload a file using an AJAX call easily.
You could base-encode it or transport it in a different manner, but there are quite a few file upload plugins for jQuery out there that may help you out.
Upvotes: 0