I'm attempting to use AJAX to call make a SOAP call (not cross-site, so it shouldn't run into difficulties with proxies, etc.)
However, this requires two custom headers in the XHR, SOAPTarget and SOAPAction. Currently, I'm using jQuery to make the ajax call like so:
jQuery.ajax({
url: this.location,
type: 'POST',
data: sm,
dataType: "xml",
contentType: "text/xml",
processData: false,
beforeSend: function(xhr){
xhr.setRequestHeader(
"SOAPTarget",
this.location
);
xhr.setRequestHeader(
"SOAPAction",
this.urn
);
},
success: jQuery.jSOAPClient.success,
error: jQuery.jSOAPClient.error
});
The code all executes as expected, however when I view the headers in Firebug, there's no change to them.
XHR will not accept a request header with a null value and, as it turns out, the this in this block refers to the Ajax call rather than the object that the ajax call is part of.
This question should probably be renamed "noob mistakes happen".
I recently had a similar problem. Instead of using 'beforeSend' try using ajaxSend.
Related
My Code is as below for Javascript
$.ajax({
type: "POST",
url: "page/rSales.aspx",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function (res) {
alert('Success');
},
error: function (res) {
alert('Fail');
}
});
I use http tracer tools to trace whether or not the parameter is passing on to my backend - and it is not. I have also tried adding contentType: 'application/json; charset=utf-8', adjust parameter by adding colon, but none of it is working.
My Backend code C# :
Request.Params["ListID"].ToString();
It always returns null, due to the parameter not passing on. I am wondering what is causing this problem and how should I resolve it.
The Request.Params collection does not support JSON requests, so you have to parse response body manually (or send it as form data).
https://msdn.microsoft.com/en-us/library/system.web.httprequest.params(v=vs.110).aspx says "Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items."
For firefox you declare var event; before your ajax call this is very well known issue in firefox.
When I first load a page I make an ajax call to bring some data for the client-side. The call is made to a different domain and the answer comes as JSONP. The call looks similar to:
$.ajax({
type: "GET",
url: url + "?callback=?",
dataType: "jsonp",
contentType: "application/javascript;charset=UTF-8",
async: true,
success: successCallback,
error: errorCallback,
cache: true,
jsonpCallback: jsonCB
});
'application/javascript' would be the possible culprit here as I did my research on the subject but this is present in a previous version of the code which never had this problem.
On all browsers except IE I receive the following error (sometimes, usually the first time and then the problem dissappears) :
script5007 object not found - line 1, char 1
The JSONP received looks like that:
func({"result":"abc"})
The param of the func is a valid JSON as I checked this using jslint.
Any idea will be highly appreciated! Thank you!
You're missing the object brackets { } inside your $.ajax function. Modify it like so:
$.ajax({
url:'',
contentType: 'application/javascript;charset=UTF-8',
crossDomain:true
......
});
The jQuery $.ajax method either takes a url parameter and an optional parameter of additional options specified as an object, or an object parameter including the url.
I have a dynamic mock setup using mockjax, and it works for most of my ajax requests, but fails when the dataType is set to Script, and lets the request fall through to regular Ajax handler.
// gets mocked
$.ajax({
type: "GET",
url: "http://myurl.com/myfile.js?_=1395314460347"
})
// does not get mocked!
$.ajax({
type: "GET",
dataType: "script",
url: "http://myurl.com/myfile.js?_=1395314460347"
})
How can I configure dynamic mocks in mockjax to intercept requests with the dataType set?
UPDATE: example code for mockjax definition
I am creating dynamic mock, so I am defining via function, not plain object, something like this...
$.mockjax(function(settings) {
// settings.url == '/restful/<service>'
var service = settings.url.match(/\/restful\/(.*)$/);
if ( service ) {
return {
proxy: '/mocks/' + service[1] + '.json',
// handle `dataType: 'script'`
dataType: 'application/javascript'
};
}
return;
});
This appears to be a bug with how Mockjax handles crossDomain script requests. It is not doing anything special to detect the crossDomain request (like it does with JSONP) and as such, when it passes the request back to the original $.ajax method – jQuery never uses the mocked up XHR object it was provided by Mockjax.
So in essence, Mockjax is intercepting the request, and then passes it right back to jQuery and it fails on you.
I opened an issue here so this can be fixed: https://github.com/appendto/jquery-mockjax/issues/136
In the mean time you have a two choices. If you want to quickly patch mockjax, add this line to around 471:
origSettings.crossDomain = false;
That section will look like this when you are done:
mockHandler.cache = requestSettings.cache;
mockHandler.timeout = requestSettings.timeout;
mockHandler.global = requestSettings.global;
origSettings.crossDomain = false;
copyUrlParameters(mockHandler, origSettings);
The other alternative (which I recommend against), is adding crossDomain: false to your actual AJAX request. I don't recommend this due to the need to remove that line when you remove your mocks later.
Thanks #Nicholas Cloud for pinging me and bringing this issue to my attention.
Are you setting the dataType property in your mocked endpoints?
See: https://github.com/appendto/jquery-mockjax#data-types
If you are, have you tried setting the mock dataType to application/javascript?
$.mockjax({
type: "GET",
dataType: "application/javascript",
url: "myfile.js?_=1395314460347",
responseText: "(function () { alert('hello world!'); }());"
});
$.ajax({
type: "GET",
dataType: "script",
url: "myfile.js?_=1395314460347"
});
The following ajax works exactly as advertised in Chrome. HTTP PUT is used to trigger the insertion of an object into a RESTful API.
$.ajax({
type: "PUT",
url: "/ajax/rest/team/create/",
dataType: "json",
processData: false,
data: JSON.stringify(teamObject),
success: function (response) {
teamObject = response.object;
}
});
I note that the jQuery API docs helpfully tell me that PUT and DELETE may work but are not guaranteed in all browsers. Such as is my problem.
How is a RESTful API supposed to be implemented on the client side with a problem like this?
EDIT: Firebug tells me that FF is indeed issuing a PUT, but for some currently unknown reason it's dying before getting to the server. To repeat, this works fine in Chrome.
EDIT: Fiddler doesn't see the FF attempt at all. :(
I got the following to work.
var payload = JSON.stringify(teamObject)
syncHTTP('/ajax/rest/team/create/', 'PUT', payload);
function syncHTTP(url,method,payload) {
var client = new XMLHttpRequest();
client.open(method, url, false);
client.setRequestHeader("Content-Type", "text/plain");
client.send(payload);
}
I'd rather use jQuery than roll my own tho. :| If anyone ever figures it out, just add an answer and if it works I'll accept it.
Thanks.
$.ajax({
type: "PUT",
url: "/ajax/rest/team/create/",
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(teamObject),
success: function (response) {
teamObject = response.object;
}
});
You need to add contentType. When contentType is set to application/json jquery do not try to create JSON object from JSON string but send it as is - as string.
I'm sure this is a basic syntax error but I'm trying to make a rest call using jQuery mobile ajax (code below) and as far as I can tell the ajax is not triggering.
function triggerCall() {
alert("function triggered");
$.ajax({
type: "GET",
dataType: "jsonp",
url: REST Url,
success: function (data) {
alert(data);
}
});
Any help would be appreciated
if you're actually writing url: REST Url, then you must change it to either a var, or a string.. that would be a problem
I believe that if you're using JSONP, you need to specify the callback in the $.ajax request and then again in your REST file return. Here is an example of what I've been using succesfuly (It's not perfect though, I'm sure).
$.ajax({
url: 'www.domain.com/string/to/your/REST/api',
data: {
dataToBeSent: variable,
dataToBeSent: sessionStorage.getItem('local/session Storage'),
dataToBeSend: "or a string"
},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data){
alert("Huzzah!");
},
error: function(){
alert("Boohisssss");
}
}); //end ajax call
And then in the url, I'd place this code at the bottom of the file:
header("Content-type: application/json", true);
echo $_GET['jsoncallback'] . '(' . json_encode($data) . ');';
exit;
Where data is a array that is JSON encoded, using json_encode() in PHP, and then wrapped up in a callback function (the $_GET['jsoncallback'])
Like I said, it's not perfect, but it's been working for me.
Check for errors in browser console. eg. in chrome menu>tools>javascript console.
Also recommend adding an error handler to your ajax call: http://api.jquery.com/error/
Determine which method, JSONP or CORS, to use for your restful ajax calls: So, JSONP or CORS? .