JQuery $.ajax - done() not being called - javascript

I have an ASP.NET/MVC site calling into WebApi webservices, using JQuery's $.ajax(). Most of these have been working fine, but I have one for which none of the callback functions - done(), fail(), always() - are being called.
The service is being called, and according to Fiddler, a response is being returned. But JQuery isn't calling any of the callback functions.
Other are working fine. Or seem to be.
The calling code is the same, in every case:
core.callService = function (serviceUrl, httpType, token, data, failMessage, callback)
{
try
{
var parameters = {
type: httpType,
dataType: "json",
timeout: ajaxRequestTimeoutMS,
headers: { "authenticationToken": "" + token }
};
if (httpType === "POST" || httpType === "PUT" || httpType === "DELETE")
{
parameters.contentType = "application/json; charset=utf-8";
parameters.data = JSON.stringify(data);
}
else
{
parameters.data = data;
}
debugger;
$.ajax(serviceUrl, parameters).done(
function (result, textStatus, jqXHR)
{
debugger;
// ...
}).fail(function (jqXHR, textStatus, errorThrown)
{
debugger;
// ...
}).always(function ()
{
debugger;
//whether success or failure
});
}
catch (e)
{
debugger;
callback({
success: false,
message: e.message,
data: null
});
}
finally
{
debugger;
}
};
Running Fiddler, I can see the request:
GET http://localhost:52057/api/MyController/myAction?myParameters HTTP/1.1
authenticationToken: eb76272e-b26e-4773-9d22-2218bea8beb1
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:61986/Feedback?items%5B0%5D.updatetype=
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: localhost:52057
DNT: 1
Connection: Keep-Alive
Cookie: ...
And the response:
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?RTpcZGV2XFplYnVcWmVidV93ZWJcdHJ1bmtcWmVidV93c1xhcGlcRW1haWxUb29sXHNlbmRFbWFpbA==?=
X-Powered-By: ASP.NET
Date: Mon, 30 Mar 2015 16:43:32 GMT
Content-Length: 21
{"message":"Success"}
So the response is getting back to the client, but JQuery is not calling the done() function, or the fail() function, or the always() function. And I can't see why. I've looked at the responses from other webservices, that are working, and I can't see anything different about them.
Any ideas?
=============Followup=============
More information, and more confusion.
If I call the webservice during the page init function, the callback is executed. If I call it from within the click event of a button, it does not.
Looking at the requests and responses, the only difference I see is in the referer field of the request. When I'm calling from the event function, I'm seeing "?items[0].updatetype=" appended to the URL. And I can't see find who's doing that.

OK, this one is just stupid. After hours of digging through the JavaScript and monitoring the network traffic trying to figure out why the callback functions weren't executing...
The click event that called my webservice was being generated by a submit button.
Argh!

Related

Axios vue.js CORS Error with proxy undefined response

I am trying to GET data with my client vueJS on port 8080 from the REST API on port 3000. This is resulting in a CORSE Error. A POST is working fine. To fix this I tried to create a proxy as described here https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3.
//vue.config.js
module.exports={
devServer:{
proxy: {
'/teams': {
target: 'http://192.168.70.54:3000',
ws: true,
changeOrigin: true,
secure: false
}}}}
I want to redirect my traffic to the 3000 port.
//rest.js
function getTeams() {
var returnVal;
axios({
method: 'get',
url: REST_API + '/teams',
responseType: 'json'
})
.then(function (response) {
console.log(response.data); //Is what I want to return
returnVal = response.data;
});
console.log(returnVal); //Is undefined
return returnVal.data;
}
I am printing response.data to the console but my returnVal is always undefined. What am I missing?
This is my network log in the browser.
General:
Request URL: http://localhost:8080/teams
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:8080
Response Headers:
Referrer Policy: no-referrer-when-downgrade
access-control-allow-header: Origin, X-Request-With, Content-Type, Accept
access-control-allow-methods: GET, POST
access-control-allow-origin: *
connection: close
content-length: 1070
content-type: application/json
Date: Tue, 17 Dec 2019 18:57:14 GMT
Request Headers:
X-Powered-By: Express
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Host: localhost:8080
Referer: http://localhost:8080/setup
User-Agent: Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Raspbian Chromium/74.0.3729.157 Chrome/74.0.3729.157 Safari/537.36
There's a lot going on in this question.
Firstly, let's focus on this bit:
function getTeams() {
var returnVal;
axios({
method: 'get',
url: REST_API + '/teams',
responseType: 'json'
})
.then(function (response) {
console.log(response.data); //Is what I want to return
returnVal = response.data;
});
console.log(returnVal); //Is undefined
return returnVal.data;
}
The first log line is logging the correct value but the second log line is undefined.
This is to be expected. It has nothing to do with CORS or proxying.
The problem is that the axios request is asynchronous, so the then callback won't be called until some point in the future. By that point the function will have returned. You should find that the log lines are being logged in the 'wrong' order for the same reason.
You can't return an asynchronously retrieved value synchronously from a function. Using async/await may make it look like you can but even that is a fudge, hiding the underlying promises.
You have two options:
Return a promise from getTeams. That kicks the problem of waiting up to the calling code.
If you are inside a component you can set a data property inside the then callback. This is instead of returning a value.
Then we have the other parts of your question.
It would seem that you have successfully managed to configure a proxy. Difficult to be sure but from everything you've included in the question that seems to be working correctly. You wouldn't be getting the correct data in your console logging if the proxy wasn't working.
However, there are a lot of CORS headers in your response. If you're using a proxy then you don't need the CORS headers. A proxy is an alternative to CORS, you don't use both.
As for why your CORS request was failing prior to using a proxy, it's difficult to say from the information provided in the question.

