I'm pretty new to Laravel, I've been trying to pass parameters to the destroy() action in my controller with Ajax, the action runs as the pictures data gets removed both from the database and the picture from storage as well, however it gives back 405 error in the console for some reason. I've tried multiple solutions posted here, but none has worked unfortunately. The destroy() action works if I'm using it purely with PHP, but I'm trying to learn a bit of Ajax as well, also I'm doing it this way because I want to do it like there are multiple photos on the site at once, and each one has its own delete button, and I want to delete the photo based on which delete button has been pressed.
It says in the response headers that only GET, HEAD allowed.
Any help would be greatly appreciated, and thank you all in advance!
Routes
Route::get('/photos/create/{albumId}', [PhotosController::class, 'create'])->name('photo-create');
Route::post('/photos/store', [PhotosController::class, 'store'])->name('photo-store');
Route::get('/photos/{id}', [PhotosController::class, 'show'])->name('photo-show');
Route::delete('/photos/{id}', [PhotosController::class, 'destroy'])->name('photo-destroy');
Controller
public function destroy($id)
{
$photo = Photo::find($id);
if (Storage::delete('/public/albums/' . $photo->album_id . '/' . $photo->photo ))
{
$photo->delete();
return redirect('/')->with('success', 'Photo deleted successfully');
}
}
Ajax
$(document).on('click', '.deletePhoto', function(e) {
var photo = $(this).val();
$('#deletePhotoId').val(photo);
$('#photoDelete').modal('show');
});
$(document).on('click', '.confirmDelete', function(e) {
var photo = $('#deletePhotoId').val();
$.ajax({
type: "DELETE",
url: "/photos/"+photo,
data: {
_token: '{{ csrf_token() }}',
},
/* success: function(response){
alert(response);
},
error: function(response) {
alert('Error' + response);
} */
})
});
Also if I have added the csrf as in the Laravel documentation like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Then it gave me 419 error no matter where I have placed it.
Here's the error
XHRDELETEhttp://photo-project.test/
[HTTP/1.0 405 Method Not Allowed 61ms]
DELETE
http://photo-project.test/
Status405
Method Not Allowed
VersionHTTP/1.0
Transferred8.43 kB (8.19 kB size)
Referrer Policystrict-origin-when-cross-origin
Allow
GET, HEAD
Cache-Control
no-cache, private
Connection
close
Content-Type
application/json
Date
Sat, 03 Jul 2021 20:21:15 GMT
Server
Apache/2.4.46 (Win64) PHP/7.3.21
X-Powered-By
PHP/7.3.21
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
en-GB,en;q=0.5
Connection
keep-alive
Content-Length
47
Content-Type
application/x-www-form-urlencoded; charset=UTF-8
Cookie
XSRF-TOKEN=eyJpdiI6IlR0bitkaitPMFhhWEdnQ1ZqL1VpTXc9PSIsInZhbHVlIjoibVREOG9JRGpOQjBqZG40QU9vWVJsS2xtT2J3OXZJK3ZjVzNzZHNKNWdQakowK1lMZ1o0RStSQWFzTVFYZ1R5cFEvNjQ2bm9ZNklYbW8xcW54ZVlzOG9sVXJXN1Z3dmU0Lys0UXRWNWZLY29Femxjb2EvS09qM0hzbm9SSndOYXIiLCJtYWMiOiI2MWJlOTc3YWFhY2NkY2VhZGM5YWZhYmE0MjcyYTc5MmRiNmQwMjU0ZmFlZmMxYzEzNTExMGU4ZjlhMTY3OTYwIn0%3D; laravel_session=eyJpdiI6IldCNU9MSHRGbnNJRlEvWDBrMmZzSmc9PSIsInZhbHVlIjoidzhoc0VFajBhZXk2dkFSa2VmNkU2UmVReVZaOFFUeGJPam1pOXI3T3gvR0FFM3crd21SODI1ZWFJZk44UThDM0VjNFdsL2V6bzNvcHk0NG9vQlpoTEtIRlNQOStxaDlvVFUvS01iOEJIUDJzODFyck11ckpZRTRzMHhVYXhHZlYiLCJtYWMiOiI5NGJmMTBlMDhlOWU0OTU4ZDkyZWRhMzlhYzIwNzFkOTAzZWI3M2RjOTEzNzI5NTYyOWFkZWIyOWMyM2E3MmM2In0%3D
Host
photo-project.test
Origin
http://photo-project.test
Referer
http://photo-project.test/albums/12
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0
X-Requested-With
XMLHttpRequest
Thank you again if you can help me in any measure as I'm kind of stuck here unfortunately.
Double-check that your photo JS variable actually has a value. If it's null for some reason, then the route being constructed would end up being the 'index' one, "/photos/", which of course does not have a DELETE http method associated with it.
Check your browser Network history to be sure. You'll see the route that it's attempting to hit, and can also double-check that against the results of php artisan route:list.
public function destroy(Request $request, $id){
$photo = Photo::find($id);
if (Storage::delete('/public/albums/' . $photo->album_id . '/' .$photo->photo )){
$photo->delete();
//if request is via ajax
if($request->ajax()){
return response()->json(['status'=>true,'message'=>'Photo Deleted Successfully']);
}
//otherwise redirect
return redirect('/')->with('success', 'Photo deleted successfully');
}
}
On Ajax Side
$(document).on('click', '.deletePhoto', function(e) {
var photo = $(this).val();
$('#deletePhotoId').val(photo);
$('#photoDelete').modal('show');
});
$(document).on('click', '.confirmDelete', function(e) {
var photo = $('#deletePhotoId').val();
$.ajax({
type: "DELETE",
url: "/photos/"+photo,
data: {
_token: '{{ csrf_token() }}',
},
dataType:'JSON',
cache:false,
success: function(response){
if(response.status){
console.log('Action Successfull....');
console.log('Response from server : ', response.message)
}
},
error: function(response) {
alert('Error' + response);
}
})
});
Just check the request type while returning response from server, If it is ajax then return the response data otherwise redirect to the page.
I'm running into a weird problem, I want to do a POST request in AJAX with the following code:
$('.login-form').on('submit', function(e) {
e.preventDefault(); // to block the behavior from HTML form
$.ajax({
type: "post",
url: "http://localhost:8080/login",
data: JSON.stringify({
username:"lmezkml",
password:"ezaezaeza"
}),
success: function(data, textStatus, jqXHR) {
console.log('success');
},
contentType: "application/json; charset=utf-8",
dataType: 'json'
});
});
Even after following the multiple topics on this problem, i'm still in trouble.
For example, i've tried :
adding dataType: 'json'
adding contentType : "application/json; charset=utf-8"
using XMLHttpRequest()
using $.post
The inspector of Chrome give me :
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/login
Request Method:POST
Status Code:400 Bad Request
**Request Headersview source**
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6
Connection:keep-alive
Content-Length:45
Content-Type:application/json; charset=UTF-8
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
**Request Payloadview source**
{username:lmezkml, password:ezaezaeza}
password: "ezaezaeza"
username: "lmezkml"
**Response Headersview source**
Connection:close
Content-Type:application/json;charset=UTF-8
Date:Wed, 09 Dec 2015 14:39:11 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Here is my code from server :
#RequestMapping(value="/login", method=RequestMethod.POST, produces={"application/json"}, consumes={"application/json"})
public ResponseEntity<?> hello(#RequestParam("name") String username, #RequestParam("password") String password) {
System.out.println("username : " + username + " password : " + password);
try {
LdapContext ctx = ActiveDirectory.getConnection(username, password);
ctx.close();
}
catch(Exception e) {
//Failed to authenticate user!
e.printStackTrace();
return new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(null, HttpStatus.OK);
}
Hope it can help to resolve my problem of 400 bad request.
Thanks in advance.
I think, problem on server.
Try send to server js object, not string, or debug in server.
I've solved my problem thanks to Alex Repeckiy. The real problem was that the data was stored in Body and ive tried to get them by parameter.
If it can help Spring Framework users, i change my function by using #RequestBody instead of #RequestParam.
Thanks !
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.
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
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>