Jquery File Upload - Not sending headers in IE9 - javascript

I'm using jQuery Fileupload to upload files. Its not sending headers that I set to the server. Why is the Authorization header missing only in IE but passed in chrome?
Here is the code:
upload_photo: function(){
var url = '/api/v1/upload';
$('#photoupload').fileupload({
url: url,
dataType: 'json',
paramName: 'uploadFile',
beforeSend: function ( xhr ) {
setHeader(xhr);
$("#check_progress").html('true');
},
done: function (e, responseJSON) {
var id = responseJSON.result.id;
url = responseJSON.result.url;
var photo_ids = $("#photo_ids");
var val = photo_ids.val();
photo_ids.val(val + id.toString() + ",");
$(".photothumb-wapper").append('<div class=\"photothumb\" id="post_photo_'+id+'"><div><img src=\"'+url+'\" /></div><img class=\"thumb-delete photo_delete\" id=\"'+id+'\" title=\"Remove\" src=\"/assets/delete-red.png\"></div>');
$("#check_progress").html("");
},
start: function (e, data) {
$(".photothumb-wapper").append('<div class="photothumb photoprogress" style="border:none"><img src="/assets/ajax-loader.gif" /></div>');
},
always: function (e, data) {
$(".photoprogress").remove();
}
});
}
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7');
};
Headers passed in IE:
Request : POST /api/v1/upload HTTP/1.1
Accept : text/html, application/xhtml+xml, \*/\*
Referer : url
Accept-Language : en-US
User-Agent :Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Content-Type :multipart/form-data; boundary=---------------------------7de2dfe037204f6
Accept-Encoding :gzip, deflate
Host :url
Content-Length :776595
DNT :1
Connection :Keep-Alive
Cache-Control :no-cache
Cookie :sitecookies
Headers passed in Chrome:
ResponseHeaders
date : Tue, 04 Mar 2014 07:32:20 GMT
Connection: Keep-Alive
content-length:225
content-type:application/json; charset=utf-8
cache-control:no-cache
RequestHeaders
Accept: application/json, text/javascript, \*/\*; q=0.01
Authorization: Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7
X-Requested-With: XMLHttpRequest
Why is the Authorization header missing in IE?

This answers my question,
Only browsers with support for XHR file upload support setting custom headers.

As a workaround in old browsers like our dear IE, you could set a cookie with the authentication token when the user authenticate and then get it in the server and verify it the same way you verify the header one. I know that it is not the most elegant solution but it works.

Related

jQuery Ajax Form Data settings convert to pure javascript

