Why .ajax always goes to success handler? - javascript

I used jQuery's .ajax function like:
$.ajax({
type:"POST",
url:"./index.php",
data:{ajax_fetch:1,action:"fetch_devInfo",nwType:nw_type,devTSN:dev_tsn,devSTime:dev_sTime,devETime:dev_eTime,dev_gType:dev_graphType},
dataType:"xml",
error:errHandler,
success:function(xml,textStatus)
{
xml_process(xml,textStatus,$("div#cont-Dev"),"Device");
}
});
// function for .ajax error callback
function errHandler(xhr, statusText, error)
{
if (xhr.status == "0" && statusText == "error")
{
$("body").append('<div class="ui-state-error ui-corner-all" id="error">Network down, try again later</div>');
}
else if (xhr.status == "200" && statusText == "parseerror")
{
window.location="./login.php";
}
}
My assumption is: if .ajax success, then the server must return it a XML file (identified by its header header("Content-type: text/xml")), that's why I specify the dataType as "xml"; however, if it failed (for example: session time out), index.php will redirect user to the login.php. In that case, the response is some HTML, shouldn't .ajax go to the function errHandler? Why does it always go to the success handler?

jQuery's $.ajax function takes the datatype and attempts to use the response as if it's that datatype, mostly to make things easier for you when you start using the response data. However, that's not how jQuery defines success or failure with the success or error handlers.
In this case, 'success' is defined by receiving information from the server. If information is received by the server, the request succeeded. Afterwards, jQuery tries to parse the information as XML (in your case). However, it isn't (or isn't what you expect), so it won't correctly do what you want it to.
Using that, I would rewrite the success handler to deal with XML or HTML data from the server, and use the error handler for your first error, where the server is down, etc.

I couldn't see a definitive answer in the jquery docs. But I'm thinking the data for the 302 response (or whatever) IS valid XML data (thus could be parsed) even if HTML isn't always.
HTTP/1.1 302 Found
Cache-Control: no-cache
Keep-Alive: timeout=3, max=993
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: /Login.aspx
Server: Microsoft-IIS/7.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Fri, 11 Dec 2009 19:17:27 GMT
Content-Length: 139
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>

Related

Yammer REST Api making different calls from different pages

I have a simple piece of code that finds the groups available to a user on Yammer using the Yammer JavaScript api and it looks a little like this:
yam.platform.request({
url: "groups.json?mine=1",
method: "GET",
success: function (data) {
callback(data);
},
error: function (error) {
console.log(error);
},
});
The call is carefully wrapped so it only ever happens once per page request, but it appears to succeed or fail on a totally arbitrary basis. The response either looks like this:
Response Headers
Cache-Control:no-cache
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Date:Wed, 26 Nov 2014 17:32:42 GMT
P3P:CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Server:nginx
Status:429
Transfer-Encoding:chunked
X-Date:1417023162896
X-Runtime:0.032459
X-UA-Compatible:IE=Edge,chrome=1
or like this:
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:https://my-access-origin.sharepoint.com
Access-Control-Expose-Headers:content-type, network_id, authorization, x-csrf-token, www-authenticate, x-xss-protection, ETag
Cache-Control:max-age=0, private, must-revalidate
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Date:Thu, 27 Nov 2014 12:17:38 GMT
ETag:"123a45b67cd89ef01234ab45cd67ef"
P3P:CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
Server:nginx
Status:200 OK
Strict-Transport-Security:max-age=31536000; includeSubDomains
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Date:1417090658344
X-Robots-Tag:none
X-Runtime:0.066098
X-UA-Compatible:IE=Edge,chrome=1
X-XSS-Protection:1; mode=block
In the former case, I see an error message in the Network panel of my development tools that looks like this:
XMLHttpRequest cannot load
https://api.yammer.com/api/v1/groups.json?mine=1&&_=123456. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://my-access-origin.sharepoint.com' is
therefore not allowed access. The response had HTTP status code 429.
This doesn't make sense for a couple of reasons - first that the request is exactly the same in both cases and secondly that I am getting "429 Too Many Requests" as the status code, but with an explicit report that the Access-Control-Allow_origin header should be set. Which it never is in my requests, but it does appear to be on the successful responses.
Can anyone explain what is going on?
First make sure that you web url in Yammer registered app's "Javascript Origins"
if still the same issue then it could be:
This is related to Yammer rest API limit, more over to this 429 error
https://developer.yammer.com/restapi/
Please refer my answer on this post
XMLHttpRequest: Network Error 0x80070005, Access is denied

$.getJSON fails on a successful http request

