Only in Opera: JSON.parse: Unterminated string - ajax

In Opera only I receive "JSON.parse: Unterminated string" when going to http://www.underfashion.nl/babys
The string is indeed unterminated, does not end with "]}.
In the other browsers (IE, FF, Chrome) it works fine and receives the entire string.
The string is very long: 217529 chars. Is that possibly the problem? The other browsers receive 220374 chars ending with "]}
I have tried 3 AJAXways to get the data, all with the same strings as result:
The first:
var value = (function () {
var val = null;
$.ajax({'async': false, 'global': false, 'url': uf_urlsearch,
'success': function (data) { val = data;
alert("Data Loaded: " + data.slice(-100) + "<br/>Numofchars: " + data.length);
}
});
return val;
})();
The second:
$.get(uf_urlsearch, function(data){
alert("Data Loaded: " + data.slice(-100));
});
The third:
uf_XMLHttpProductlist.onreadystatechange=function(){
if (uf_XMLHttpProductlist.readyState==4 && uf_XMLHttpProductlist.status==200){
//Get the returned menu-items in Responsetext, expected to look like this:
...
};//if (uf_XMLHttp.readyState==4 && uf_XMLHttp.status==200){
};//uf_XMLHttp.onreadystatechange=function()
uf_urlsearch = "http://www.underfashion.nl/php/get_productlist.php?"+uf_PHPsearchstring;
uf_XMLHttpProductlist.open("GET",uf_urlsearch,true);
uf_XMLHttpProductlist.send();
};
Anyone see any solution?
Best regards,