AJAX POST - Working in IE, Chrome, Not Firefox

I have a Javascript function that posts to a PHP page to assign session vars.
Here is the code for the update function:
function updateSession() {
$.ajax({
type: "POST",
url: "update-session.php",
data: $('#welcome').serialize() + '&ajax=true'
});
}
When I run this function, I get an error on line '8630' for jQuery which is a line containing the following:
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
The POST is not going across a different domain and I have already tried using the full URL in the AJAX POST.
My request headers are below:
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Content-Length
124
Content-Type
application/x-www-form-urlencoded; charset=UTF-8
User-Agent
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
X-Requested-With
XMLHttpRequest
I've also tried using different versions of jQuery.
Any help would be appreciated!

HighCharts query parameters issue with Flask webservice

I have a HighCharts client whose responsibility is to load data from a webservice and show a chart. The function that requests data looks as below:
function requestData() {
$.ajax({
url: 'http://myhost.com/type?x=1&y=2&z=3',
headers: {
Accept : "application/json"
},
type: "GET",
dataType: "json",
success: function(data) {
//do something
},
cache: true
});
}
(in the future, the url property will be dynamically generated)
The target webservice is read-only and implemented using Flask microframework: its purpose is to return JSON data to the HighCharts client. This is the Flask view (function) taking care of data requests:
#app.route('/<type>')
def get_data(type):
x = request.args.get('x','')
y = request.args.get('y','')
z = request.args.get('z','')
[...]
Problem: when I execute the javascript code in Chrome, the following HTTP request is sent to the webservice:
GET /type?x=1&y=2&z=3 HTTP/1.1 // '&' have been escaped to '&'
Host: myhost.com
Connection: keep-alive
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Accept: application/json
Referer: http://myhost.com/chart.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
...I get a 404 status code (Bad Request) from the server, which is perfectly good and expected whenever one or more of the request's query parameters is null or malformed:
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html; charset=utf-8
Content-Length: 16
Server: Werkzeug/0.8.3 Python/2.7.3
Date: Wed, 14 Nov 2012 10:23:49 GMT
After debugging on my Flask webservice I noticed that only the x query parameter (which please note is the first given in the HTTP request) is correctly parsed, while y and z are empy strings, which causes the 404.
Why is it happening? Any charset inconsistency regarding the & -> & escaping?
Thanks, any hint would be of real help (just ask if you need more specs or code)
I think the error is as you expected the escaped ampersand.
Try this:
function requestData() {
$.ajax({
url: 'http://myhost.com/type',
headers: {
Accept : "application/json"
},
data: {
x: 1,
y: 2,
z: 3
},
type: "GET",
dataType: "json",
success: function(data) {
//do something
},
cache: true
});
}

JSON get result null

