I am doing an Ajax post to a specific page where I either can get an ID as response if everything went as expected or I could get a random html page and a http 400 as response if something went wrong. In the error case I want to open up the entire html page in a new window. I have tried the following but it is not working - it sets the variable data to [object Object] instead of the intended html page.
$.ajax({
type: "POST",
url: postUrl,
data:'message=' + message + '&' + 'title=' + title,
statusCode: {
400:function(data) {
var newWin = open('','windowName','height=300,width=300');
newWin.document.write(data);
},
},
success: function(json) {
alert("Post success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error connecting to page.");
}
});
Specify dataType : 'html' and change the success function variable. Example:
$.ajax({
type: "POST",
dataType: 'html',
url: postUrl,
data:'message=' + message + '&' + 'title=' + title,
statusCode: {
400:function(data) {
var newWin = open('','windowName','height=300,width=300');
newWin.document.write(data);
},
},
success: function(html) {
alert("Post success");
$("#myDiv").html(html);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error connecting to page.");
}
});
Related
This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!
I'm using ajax to get the returned value from php function, the call is correct but I can't access the data properly.
The ajax call is:
$.ajax({
data: {"hotel_id" : hotel_id},
url: '/get_type_check',
type: 'get',
success: function (response) {
console.log(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If I print the console log shows:
<!DOCTYPE html>
comment:
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
{"status":["CAB2"]}
And the php function:
public function get_type_check(){
$type_checks=Hotel::get_type_checks($_GET['hotel_id']);
echo json_encode(array('status' => $type_checks));
}
How can I get the response.status?
Should I use return instead of "echo"?
You have to parse the response to json to catch it as json.
Just add the line:
var data = $.parseJSON(response);
So your ajax will as follows:
$.ajax({
data: {"hotel_id": hotel_id},
url: 'ajax.php',
type: 'get',
success: function(response) {
var data = $.parseJSON(response);
console.log(data.status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
});
So I have an ajax script that runs, it looks like this:
jQuery.ajax({
url: 'http://localhost/?page_id=104256',
type: 'POST',
data: { name : 'name2' },
success: function (data) {
alert(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details0: " + desc + "\nError:" + err);
},
});
This runs fine but returns a 404 from the page set as the 'url'
If I remove 'type: post'
Here your method: 'Post', Type is something what you want to get in return like text
jQuery.ajax({
url: 'http://localhost/?page_id=104256',
method: 'POST',
data: { name : 'name2' },
success: function (data) {
alert(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details0: " + desc + "\nError:" + err);
},
});
If type: 'POST' is omitted, jQuery is treating it like a GET request, which it defaults to see the docs, where the resource may not exist therefore resulting in a the 404 you're seeing.
It turns out I forgot to add the name="" parameter in my input types. Doh!
I'm trying to get JSON data from another domain.
It returns status 200 but invokes an error in the callback function.
Is it possible to get the raw data or html or even just text when I get into the error callback?
Why is xhr.responseText undefined?
Here is part of my code:
$.ajax({
type: 'POST',
url: 'http://timetable.nctu.edu.tw/?r=main/get_cos_list',
dataType: 'jsonp',
crossDomain: true,
async: false,
data:{m_acy:'**',m_sem:'**',m_degree:'**',m_dep_id:'**',m_group:'**',
m_grade:'**',m_class:'**',m_option:'cos_code',m_crsname:'**',m_teaname:'**',
m_cos_id:'**',m_cos_code:'DAM1346',m_crstime:'**'},
jsonp: true,
success: function(json) {
$('#jjjj').html(json);
},
error: function(xhr, textStatus, errorThrown) {
$('#content').append("readyState: "+xhr.readyState+"<br>status: "+xhr.status+"<br>responseText: "+xhr.responseText+"<br><hr>");
alert('Ajax request error.' + xhr.responseText + xhr.responseData + errorThrown);
},
complete: function(xhr, textStatus)
{
alert(xhr.responseText + xhr.responseHtml);
alert(h.responseHtml);
}
});
I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}