To inspect the network activity, Go to Opera Menu -> Tools -> Advanced -> Opera Dragonfly. Then enter the URL in your addressbar.
In the Network Tab you can see the list of resources. Select the XHR button, and you will see the get_productlist.php resource. For what is worth, I didn't have any issue with your Web site. The HTTP Request was:
GET /php/get_productlist.php?afdeling=babys HTTP/1.1
User-Agent: Opera/9.80 (Macintosh; Intel Mac OS X 10.7.4; U; fr) Presto/2.10.289 Version/12.00
Host: www.underfashion.nl
Accept-Language: fr,en;q=0.9,en-US;q=0.8,ja;q=0.7,pt;q=0.6,de;q=0.5,zh-CN;q=0.4,es;q=0.3,it;q=0.2,nl;q=0.1,sv;q=0.1,nb;q=0.1,da;q=0.1,fi;q=0.1,zh-TW;q=0.1,ko;q=0.1,pl;q=0.1,pt-PT;q=0.1,ru;q=0.1,ar;q=0.1,cs;q=0.1,hu;q=0.1,tr;q=0.1,ca;q=0.1,el;q=0.1,he;q=0.1,hr;q=0.1,ro;q=0.1,sk;q=0.1,th;q=0.1,uk;q=0.1
Accept-Encoding: gzip, deflate
Referer: http://www.underfashion.nl/babys
Cookie: JSESSIONID=9ABC3B0357487E01298EBC7A02B5FDCD; __atuvc=1%7C25; __utma=137714676.906129982.1340200451.1340200451.1340200451.1; __utmb=137714676.1.10.1340200451; __utmc=137714676; __utmz=137714676.1340200451.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=
Connection: Keep-Alive
X-Requested-With: XMLHttpRequest
Accept: */*
Now the HTTP Response is interesting:
HTTP/1.1 200 OK
Date: Wed, 20 Jun 2012 13:54:11 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.15
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 11469
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/html
Then the json content. Do you see what is wrong in the HTTP response above? YUP.
Content-Type: text/html
The mime type for JSON is defined in RFC 4627. Please send with JSON content the following mime type.
Content-Type: application/json
That said You are saying that you still have the issue (I don't) on some specific URIs. Could you share which one?

Related

Set-Cookie doesn't set the cookie

There is a well-known Google XSS game (https://xss-game.appspot.com/) that allows you to learn how to find and exploit XSS bugs. The advance to the next level occurs after the user injects a script to pop up a JavaScript alert().
Previously, the advance to the next level did not cause problems, but now something seems to be broken in this game because even after the alert is displayed on the screen, the following message appears when you try to move next:
Based on your browser cookies it seems like you haven't passed the previous level of the game. Please go back to the previous level and complete the challenge.
Let's try to figure out what's going on.
The source code (game.js, lines 11-24) of the site shows that the following code is responsible for moving to the next level:
function levelSolved() {
if (!userOpenedAlert) {
return;
}
var oReq = new XMLHttpRequest();
oReq.onload = function () {
if (oReq.readyState != 4) return;
document.getElementById('next-controls').style.display = "block";
eval(oReq.responseText);
};
oReq.open("GET", window.location.toString() + '/record', true);
oReq.send();
}
Request https://xss-game.appspot.com/level1/record looks like this:
General:
Request URL: https://xss-game.appspot.com/level1/record
Request Method: GET
Status Code: 200
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
alt-svc: h3=":443"; ma=2592000
cache-control: no-cache
content-length: 0
content-type: text/html; charset=utf-8
date: Wed, 31 Aug 2022 18:14:26 GMT
expires: Wed, 31 Aug 2022 18:14:26 GMT
server: Google Frontend
set-cookie: level1=f148716ef4ed1ba0f192cde4618f8dc5; Path=/; Expires=Wed, 22 Jul 2022 12:34:56 GMT; HttpOnly
x-cloud-trace-context: 31ad2e6a5cdd8b63c39bad66e783535b;o=1
Request Headers:
:authority: xss-game.appspot.com
:method: GET
:path: /level1/record
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: q=0.9,en-US;q=0.8,en;q=0.7
sec-ch-ua: "Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: none
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36
So, as you can see, there is the Set-Cookie response header that should set the cookie. If set this cookie manually by the browser, then everything starts working normally, and the advance to the next level happens without problems.
The question actually is why the Set-Cookie header does not work in this case? The request is not cross-origin, and you can even execute it not as an XMLHttpRequest, but as a regular GET request, but this does not work anyway.
Let's help Google to fix this game ;)
The server sends Expires=Wed, 22 Jul 2022 12:34:56 GMT within the cookie. So there are no reasons to set this already expired cookie

esp32, esp32_https_server library, self-signed certificate, cors and 499 status code

i am working on an ESP32 project. one of my goals is to communicate with the ESP32 from a website using javascript fetch or XMLHttpRequest().
the ESP32 is connected to my local network and i am using the esp32_https_server library. it uses a self-signed certificate which the browser indicates as valid (but issues a warning, "Connection not protected" due to the self-signed certificate). the website has a CA certificate and is secure.
in testing, the esp32 is conected via USB to my computer, idealy i would like it to stand alone.
the problem i am experiencing is that i cannot seem to connect to the esp32. i keep getting status code 499 errors.
my questions are:
1) how do i successfully connect to the esp32 server from a secure website to get data frome the esp32?
2) how do i do this when the esp32 is not connected to my pc via the usb cable?
please see more info regarding the esp32 set up and responses below.
here's the esp32 code:
ResourceNode *nodeRoot = new ResourceNode("/", "GET", [](HTTPRequest *req, HTTPResponse *res) {
ResourceParameters *params = req->getParams();
std::string action = params->getRequestParameter("action");
String aksie = action.c_str();
Serial.println("Aksie: " + aksie);
if (aksie != "upload_data" && aksie != "upload_current_temp")
{
// this should be home page displayed
// Set the response status
res->setStatusCode(200);
res->setStatusText("success");
res->println("Secure Hello World!!!");
}
else
{
// either uploads..
processParams(aksie, res);
}
});
secureServer->registerNode(nodeRoot);
and here's the code that processes the "upload_current_temp" request:
if (action == "upload_current_temp")
{
// get random temperature
int currentTemp = random(0, 9);
String temp = String(currentTemp);
Serial.println("upload current temperature");
Serial.println("uploadCurrentTemp: " + temp);
std::string tem = temp.c_str();
// Set the response status
res->setStatusCode(200);
res->setStatusText("success current temperature");
StaticJsonDocument<200> doc;
doc["temperature"] = temp;
// Produce a minified JSON document
String output;
serializeJson(doc, output);
Serial.println("curent temp json output: " + output);
deserializeJson(doc, output);
// Set the content type of the response
res->setHeader("Content-Type", "application/json");
res->setHeader("Access-Control-Allow-Origin", "*");
res->setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
// As HTTPResponse implements the Print interface, this works fine. Just remember
// to use *, as we only have a pointer to the HTTPResponse here:
serializeJson(doc, *res);
}
and also in setUp() i have this line:
secureServer->setDefaultHeader("Access-Control-Allow-Origin", "*"); //replace * with actual address
when using:
const xhr = new XMLHttpRequest();
const url = 'https://192.168.0.102/?action=upload_current_temp';
xhr.open('GET', url);
xhr.responseType = 'text';
xhr.onload = function () {
const data = xhr.response;
console.log(data);
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
console.log("getCurTemp(), responseText: " + JSON.stringify(this.responseText, null, 2));
currentTemperature = obj.temperature;
console.log("current temperature: " + currentTemperature);
document.getElementById('currentTemp').innerHTML = currentTemperature;
}
};
xhr.send();
i get these errors (in opera):
499 (Request has been forbidden by antivirus)
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
and in chrome:
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
with these headers (opera):
Request URL: https://192.168.0.102/?action=upload_current_temp
Request Method: GET
Status Code: 499 Request has been forbidden by antivirus
Remote Address: 192.168.0.102:443
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-store, no-cache, must-revalidate, max-age=0
Connection: close
Content-Length: 52266
Content-Type: text/html; charset=utf-8
Expires: Mon, 04 Dec 1999 21:29:02 GMT
Pragma: no-cache
Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Host: 192.168.0.102
Origin: https://istimuli.co.uk
Referer: https://istimuli.co.uk/?code=66b72f8e-400c-4adb-ad42-f4efec391d06
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 OPR/67.0.3575.79
action: upload_current_temp
and when using :
var url = "https://192.168.0.102/?action=upload_current_temp";
var request = new Request(url, {
method: 'GET',
mode: 'cors', // no-cors, *cors, same-origin
headers: {
'Content-Type': 'application/json'
}
});
fetch(request).then(function (response) {
// Convert to JSON
return response.json();
}).then(function (data) {
console.log("temp: " + JSON.stringify(data));
return data;
}).catch(function (error) {
console.log('Request failed', error)
return 000;
});
i get these errors in opera:
499 (Request has been forbidden by antivirus)
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and in chrome:
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and these are the headers (opera):
1 requests
51.3 KB transferred
51.0 KB resources
Request URL: https://192.168.0.102/?action=upload_current_temp
Request Method: OPTIONS
Status Code: 499 Request has been forbidden by antivirus
Remote Address: 192.168.0.102:443
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-store, no-cache, must-revalidate, max-age=0
Connection: close
Content-Length: 52266
Content-Type: text/html; charset=utf-8
Expires: Mon, 04 Dec 1999 21:29:02 GMT
Pragma: no-cache
Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: GET
Connection: keep-alive
Host: 192.168.0.102
Origin: https://istimuli.co.uk
Referer: https://istimuli.co.uk/?code=66b72f8e-400c-4adb-ad42-f4efec391d06
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 OPR/67.0.3575.79
action: upload_current_temp

Chrome extension unable to get data from a server after switch to https due to Origin Control

I've been battling with Chromium, jQuery and AJAX. My extension takes some resources from some sites using ajax, then parse the results and store it somewhere. One of those sites decided to do the jump to https. Neat. I just have to change the http for https, and fix any problem I hit down the road. No joy.
I use the following ajax method to get the stuff (is the smallest unit I could reproduce):
$.ajax({
url: "https://reader.japanzai.com/search/",
type: 'POST',
data: {
'search': "onna"
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
headers: {
'Access-Control-Allow-Origin': '*'
}})
Lets ignore for a while that I've set the headers twice, since just using one don't work either and throw the result:
OPTIONS https://reader.japanzai.com/search/ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://nhjloagockgobfpopemejpgjjechcpfd' is therefore not allowed access. jquery.js:5
x.support.cors.e.crossDomain.send jquery.js:5
x.extend.ajax jquery.js:5
(anonymous function) VM4000:2
InjectedScript._evaluateOn VM3770:581
InjectedScript._evaluateAndWrap VM3770:540
InjectedScript.evaluate VM3770:459
XMLHttpRequest cannot load https://reader.japanzai.com/search/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://nhjloagockgobfpopemejpgjjechcpfd' is therefore not allowed access. lab.html:1
As you can see, it says that the request header is not present, which is true following the http request:
Request URL:https://reader.japanzai.com/search/
Request Method:OPTIONS
Status Code:200 OK
Request Headersview parsed
OPTIONS https://reader.japanzai.com/search/ HTTP/1.1
origin: chrome-extension://nhjloagockgobfpopemejpgjjechcpfd
access-control-request-method: POST
dnt: 1
accept-encoding: gzip,deflate,sdch
host: reader.japanzai.com
accept-language: es,en-US;q=0.8,en;q=0.6
method: OPTIONS
user-agent: Mozilla/5.0 (X11; Linux i686 (x86_64)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
accept: */*
url: /search/
scheme: https
version: HTTP/1.1
access-control-request-headers: access-control-allow-origin, accept, content-type
Response:
HTTP/1.1 200 OK
cache-control: post-check=0, pre-check=0, max-age=0
content-encoding: gzip
content-type: text/html
date: Thu, 13 Feb 2014 22:58:03 GMT
expires: Sat, 01 Jan 2000 00:00:01 GMT
last-modified: Thu, 13 Feb 2014 22:58:03 GMT
pragma: no-cache
server: nginx/1.5.8
set-cookie: ci_session=U3Q14aq8Q7W4KVifDyLi7%2B3lppr%2FS4BNmW1kD9t60H7dz73M5KMs1jgBo8ZrilKoswn63PvCl1sOldPs1RCl6NdiP1VZeekoMTISyQenQZU0F8yUC0odw6WuMUE5I%2FY%2Bfvddv2YH06b2pxyyNBDZnNn%2BLnLzPrRYBXHuAjFbTyucX%2FMLUUM2cwKLzaK3ILKPhxy8FXW%2FI%2F9EPPbwo%2B8nmbPwOeqDfpDdu61F5yzUU8KjfUo7MwwFIXyGWtqbjbF3PCKNZrY%2F3Cj77DgCpcCbTTKZ%2BVzrdw16oGVDg1dP8lQgSof89rLNqUlQSj60tCVzZ27oPNh9OvvTNJ92tYkTHDukG4dyv21yM4M3PACZ%2FKVNP0i2UWHbBujADPSsrGJhJxPzBsuRDLcPtDcBtuaXA4LLMoGoYW6SxYk%2BseltMvk%3D; expires=Fri, 14-Feb-2014 00:58:03 GMT; path=/
set-cookie: ci_session=tQT8qmNRnMRN2Oj3moCdZg9VNEEsPxi3t88g2SpYQxahFr%2FpiEpQFzsO2mLTp1bPlsGLmqQGnMUiuwFpLYNIneNHtU%2BoKkVOcnR8ZKxPd0FDrkW%2BqT0N2IIsV%2BC%2FXQX%2BZUkLg1E4iP6u%2F0%2Fjk1t%2BAwcwhoC0M3zODuEKv1l9JMFo%2B1g4%2BhIOp%2FHTzBnlMvE2KjanXJR55F3DOHdyi4MvQb1vzgWEZTTAfhZ3bkQPkKe41ZCJYQTw%2FrDfry8n2h43UKPc1IF4tWp%2BKh0yhux%2FsBn84meT3xR%2Bpba9ffeZObrQyVomKlmJg9oRkKvlhR4MlNsiIeIZEvtP52ns0X1uF%2B7Pg6RpcMihe1u2S0%2Fbz5wm75vQ6tyykmFp5qfnoDgXB6J7RmbBQy4GTOFEA2zqN3V6QXT71cSn%2B1ARd9GtNMA%3D; expires=Fri, 14-Feb-2014 00:58:03 GMT; path=/
status: 200 OK
strict-transport-security: max-age=31536000
vary: Accept-Encoding
version: HTTP/1.1
x-powered-by: PHP/5.4.4-14+deb7u7
So, I'm missing something obvious here or there's just no way to do this?
I followed abraham advice and added the site to the permissions field in the manifest. It worked, the only bad thing is that if another site decides to move to https I need to release a new version, so this is what I ended doing:
"permissions" : [
"tabs",
"*://*/*",
"https://ssl10.ovh.net/*",
"unlimited_storage",
"clipboardWrite",
The important part here is "*://*/*" which includes anything from http and https.

WCF service returns incorrect Content-Length when using gzip encoding

I have a web page containing a filtering text box and a list box. Modifications to the text box trigger an AJAX request, which returns an array of values with which to populate the list box.
I had problems with these calls failing sometimes, dependent on the size of the data returned. Small-sized returned data would result in an error, large-size data was returned and processed succesfully.
This problem only happens when I use a jQuery version greater than 4.2. If I use jQuery version 4.2, I don't have the problem.
Here is the code of the call:
jQuery.ajax(
{
cache: false,
url: "../Services/CmsWebService.svc/GetAvailableVideosForCompany",
type: "GET",
complete: function (jqXHR, textStatus) {
var responseText = jqXHR.responseText;
jQuery('#debugConsole').text(responseText);
availableVideosPopulationState.isRunning = false;
setTimeout(populateAvailableVideosListBox, 100);
},
data: { "companyIdString": queryParameters.companyIdField,
"textFilter": queryParameters.filterText
},
dataType: 'json',
error: function (jqXHR, textStatus, errorThrown) {
var errorString = 'Error thrown from ajax call: ' + textStatus + 'Error: ' + errorThrown;
alert(errorString);
},
success: function (data, textStatus, jqXHR) {
populateVideoListFromAjaxResults(data);
}
}
);
Here is the contents of the debug console if two elements are returned:
{"d":[{"__type":"ListEntry:#WebsitePresentationLayer","Text":"SOJACKACT0310DSN1.mpg - [SOJACKACT0310DSN1]","Value":"5565_5565"},{"__type":"ListEntry:#WebsitePresentationLayer","Text":"SOJACKACT0310DSN1Q.mpg - [SOJACKACT0310DSN1Q]","Value":"5566_5566"}]}
But if one element is returned:
{"d":[{"__type":"
So, of course, we get an "Unterminated String Constant" error.
I have done some investigation using fiddler.
On all responses (even the succesful ones), fiddler displayed an error:
Fiddler has detected a protocol violation in session #n1.
Content-Length mismatch: Response Header indicated n2 bytes, but
server sent n3 bytes.
If the response header indicates a size greater than than actual size, then the results could still be interpreted by the browser.
If the response header indicates a size less than the actual size, then the browser could not interpret the results.
The obvious assumption to make there is that the response handling code reads the Content-Length header and doesn't read any more data than that stipulated in the length.
The next step in my investigation is to compare the request/response headers for jQuery version 1.6.1 (which breaks) and version 1.4.2 (which does not break).
jQuery 1.6.1 request header:
GET /Web/Services/CmsWebService.svc/GetAvailableVideosForCompany?companyIdString=2&textFilter=3DSBDL2&_=1315869366142 HTTP/1.1
X-Requested-With: XMLHttpRequest
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:52200/Web/Admin/PlayerGroupEditor.aspx?groupid=76
Accept-Language: en-au
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Host: localhost:52200
Connection: Keep-Alive
Cookie: .ASPXAUTH=CE853BBD860F40F0026400610074006D006500640069006100310000002B5387799D71CC01002B5B5D62C771CC0100002F0000006B119589A7305098A560E57515498C56ECB332035F300427CDA2B28205D5E6B6
jQuery 1.6.1 response headers
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 12 Sep 2011 23:02:36 GMT
X-AspNet-Version: 4.0.30319
Content-Encoding: gzip
Content-Length: 140
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close
And here is the request header when I use jQuery 1.4.1. Notice that the Accept header is different from the jQuery 1.6.1 value.
GET /Web/Services/CmsWebService.svc/GetAvailableVideosForCompany?_=1315870305531&companyIdString=2&textFilter=3DSBDL2 HTTP/1.1
Referer: http://localhost:52200/Web/Admin/PlayerGroupEditor.aspx?groupid=76
Content-Type: application/x-www-form-urlencoded
X-Requested-With: XMLHttpRequest
Accept: application/json, text/javascript, */*
Accept-Language: en-au
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Host: localhost:52200
Connection: Keep-Alive
Cookie: .ASPXAUTH=CE853BBD860F40F0026400610074006D006500640069006100310000002B5387799D71CC01002B5B5D62C771CC0100002F0000006B119589A7305098A560E57515498C56ECB332035F300427CDA2B28205D5E6B6
And the response back to jQuery 4.1.1:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 12 Sep 2011 23:31:46 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 131
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close
So the obvious difference is that when the call is made via jQuery 1.6.1 the response is compressed using gzip, and when the call is made via jQuery 1.4.2 the response is not compressed.
So now I can do a work around solution, which is to override the default Accept header to ensure it does not contain the "q=0.01" string. (The best explanation I can find for "q=0.01" is here, but I fail to see why my service implementation is interpreting this as a request to zip up the response badly.)
// Make the AJAX call, passing in the company id and the filter string
jQuery.ajax(
{
accepts: 'application/json, text/javascript, */*',
cache: false,
url: "../Services/CmsWebService.svc/GetAvailableVideosForCompany",
type: "GET",
complete: function (jqXHR, textStatus) {
var responseText = jqXHR.responseText;
jQuery('#debugConsole').text(responseText);
availableVideosPopulationState.isRunning = false;
setTimeout(populateAvailableVideosListBox, 100);
},
data: { "companyIdString": queryParameters.companyIdField,
"textFilter": queryParameters.filterText
},
dataType: 'json',
error: function (jqXHR, textStatus, errorThrown) {
var errorString = 'Error thrown from ajax call: ' + textStatus + 'Error: ' + errorThrown;
alert(errorString);
},
success: function (data, textStatus, jqXHR) {
populateVideoListFromAjaxResults(data);
}
}
);
So after all this investigation, the remaining question is why is there a disparity between the content length header and the actual content length when the response is GZIP compressed?
I'm using a WCF service with webHttpBinding.
First of all-Very good question. This question provided me with enough information to reach a solution for my problem.
I had a similar issue, and posting the fix here- so that it might help someone.
Ajax get & post requests were returning null in IE
Was working fine in rest of the browsers, but saw the 'Response Header indicated n bytes, but server sent nn bytes' message in fiddler for the request.
The obvious assumption to make there is that the response handling
code reads the Content-Length header and doesn't read any more data
I think so too!
In this case, I was clear with one thing. Something was tampering the request/response.
I tried switching back to older version of jQuery (as mentioned in your question), but that didn't help.
Fix-
I opened up the web config of my application, and read through it.
There was a 'RadCompression Module' from telerik included in modules, and on removal of it everything started working fine.
RadCompression module is known to be buggy and cause multiple issues by compressing the Response.
If you are having similar issues, try checking what might be intercepting your request/response.
Response Header indicated 140 bytes, but server sent 254 bytes says much. Does the same happen independently of the browser you use? If so, we may say that IE or jQuery 1.4.3 and further in IE does not read bytes after reading as many bytes as specified in Response Header, while other browsers read all the content anyway.
It is also possible (yet I hardly believe this) that response header is wrongly formed only for IE requests. Then you must look at the differences between IE and other browser requests and your service code. Maybe your services handles IE requests specifically?
It would be interesting to calculate how much bytes there is after the last captured quotation mark (") in your JSON string. 114 maybe?

Authorize with JsonReult action jQuery ajax returned status code 200 when not authorized

I have JsonResult action which required authentication and special role
[Authorize(Roles = "User")]
public virtual JsonResult Cancel()
{
//...
}
But when for example i log off and hit this action with jQuery ajax i could see that status code is 200, but it is should be 401.
$.ajax({
url: "/Cancel/",
type: "POST",
dataType: "text",
cache: false,
success: function (data, textStatus, xhr) {
alert(xhr.status); //200 here when unauthorized
}
});
So I really not able to execute the controller logic because it is not authorized, i checked that on debug, but why i am getting status code 200 in jquery ajax?
UPDATED:
In Fiddler it is saying status code 302 and i could see that request to /Acount/Login was made after /Cancel request.
/Cancel - 302
/Acount/Login - 200
In Chrome network Status Code:302 Found and also i could see that login controller(/Acount/Login) getting called after /Cancel was called.
/Cancel - 302
/Acount/Login - 200
Complete request details in Opera network
Could someone explain whats happening, why jquery didn't get correct status code?
Really what i want to do - a want to get correct status code and if it is 401 i want to redirect user to login page (window.location.href = " /Acount/Login")
Request details
POST /Cancel/ HTTP/1.1
User-Agent: Opera/9.80 (Windows NT 6.1; U; en) Presto/2.9.168 Version/11.50
Host: localhost:999
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate
Referer: http://localhost:999/Action
Cookie: style=normalText; ASP.NET_SessionId=latzewpi3kqmkq4meljv0ln5
Connection: Keep-Alive
Content-Length: 0
Accept: text/plain, */*; q=0.01
X-Requested-With: XMLHttpRequest
Content-Type: text/xml; charset=utf-8
Content-Transfer-Encoding: binary
Response details
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: /Account/LogOn?ReturnUrl=%2fCancel%2f
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 11 Aug 2011 03:04:53 GMT
Content-Length: 169
FormsAuthentication have handler in its http module, that will redirect all 401 responses to login page instead of error page.
Looking at source code of FormsAuthenticationModule there should be (quite ugly) workaround - if you append ReturnUrl=/ to your query string, the module should do no redirection.
The best solution is probably to write own http module for authentication - you can open FormsAuthenticationModule in reflector and use it as reference.

Resources