I'm developing an app using HTML5 with jQuery, and I am using Sync Framework for the synchronization and it consumes a service in the cloud (Windows Azure).
The problem is when I send the Request frame to the service:
$.ajax({
dataType: "json",
Accept: 'application / json',
url: serviceUri,
crossDomain: true,
success: function (json) {
console.log(" reponse :" + json);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("error :" + XMLHttpRequest.responseText);
}
});
The Request frame is:
GET http://157.56.8.203/DefaultScopeSyncService.svc/defaultscope /DownloadChanges?id=7AE7C771-0A98-4A5D-A046-430DDB0A7917 HTTP/1.1
Host: 157.56.8.203
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept: application/json, text/javascript, /
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: htp://localhost:49427/ListSample.htm
Origin: htp://localhost:49427
And the Reply is:
HTTP/1.1 200 OK
Content-Length: 1388
Content-Type: application/json
Server: Microsoft-IIS/7.0
SyncServiceVersion: 1.0
X-Powered-By: ASP.NET
Date: Wed, 30 Nov 2011 11:55:25 GMT
{"d":{"_sync":{"moreChangesAvailable":false,"serverBlob":"AAEAAAD/////AQAAAAAAAAAMAgAAAGVNaWNyb3NvZnQuU3luY2hyb25pemF0aW9uLlNlcnZpY2VzLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49ODk4NDVkY2Q4MDgwY2M5MQUBAAAAK01pY3Jvc29mdC5TeW5jaHJvbml6YXRpb24uU2VydmljZXMuU3luY0Jsb2IFAAAAIDxDbGllbnRLbm93bGVkZ2U+a19fQmFja2luZ0ZpZWxkIDxDbGllbnRTY29wZU5hbWU+a19fQmFja2luZ0ZpZWxkHDxJc0xhc3RCYXRjaD5rX19CYWNraW5nRmllbGQaPEJhdGNoQ29kZT5rX19CYWNraW5nRmllbGQaPE5leHRCYXRjaD5rX19CYWNraW5nRmllbGQHAQADAwIBbVN5c3RlbS5OdWxsYWJsZWAxW1tTeXN0ZW0uR3VpZCwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV1tU3lzdGVtLk51bGxhYmxlYDFbW1N5c3RlbS5HdWlkLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAJAwAAAAYEAAAAJDhhMzZhNGYyLTg5ZjQtNDJkMi1iNDhmLTJiNWM4ZDc5ZGE4OQEKCg8DAAAAkAAAAAIAAAAFAAAAAAAAAAEAAAAAAAAABQAAEAAAAAKKNqTyifRC0rSPK1yNedqJ6MOD+NOvRl6RwtFgNGnbbgAAABgAABABKAIAAAEAAAAVAAAAAgAAAAEAAAAAAAAAAQAAAAEAAAABAAAAAAAAAQ8AAAAXAAAAAQAAABYAAAABAAMAAAAAAQAAAAAAAAAZAQAAAAAL"},"results":[{"Id":"7ae7c771-0a98-4a5d-a046-430ddb0a7917","Name":"Santiago","Surname":"Dalto","BirthDate":"/Date(917913600000)/","Gender":"M","_metadata":{"uri":"http://157.56.8.203/DefaultScopeSyncService.svc/Persons(Id=guid'7ae7c771-0a98-4a5d-a046-430ddb0a7917')","type":"DefaultScope.Persons"}}]}}
The "data" object in the script is always null, but the reply frame has the correct data.
Can somebody help me?
You must write the call function with this code, the reponse data you can get with json.d.results if the response has more than one object if you will get single object than you reach them with json.d[0].
$.ajax({
dataType: "json",
Accept: 'application / json',
url: serviceUri,
crossDomain: true,
success: function (json) {
if (json.d.results == undefined)
{
// to do
}
else {
console.log(" response :" + json.d.results);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("error :" + XMLHttpRequest.responseText);
}
});
Best Regards.
Cross domain requests doesn't allowing in ALL modern browsers and it is not good to use them. In any case if you would like to receive your data you need to user your server like proxy, so it will work like this:
You implement request from server (YOUR SERVER) to another server
You call request to YOUR server, not to another (cross domain server)
Other ways is hucking.
I.e. you can use this link (BUT I don't suggest it) http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

Ajax call to web service - success in method but forbids data access

I am trying to call a web service from an ajax jquery. It is successfully entering the success method but unfortunately a 403 error is being triggered and thus won't allow me to access the data.
This is my code:
try {
$.ajax({
type: "POST",
url: urlAddress,
data: dataa,
contentType: "text/xml; charset=utf-8",
success: function(Msg) {
// $("#Result").text(msg.d);
alert("ok");
alert("hi "+Msg.responseText + " How are you?");
},
error: function(request, status, error) {
alert("Error "+request.statusText.toString());
alert("ERROR");
}
});
}
catch (e)
{}
Msg.ResponseText comes back "undefined"
From Live Http Headers I get the following:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115 Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
HTTP/1.1 403 Forbidden
Content-Length:1758
Content-Type: text/html
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Date: Tue, 27 Jul 2010 10:59:04 GMT
Smells like urlAddress is not located on the same domain you're running that script.
That would breach the same origin policy and therefore, fail.
If I'm wrong here with that assumption, your're webservice might require a login (username+password) which you might missing to pass through .ajax().

Categories

Resources