I'm calling the method in my page:
var dfd = $.Deferred(
$.getJSON(serviceAddress)
.done(function (result, status) {
bo.BusinessObject.DtosToaKoArray(result, resultList);
dfd.resolve(resultList);
})
.fail(function (result, status) {
logger.logError(result);
dfd.reject(result);
}));
return dfd;
After calling the JSON, the firebug shows that HttpRequest was successfull and the response header is like:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcV29ya3NwYWNlc1xNZWhyYW5cSW5mcmFzdHJ1Y3R1cmVcTWFpblxTb3VyY2VcSW5mcmFzdHJ1Y3R1cmVcU291cmNlXENhcmFuZS5HYWxheHkuV2ViQXBpXGFwaVxEYXRhUHJvdmlkZXJcTGlzdFNlcnZpY2Vc?=
X-Powered-By: ASP.NET
Date: Sun, 04 Aug 2013 05:57:39 GMT
Content-Length: 6684
but the problem is that instead of done callback, the fail callback is called with this result:
Object { readyState=4, status=404, statusText="error"}
What is wrong about my call that fails the successful http request?
Edit1.
My website (MyApp.Web) is on localhost:2771 and the calling service is in another project (MyApp.WebApi) on the localhost:4143
You will definitely run into some hurdles trying to make cross-origin requests. That includes port-to-port.
The solutions also depend on the service and what features it supports.
JSONP (or, JSON with Padding)
The service would need to accept a callback and output the JSON wrapped in a function call:
// http://...?callback=completeRequest
completeRequest(["json", "data"]);
The parameter can be a different name than callback. But, you can instruct jQuery to use it by including a placeholder parameter (...=?):
$.getJSON(serviceAddress + "?callback=?")
This can also be used in any browser as it's requested as a <script src> and the JSON will be parsed as JavaScript literals.
CORS
The service will need to support preflight, OPTIONS requests and respond with Access-Control-Allow-* headers.
Also, while most current browsers support CORS, this can be limited if you need to support older editions.
Otherwise, you'll need to create a proxy destination in your application (localhost:2771) that makes the cross-origin request server-side to the service (localhost:4143).
It might not be finding your target page and that's why you might be getting a 404 in your result object. Make sure that your serviceAddress is correct.
In addition to that When you specify: dataType: 'json' jQuery will fire the error event if the response cannot be parsed as JSON(despite the 200 reply). Make sure that the data returned from the server is valid JSON, you might want to validate the structure manually via JSONLint.
It might be any of these 2 problems.

JSON Returned From Rails Server via AJAX fails to run

I have a simple ajax post to the server..
$(".invite-team-members-submit-btn").click(function() {
$.post("invite_team_member", {
token: $("#token").val(),
email: $("#email").val(),
team: $("#team").val()
},"json")
.done(function (responseText) {
alert(responseText.response);
})
.fail(function (xhr,status,message) { alert("ERROR: " + message); })
.then(function () { alert("Something should happen."); });
});
The JSON returned looks like this...
{"response":"Person has been invited."}
My response header in the console looks like this...
Response Headers
Cache-Control max-age=0, private, must-revalidate
Connection close
Content-Type application/json; charset=utf-8
Date Wed, 22 May 2013 21:45:07 GMT
Etag "e5b5e12acbcc78372b2a861027b66c05"
Status 200 OK
Transfer-Encoding chunked
X-Request-Id d835ce021eff7733d67ebfcdd468bdf2
X-Runtime 0.007909
x-ua-compatible IE=Edge
My console is not only telling me that I received a 200 status but that my response includes the JSON I want. However when it comes to handling the parsed JSON no alerts are made. Note that I'm receiving NO alerts, not even from the then function. What could be causing this?
This is most likely due to jQuery automatically parsing the json for you before the success callback. To cause this to always happen so that you can consistently expect it, use this:
$(".invite-team-members-submit-btn").click(function() {
$.post("invite_team_member", {
token: $("#token").val(),
email: $("#email").val(),
team: $("#team").val()
},"json")
.done(function (responseText) {
alert(responseText.response);
})
.fail(function (xhr,status,message) { alert("ERROR: " + message); })
.then(function () { alert("Something should happen."); });
});
note the "json" parameter at the end of line 2
Update There was a ; at the end of $.post() making .done, .fail, and .then invalid. fixed in the above code.
If you still aren't seeing either a done alert or a fail alert, then there's an error in your console or the click event isn't happening in the first place. If using Firefox, make sure you're using firebug too. If testing in IE, try another browser.

How to get final destination URL from AJAX?

When I do an XMLHttpRequest, I always get redirected automatically to the URL (presumably by the headers of the response). For example, if I query "http://www.stackoverflow.com" I will be redirected to "http://stackoverflow.com".
How can I get that final URL? (http://stackoverflow.com/ in the example)
I checked in the response headers but I cannot seem to find it. (I just used the GET/POST method not HEAD).
Look for a location header in the response.
In the example you gave, accessing www.stackoverflow.com and being redirected to stackoverflow.com here is most definatly a Location header being used.
[trcjr#rigel ~]$ curl -I http://www.stackoverflow.com
HTTP/1.1 301 Moved Permanently
Content-Length: 148
Content-Type: text/html; charset=UTF-8
Location: http://stackoverflow.com/
Date: Sat, 05 Feb 2011 21:47:17 GMT
[trcjr#rigel ~]$
Using jQuery (this is for current page url) :
$(document).ready(function () {
var href = window.location.href.toString();
});
EDIT : For, response page final url, pass jqXHR to ajaxComplete & then read the header.

Allow RESTful DELETE method in asp.net mvc?

im currently setting up asp.net to accept DELETE http verb in the application.
However, when i send
"DELETE /posts/delete/1"
i always get a 405 Method not allow error. I tried to take a look at the header:
Response Headers
Cache-Control private
Pragma No-Cache
Allow GET, HEAD, OPTIONS, TRACE
Content-Type text/html; charset=utf-8
Server Microsoft-IIS/7.5, Private-Server
Date Tue, 17 Nov 2009 18:30:31 GMT
Content-Length 5590
Allow GET, HEAD, OPTIONS, TRACE
notice the Allow header in IIS7, it's only allow GET HEAD OPTIONS and TRACE. I currently using [AcceptVerbs(HttpVerbs.Delete)] in my delete controller (i think this one is extended by MVCContrib, correct me if im wrong)
PS: i send DELETE using Javascript:
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
and:
_ajax_request($(this).attr('href'), "", function(d) { alert("submit"); }, "json", 'DELETE');
THank you in advance!
MVC 2 has this built in. You don't need MVCContrib for it. See HtmlHelper.HttpMethodOverride and HttpDelete.

Categories

Resources