Found the answer thanks from Patrick Evans:
window.onload = function()
{
var data = new FormData();
data.append("gcd", "gcd");
data.append("name", "name");
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(options.data || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
Here is my Ajax test javascript using jQuery and Pure Javascript Ajax:
window.onload = function()
{
var url = "GRNM";
var data = {
gcd: "gcd",
name: "name"
};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
Pure Javascript Ajax:
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(JSON.stringify(options.data) || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
And this is the result:
jQuery: I could get the value data successfully
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 200
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: keep-alive
Content-Length: 43
Content-Type: application/json
Date: Fri, 27 Aug 2021 06:20:37 GMT
Keep-Alive: timeout=60
Request Headers:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 17
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
gcd: gcd
name: name
Pure Javascript: I couldn't get the data
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 400
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: close
Content-Language: en-US
Content-Type: text/html;charset=Shift_JIS
Date: Fri, 27 Aug 2021 06:20:37 GMT
Transfer-Encoding: chunked
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 27
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
{"gcd":"gcd","name":"name"}:
My Spring Boot Controller couldn't find the gcd and name parameter that came from pure javascript because the Form Data format is different. I've also tried to use FormData() but couldn't make it work.
My Form Data becomes like this:
Form Data:
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name: "gcd"
gcd
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name="name"
name
------WebKitFormBoundaryLgD8tjkxnVk4hfiE--
I've also tried changing http_request.send(JSON.stringify(options.data) || null); to http_request.send(options.data || null); but didn't worked.
How can I achieve the same result as jQuery? How can I pass my var data object to controller using Ajax POST same as jQuery?
You need to supply the correct content-type with the correct content.
If you want to send JSON text you have to use application/json content-type
http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(JSON.stringify(options.data));
If you want to use the FormData object you need the multipart/form-data content-type
let fd = new FormData();
for(let key in options.data){
fd.append(key,options.data[key]);
}
//don't need to explicitly set content-type when sending FormData
//it will automatically do that
//http_request.setRequestHeader('Content-Type', 'multipart/form-data');
http_request.send(fd);
If you just want to use your object you will need to convert it to one of the previously mentioned methods or create a param string from it and use application/x-www-form-urlencoded content-type
//builds a param=value&param2=value2 type of string from your options.data object
let paramStrings = [];
for(let key in options.data){
paramStrings.push(`${key}=${options.data[key]}`);
}
let data = paramStrings.join('&');
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.send(data);

php can not parse json data to ajax

The question is very common in stackoverflow. I have been to too many solution provided in this forum for problem like mine. but it did not help. So i am posting it. Please please be kind enough to answer me.
Problem:
I am trying to send an integer from cakephp controller function to view having ajax call.
I keep getting this error for all the solutions i tried from here and other forums.
"SyntaxError: Unexpected token a in JSON at position 0"
Please tell me what is wrong looking at my code :
I can see clearly i get data in json format in php while i make echo but not in main Ajax call.
Console says :the result is {"data":1}
Controller :
public function addit()
{
$mycount = 1;
$responseJSON = array(
'data' => $mycount
);
//$responseJSON = array('status' =>'true', 'result'=>$arr);
header('content-type:application/json');
$response = json_encode($responseJSON);
echo $response;
}
ajaxcall in view:
$(document).ready(function(){
$('#bn_cart').click(function(event){
//alert('clicked');
var form_data = $(this).serialize();
var id = $('#id').val();
alert("your item id is "+ id);
var csrfToken = <?php echo(json_encode($this->request->getParam('_csrfToken'))) ?>;
//alert("your form data "+csrfToken);
event.preventDefault();
$.ajax({
headers: {
'X-CSRF-Token': csrfToken
},
url:'../addit',
type:'POST',
data: { id : id },
dataType:'json',
success:function(xhr, response){
var respons = response;
console.log("conosle success says "+ (respons.result));
alert("success"+respons.result);
},
error:function(xhr, e,etype,response){
//alert("<br>error<br>"+ error.responseText.message);
alert("response = "+ response +"xhr = "+ xhr + " e = " + e + " etype = "+ etype);
console.log(" response =" + response + "error ="+ e +"xhr = "+ xhr + " etype = "+ etype );
// $("#result").html(error.Message);
// alert('error ='+(error.Message));
}
});
});
});
Network>Header:
Request URL: http://localhost/shoppingCart/products/addit
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 583
Content-Type: text/html; charset=UTF-8
Date: Tue, 23 Oct 2018 14:10:08 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=99
Pragma: no-cache
Server: Apache/2.4.29 (Win32) OpenSSL/1.0.2n PHP/7.1.15
X-DEBUGKIT-ID: 182187f0-546d-48d4-9e5a-6746a40dba64
X-Powered-By: PHP/7.1.15
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: csrfToken=0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b; CAKEPHP=mhphclr8cuvacrlotbit45dd3l; csrftoken=t0p47S5P7NBcwGGQ9sfuNGLi5JJDkll8ifuCWhG3W6MRSIewe9GtRNjanPUqms54
Host: localhost
Origin: http://localhost
Referer: http://localhost/shoppingCart/products/view/2
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
X-CSRF-Token: 0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b
X-Requested-With: XMLHttpRequest
Network>>Response :
{"data":1}
You need to return your response encoded in json. You are trying to echo a non json-encoded response which will not work.
public function addit()
{
$mycount = 1;
$responseJSON = array(
'data' => $mycount
);
//$responseJSON = array('status' =>'true', 'result'=>$arr);
header('content-type:application/json');
return json_encode($responseJSON);
}
Ajax call :
success:function(data, status, jqxhr)
var respons = data;
console.log("conosle success says "+ (respons.result));
alert("success"+respons.result);
},

jquery ajax long pending status type put and json only on android

The same code is working fine on every desktop browser (Safari, Chrome, Firefox, IE) or iPad 4 in 1-2 seconds. But fails with long pending (2-4 minutes) when testing on Android tablet (4.2.2) browser / Google Chrome 31 or iPad 2 UMTS.
jquery version = 1.10.2
var datasend;
$.putJSON = function(url, data, callback) {
return $.ajax({
url : url + "?_=" + jQuery.now(),
beforeSend: function(par1, par2, par3){
console.log('beforeSend: ',par1, par2, par3);
},
error: function (par1, par2, par3){
console.log('error: ',par1, par2, par3);
},
success : callback || function() {
},
data : JSON.stringify(data),
timeout: 15000,
dataType : 'json',
type : 'PUT',
cache: false,
contentType : 'application/json; charset=utf-8'
});
};
$('#postklick').on('click', function() {
$.putJSON('/rest/idea', datasend, function(data, statusText, xhr) {
var response = $.parseJSON(xhr.responseText);
console.log(response.exception);
}).fail(function(xhr, status, statusError) {
console.log(statusError);
});
return false;
});
datasend = {
"name": "idee",
"description": "adasdasdasa",
"base64Image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeoAAAGkCAYAAAD+P2YmAA..."
};
Response Header:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Server: Microsoft-IIS/7.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: accept, origin, content-type
Access-Control-Max-Age: 1728000
access-control-allow-credentials: true
X-REST-Response-State: ok
X-Powered-By: ASP.NET
Date: Fri, 24 Jan 2014 14:55:18 GMT
Content-Length: 811
Request Header:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Content-Length: 326765
Connection: keep-alive
In chrome//net-internals/#events I see:
...
[st = 10] HTTP_STREAM_PARSER_READ_HEADERS --> net_error = -101 (ERR_CONNECTION_RESET)
[st = 128859] HTTP_TRANSACTION_RESTART_AFTER_ERROR --> net_error = -101 (ERR_CONNECTION_RESET)
...
Any ideas?

Got XHR.status 0 while doing http get request through jquery code while HTTP response is 200 ok

I am trying to send get request to REST based API(JAX-RS/Jersey based API) through jquery. Request reaches successfully to API as I have seen in logs and on firebug i saw 200 ok response
below is my jquery based client
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'http://mtnlp.com:8080/restdemo/resources/employee/1',
dataType: "json",
success: function(data){
alert("success");
},
error: function(xhr){
alert("error"+xhr.status);
}
});
});
});
But xhr.status is 0.
MY resource is
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson( #PathParam("empno") int empno) {
JSONObject jObject = new JSONObject();
System.out.println("someone calls me");
switch(empno) {
case 1 :
jObject.put("name", "George Koch");
jObject.put("age", "58");
break;
case 2:
jObject.put("name", "Peter");
jObject.put("age", "50");
break;
default:
jObject.put("name", "Unknown");
jObject.put("age", "-1");
} // end of switch
return jObject.toString();
}
When i use my jersey based client it works fine. but with jquery based client I am facing above issue.
Please find below the request and response headers for HTTP get request
Response Headers
Content-Type: application/json
Date: Tue, 04 Jun 2013 06:38:12 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate Accept-Language en-US,en;q=0.5
Host: localhost:8080
Origin: null
User-Agent: Mozilla/5.0 (Windows NT5.1; rv:19.0) Gecko/20100101 Firefox/19.0

