HighCharts query parameters issue with Flask webservice - javascript

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
});
}

Related

Serverless CORS Error: Did not find method in CORS header ‘Access-Control-Allow-Methods'

I tried using Serverless framework and have followed the guide to enable CORS.
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
temperature: 30,
locationId: event.queryStringParameters || event.queryStringParameters.id
})
};
And I also added in the serverless.yml.
functions:
getListComment:
handler: handler.getListComment
events:
- http:
path: comments/list
method: get
cors: true
The final endpoint is here
https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list
Somewhat when I tried calling the endpoint via AJAX.
$.ajax({
url: 'https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list',
type: 'json',
crossDomain: true,
contentType: "application/json",
success: function(data) {
alert('test');
}
});
There is nothing happens.
The Firefox console shows this message
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list.
(Reason: Did not find method in CORS header
‘Access-Control-Allow-Methods’).
And the Chrome console also shows this
XMLHttpRequest cannot load
https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list.
Method JSON is not allowed by Access-Control-Allow-Methods in
preflight response.
But when I tried the endpoint in http://www.test-cors.org, it looks okay, though.
Sending GET request to https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list
Fired XHR event: loadstart
Fired XHR event: readystatechange
Fired XHR event: readystatechange
Fired XHR event: progress
Fired XHR event: readystatechange
Fired XHR event: load
XHR status: 200
XHR status text: OK
XHR exposed response headers:
Content-Type: application/json
Here's the response header for OPTIONS
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 0
Connection: keep-alive
Date: Sat, 17 Dec 2016 02:16:30 GMT
Access-Control-Allow-Headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
Access-Control-Allow-Methods: OPTIONS,GET
Access-Control-Allow-Origin: *
x-amzn-RequestId: d2ab4dce-c3fe-11e6-bcee-6767a7211424
X-Cache: Miss from cloudfront
Via: 1.1 c038088d4b94486d7346fd44d03188a0.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 30nHstKUhLwnHDwYEF3VdugR3JsuXHvUScBRDRFHRhimPW_DHS7RPQ==
Here's for the GET
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 158
Connection: keep-alive
Date: Sat, 17 Dec 2016 02:17:17 GMT
Access-Control-Allow-Methods: OPTIONS,GET
Access-Control-Allow-Origin: *
x-amzn-RequestId: ee6c19a6-c3fe-11e6-a0dc-01a17c495e09
X-Amzn-Trace-Id: Root=1-5854a02d-ba86e18abb4d47eb5094343b
X-Cache: Miss from cloudfront
Via: 1.1 18101d17be4ee51b5a03b68cfed50445.cloudfront.net (CloudFront)
X-Amz-Cf-Id: 8K8NhwXGzhqR4bYLSFrRglogJQmQq3D3GJ2P4FrYoO-naDs-I55haA==
What did I do wrong?
You're making the request using a request method of 'json' (via the type property); 'json' is not a valid request method. Instead of type: 'json' you probably want dataType: 'json'.
The type property can be used to specify the request method (eg 'GET'), though it was deprecated in favour of the method property as of jquery v1.9.
$.ajax({
url: 'https://dgyoawr9n0.execute-api.us-east-1.amazonaws.com/dev/comments/list',
method: 'GET', // not necessary since it will default to 'GET'
dataType: 'json', // use dataType, not type, to specify expected response data type
crossDomain: true,
contentType: "application/json",
success: function(data) {
alert('test');
}});

JSON.stringify odd behavior

I'm wrapping up some values to send back to an ASP.NET MVC controller action. I'm getting Invalid JSON primitive exceptions, but I'm using JSON.stringify and am confused.
I build up a search value holding called searchValues. Putting console.log(JSON.stringify({ "values": searchValues })); in my code and opening Chrome's console outputs the following
{"values":["name_last:foo"]}
I use the exact some bit of code sans the console.log usage to populate the data parameter to the ajax call. However, watching the call in Fiddler, the request being sent looks like such
0=%7B&1=%22&2=v&3=a&4=l&5=u&6=e&7=s&8=%22&9=%3A&10=%5B&11=%22&12=n&13=a&14=m&15=e&16=_&17=l&18=a&19=s&20=t&21=%3A&22=f&23=o&24=o&25=%22&26=%5D&27=%7D
I'm using this in a Kendo grid but am specifying it to be sent as post as such:
$("#search-preview").kendoGrid({
columns: ...column stuff...,
dataSource: {
transport: {
read: {
url: "/SearchPreview",
dataType: "json",
data: JSON.stringify({"values": searchValues}),
type: "POST",
contentType: "application/json; charset=utf-8"
}
}
}
});
And I can see in Fiddler it being sent in the request body and not being appended to the URL such as if it were a GET. What's going on here?
Edit:
Adding what the entire Fiddler request looks like:
POST http://localhost/MvcTestBed/SearchPreview HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 149
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost/MvcTestBed
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: .... asp.net cookie fluff ....
0=%7B&1=%22&2=v&3=a&4=l&5=u&6=e&7=s&8=%22&9=%3A&10=%5B&11=%22&12=n&13=a&14=m&15=e&16=_&17=l&18=a&19=s&20=t&21=%3A&22=f&23=o&24=o&25=%22&26=%5D&27=%7D
Edit 2:
I've experimented with the processData and traditional settings on the jQuery ajax constructor, and the best I've gotten is for the post body to now look like
[object Object]
Based on the results you're getting in fiddler, it looks like something is calling $.param on your json string. jQuery does not do that, so it must be kendo grid.
One solution would be to make the ajax request directly, then in the success initialize the grid with the result.
After some research my solutions is use read as a function:
$("#search-preview").kendoGrid({
columns: ...column stuff...,
dataSource: {
transport: {
read: function (options) {
url: "/SearchPreview",
dataType: "json",
data: JSON.stringify({"values": searchValues}),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
}
}
}
});

JQuery $.ajax - done() not being called

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!

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