AJAX FormData Post - 503 Service not available
I have searched for this issue many times with no option or maybe I missed this issue. Please pass on to me anything I can do to improve the explanation.
I have a "File" input that calls a php file using Ajax on 'change' , for example:
$(document).on('change', 'input[name="photo"]', function(){
var file = this.files[0];
var formData = new FormData();
var user = localStorage.getItem("user");
formData.append('_file', file);
formData.append('_user', user);
$.ajax({
type: "POST",
cache: false,
url: ip + "php/insert_img.php",
data: formData,
contentType: false,
processData: false,
success: function (e) {
// do something
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
});
This is supposed to be a phonegap app and I am using the Chrome Ripple Emulator with Apache Cordova / PhoneGap framework for testing.
Now everything works as expected when using localhost and PHP prints formData as it should, however when I use the same PHP file uploaded to the server (hence the ip variable in the Ajax url ) it's a different story.
After a while, the error parameter is returned , and when checking the Chrome Developer Tools> Networking tab, I see the Request Status Code: 503 Service Unavailable. BUT if I change the data strong> parameter to anything other than FormData () it works.
It looks like the problem comes from the server settings, but I don't know what the problem might be.
source to share
I've encountered this issue many times while using AJAX, so here are my initial thoughts:
Is "ip" defined? url: ip + "php / insert_img.php"
Also I found that removing some of the advanced AJAX options fixed the problem. Modified code below:
$(document).on('change', 'input[name="photo"]', function(){
var file = this.files[0];
var formData = new FormData();
var user = localStorage.getItem("user");
formData.append('_file', file);
formData.append('_user', user);
$.ajax({
type: "POST",
url: ip + "php/insert_img.php",
data: formData,
success: function (e) {
// do something
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
});
Hope it helps.
---------- EDIT ----------
After a little searching, I believe the problem is that you are adding data _file
and _user
. If the values โโof this data are an array, you will have to "reinforce" it:
formData.append('_file', JSON.stringify(file));
formData.append('_user', JSON.stringify(user));
source to share