$.ajax to dojo.xhr for use in sharepoint web-services not working

This function uses jquery and Dojo libraries to fetch infor from Sharepoint. I want to use only Dojo. How can I port the jquery part to Dojo?
To be specific, the $.ajax call needs to be converted to dojo.xhrPost
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "xml",
data: getSOAPEnvelope(fields, guid),
complete: function (xData, status) {//parse xml to json},
contentType: "text/xml"
})
This is my attempt:
dojo.xhrPost({
url: url,
sync:true, //in jquery, sync => async
handleAs:"xml", //in jquery, handleAs => dataType
content:getSOAPEnvelope(fields, guid),//in jquery, content => data
load: (fn from 1.1 section goes here) //in jquery, load => complete
headers: {Content-Type:"text/xml"} //in jquery is contentType:"text/xml"
}
});
And this is the full original (unported) function:
/*
Returns a json object from a sharepoint list
url and guid arguments are strings (without the {})
fields is an optional array of fileds to be output. this will reduce teh size of the response.
uniqueFields is an optional array of fileds to be filtered. For example:
if the list has
row,fruit,color,size
1,banana,green,small
2,banana,yellow,small
3,apple,yellow,medium
4,apple,green,small
5,apple,red,small
for a list of fruits, you put: getJsonItems(url,guid,true,['row',fruit','color'],['fruit']) -> returns rows 1 and 3
for a list of fruit sizes, do: getJsonItems(url,guid,true,false,['fruit','size']) -> returns all columsn for items (1,3,4)
*/
dojo.require("dojox.xml.parser");
function getJsonItems(url, guid, fields, uniqueFields) {
//prepare the SOAP envelope
var jsonItems = []
var pkHash = []
//1. fetch xml data from server and parses into json
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "xml",
data: getSOAPEnvelope(fields, guid),
complete:
//1.1 when data is received from the server, parse it to json
function (xData, status) {
//1.1.1 convert xml to DOM for easier manipulation
var dom = dojox.xml.parser.parse(xData.responseXML.xml)
//1.1.2 get xml rows
var rows = dom.getElementsByTagName("z:row")
//1.1.3 parse each xml row and add it to jsonItems array
dojo.forEach(rows, function (row, i) {
var jsonItem = {};
var uniqueKey = "";
//1.1.3.1 parse each xml row into json object. (It removes the ";#" prefix and other MS junk for lookup values or values with spaces)
for (var j = 0; j < row.attributes.length; j++) {
//1.1.3.1.1 parse the col name by removing ows_, replacing hex numbers (x_00xx_) and trimming spaces
var col = row.attributes[j].nodeName.replace("ows_", "").replace(/_x([A-F\d]{4})_/gi, function (str, hexNum) { return eval("\"\\u" + hexNum + "\"") }).replace(/^\s+|\s+$/g, "$1")
var val = row.attributes[j].nodeTypedValue.replace(/\d+;#/, "")
//1.1.3.2 add property to jsonItem
if (dojo.indexOf(fields?fields:[col], col) >= 0) jsonItem[col] = val;
//1.1.3.3 filter duplicates based on uniqueFields
if (dojo.indexOf(uniqueFields?uniqueFields:[col], col) >= 0) uniqueKey += col + val;
}
//1.1.3.3 add to uniqueKey to pkHash
if (dojo.indexOf(pkHash, uniqueKey) < 0) {
pkHash.push(uniqueKey);
jsonItems.push(jsonItem)
}
})
},
contentType: "text/xml"
})
//2. return parsed xml to json ojbect
return jsonItems
}
function getSOAPEnvelope(fields,guid){
//prepare ViewFields element
var viewFields = "";
if (fields) {
viewFields = "<viewFields><ViewFields Properties='True'>"
dojo.forEach(fields, function (e) {viewFields += "<FieldRef Name='"+e+"'/>"});
viewFields += "</ViewFields></viewFields>";
}
var envelope = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
<soapenv:Body> \
<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
<listName>{" + guid + "}</listName>\
" + viewFields + " \
</GetListItems> \
</soapenv:Body> \
</soapenv:Envelope>";
return envelope;
}
If you use content in dojo.xhr, Dojo will treat the content as a JSON object and convert it using form encoding. For example, if you pass {a : 1, b : 2} as content, the actual data sent to server is a=1&b=2.
Your getSOAPEnvelope function actually returns a simple string, so you can not use content. Just remove content and use postData instead. For example,
dojo.xhrPost({
url: url,
sync:true, //in jquery, sync => async
handleAs:"xml", //in jquery, handleAs => dataType
postData:getSOAPEnvelope(fields, guid),//in jquery, content => data
load: (fn from 1.1 section goes here) //in jquery, load => complete
headers: {Content-Type:"text/xml"} //in jquery is contentType:"text/xml"
}
});
I wish I can use Firebug but I have to use fiddler because FF will not SSO on Sharepoint. I am using VS 2010 to debug and it breakes when the "access denied error" IE dialog shows at xhr.open function. This prevents anything to be posted even if I ignore or continue the error. This happens at line 11208 of dojo.xd.js.uncompressed ver 1.6 from google cdn:
// IE 6 is a steaming pile. It won't let you call apply() on the native function (xhr.open).
// workaround for IE6's apply() "issues"
xhr.open(method, ioArgs.url, args.sync !== true, args.user || undefined, args.password || undefined);
if(args.headers){
for(var hdr in args.headers){
if(hdr.toLowerCase() === "content-type" && !args.contentType){
args.contentType = args.headers[hdr];
}else if(args.headers[hdr]){
//Only add header if it has a value. This allows for instnace, skipping
//insertion of X-Requested-With by specifying empty value.
xhr.setRequestHeader(hdr, args.headers[hdr]);
}
}
}
the arguments values being passed are:
method:POST,
ioArgs.url:*my sharepoint url*,
args.user:*undefined*,
args.password:*undefined*
I have a feeling it's the username / pwd. Just something missing on the dojo.XHRPost params or simply I need to use other dojo function (such as dojo.io.iframe)
Now, if you want to compare the XHR responses, with jquery I get:
A confirmation box from IE stating that "the page is accessing information that is not under its control with a security risk"
A first attempt to request info from _vti_bin/lists.asmx with a 401 Unauthorized response
A second succesful attempt to request the same
Here are the details:
1st Request with jquery:
POST https://a101.sharing.***.com/sites/HOU000169/_vti_bin/lists.asmx HTTP/1.1
Accept: application/xml, text/xml, */*
Accept-Language: en-us
x-requested-with: XMLHttpRequest
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; MS-RTC LM 8)
Host: a101.sharing.***.com
Content-Length: 0
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: WSS_KeepSessionAuthenticated=80
Authorization: NTLM TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAGAHEXAAAADw==
1st Response
HTTP/1.1 401 Unauthorized
Content-Length: 1539
Content-Type: text/html
Server: Microsoft-IIS/6.0
WWW-Authenticate: NTLM TlRMTVNTUAACAAAAEAAQADgAAAAFgomioKDRqMorlxAAAAAAAAAAALQAtABIAAAABQLODgAAAA9BAE0ARQBSAEkAQwBBAFMAAgAQAEEATQBFAFIASQBDAEEAUwABABgASABPAFUASQBDAC0AUwAtADYAMAA3ADgABAAkAGEAbQBlAHIAaQBjAGEAcwAuAHMAaABlAGwAbAAuAGMAbwBtAAMAPgBoAG8AdQBpAGMALQBzAC0ANgAwADcAOAAuAGEAbQBlAHIAaQBjAGEAcwAuAHMAaABlAGwAbAAuAGMAbwBtAAUAEgBzAGgAZQBsAGwALgBjAG8AbQAAAAAA
MicrosoftSharePointTeamServices: 12.0.0.6219
X-Powered-By: ASP.NET
Date: Fri, 16 Sep 2011 16:49:31 GMT
Proxy-Support: Session-Based-Authentication
2nd try
POST https://a101.sharing.***.com/sites/HOU000169/_vti_bin/lists.asmx HTTP/1.1
Accept: application/xml, text/xml, */*
Accept-Language: en-us
x-requested-with: XMLHttpRequest
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; MS-RTC LM 8)
Host: a101.sharing.***.com
Content-Length: 433
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: WSS_KeepSessionAuthenticated=80
Authorization: NTLM TlRMTVNTUAADAAAAGAAYAKYAAABmAWYBvgAAABAAEABYAAAAJAAkAGgAAAAaABoAjAAAAAAAAAAkAgAABYKIogYAcRcAAAAPpsehFcQrqLsci4ksbHmc0kEATQBFAFIASQBDAEEAUwBKAG8AcwBlAC4ATAAuAEwAZQB2AGkAYQBnAHUAaQByAHIAZQBIAE8AVQBCAFQAQwAtAEQALQA2ADkANgAxAAFMM6NEtmJORCTtsBAnHHWRUNRPM01quP7zKT4VD35T2Y4glT4PV6YBAQAAAAAAAFFUfpuQdMwBkVDUTzNNargAAAAAAgAQAEEATQBFAFIASQBDAEEAUwABABgASABPAFUASQBDAC0AUwAtADYAMAA3ADgABAAkAGEAbQBlAHIAaQBjAGEAcwAuAHMAaABlAGwAbAAuAGMAbwBtAAMAPgBoAG8AdQBpAGMALQBzAC0ANgAwADcAOAAuAGEAbQBlAHIAaQBjAGEAcwAuAHMAaABlAGwAbAAuAGMAbwBtAAUAEgBzAGgAZQBsAGwALgBjAG8AbQAIADAAMAAAAAAAAAABAAAAACAAAMzqw8jpvzbRjHmde0Fhp8Dw6btoC9d5sGE8/LukEd0PCgAQAOq5JkugZHw/GB0+NrLsKCMJADYASABUAFQAUAAvAGEAMQAwADEALgBzAGgAYQByAGkAbgBnAC4AcwBoAGUAbABsAC4AYwBvAG0AAAAAAAAAAAA=
<soapenv...the hole soap envelope
2nd Response
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Length: 103794
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/6.0
MicrosoftSharePointTeamServices: 12.0.0.6219
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Set-Cookie: WSS_KeepSessionAuthenticated=80; path=/
Set-Cookie: MSOWebPartPage_AnonymousAccessCookie=80; expires=Fri, 16-Sep-2011 17:19:31 GMT; path=/
Date: Fri, 16 Sep 2011 16:49:31 GMT
<?xml version...and the rest of my xml response that I'll later on parse to json
Remember that jquery works fine from the desktop after accepting the security risk but it does not work with dojo. If I move the file to the server itself, it works fine.
Bottom line question
At the end, my main concern is, why jquery can bypass the cross-domain security but not with dojo? Maybe with dojo.io.iframe but so far, no luck!
I think I found the problem. I simplified to the minimum and dojo.xhr works fine. There are some slight differences:
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "xml",
data: soap,
complete: function (xData, status) {
alert(xData.responseXML.xml)
},
contentType: "text/xml; charset=utf-8"
})
dojo.xhrPost({
url: url,
sync: true,
handleAs: "xml",
postData: soap,
load: function (xData, status) {
alert(xData.xml )
},
headers: { "Content-Type": "text/xml; charset=utf-8;" }
})
Here is the complete code. You can copy paste this script and run it from your desktop because everything is cdn and the sharepoint library I use for testing is public
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js.uncompressed.js" djConfig="parseOnLoad: true"></script>
<script>
var url = "http://msftplayground.com/_vti_bin/lists.asmx"; //this is a public sharepoint site, so you don't have to change anything
var soap = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GetListCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/" /></soap:Body></soap:Envelope>';
function jqueryAjax() {
dojo.byId("xmlResp").value = "response from $.ajax: ";
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "xml",
data: soap,
complete: function (xData, status) { dojo.byId('xmlResp').value += xData.responseXML.xml },
contentType: "text/xml; charset=utf-8"
})
}
function dojoXhr() {
dojo.byId("xmlResp").value = "response from dojo.xhrPost: ";
dojo.xhrPost({
url: url,
sync: true,
handleAs: "xml",
postData: soap,
load: function (xData, status) {
dojo.byId('xmlResp').value += xData.xml
},
headers: { "Content-Type": "text/xml; charset=utf-8;" }
})
}
</script>
</head>
<body>
<pre>
<button onclick="jqueryAjax()">test jquery</button>
<button onclick="dojoXhr()">test dojo</button>
Response:
<textarea id="xmlResp" style="height:500px;width:99%;overflow:auto"></textarea>
</pre>
</body>
</html>

Categories

Resources