I am using jquery ajax to retrieve some data, but it fails, below are the codes:
$.Webpic_Init = function(){
var type = 'default';
$.ajax({
url:SITE_PATH+"services/service.php?m=share&a=uploadwebpic&photo_type="+type,
type: "POST",
data:{ name: "John", location: "Boston" },
cache:false,
dataType: "json",
success:function(result){
alert(result);
},
error:function(){
alert('error');
}
});
}
this alerts 'error'. But if I change the url parameter to 'SITE_PATH+"services/service.php"', the 'success' event was dispatched. So what can I do, if I don't want to change the url parameter?
You are making a POST request all your fields should be in the data object like you have made.
data:{ name: "John", location: "Boston" }
You should not be putting anything on the url. Thats for GET request.
Prepend /
in the url instead of adding SITE_PATH
. This will make the URL relative to the domain i.e. relative to www.your-domain.com/
. If the services
is within some sub folder you can do it like /sub_folder_name/services/your_path_continue
var type = 'default';
$.ajax({
url: 'services/service.php',
type: "POST", dataType: "json",
data: { 'm': 'share', 'a': 'uploadwebpic', 'photo_type': type, 'typename': "John", 'location': "Boston" },
//contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
alert(result);
}
});
Just a suggestion, try using the $.ajaxSetup() to get the correct error like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.
Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.
' + jqXHR.responseText);
}
}
});
});
This would help you to properly handle the Ajax error and get the exact error that occurred while making the ajax call.