Send ajax GET request to ASP .NET Web API - javascript

I use the following ajax script.
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
The attribute Route in Web API before method.
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
The genarated request from ajax.
http://localhost:xxxxx/api/tudisp/Edit/?179
How to force ajax to not generate sign '?' by id parameter.

The simplest way to do it is to change the url property of the Ajax options...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.
However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.

Related

Url that have been passed to long

Im writing this code for save an url in a file txt, that i will use too pass after the same for invoke the button share.
my problem come when i use this code
$.ajax({
url: "/condividi.php",
dataType: "json",
data: {
res: osrm_result
},
success: function(data, textStatus, jqXHR) {
alert("ciaociao");
window.open("https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2F52.16.81.189%2Findex_gen.html&src=sdkpreparse");
}
});
this trigger the error: Url too long
how i can correct this to make it work
the default method which jQuery uses is GET which has limited data length,
try sending the data by POST (you should of course update the condividi.php accordingly to serve the POST request):
$.ajax({
type: "POST",
url: "/condividi.php",
dataType: "json",
data: {
res: osrm_result
},
success: function(data, textStatus, jqXHR) {
alert("ciaociao");
window.open("https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2F52.16.81.189%2Findex_gen.html&src=sdkpreparse");
}
});

How to parse parameters from Ajax return string

I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Access the URL of an jQuery Ajax Request in the Callback Function

Is there a way that I can see the URL that was requested when I do an Ajax request with jQuery?
e.g.,
var some_data_object = { ...all sorts of junk... }
$.get('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
var real_url = ? # <-- How do I get this
})
How can I access the URL that jQuery actually used to make the request? Perhaps some method/property of jqHXR? I couldn't find it in the documentation.
Thanks.
Set a break point in success method, then watch
this.url
is the real url for the request.
Here is a possible solution:
Catch the ajax call before it is sent to the server by implementing the beforeSend callback function.
Save the url and the data
Report it in the error message you generate.
var url = "";
$.ajax({
url: "/Product/AddInventoryCount",
data: { productId: productId, trxDate: trxDate, description: description, reference: reference, qtyInCount: qtyInCount }, //encodeURIComponent(productName)
type: 'POST',
cache: false,
beforeSend: function (jqXHR, settings) {
url = settings.url + "?" + settings.data;
},
success: function (r) {
//Whatever
},
error: function (jqXHR, textStatus, errorThrown) {
handleError(jqXHR, textStatus, errorThrown, url);
}
});
function handleError(jqXHR, textStatus, errorThrown, url) {
//Whatever
}
Using $.ajaxPrefilter:
// Make sure we can access the original request URL from any jqXHR objects
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
jqXHR.originalRequestOptions = originalOptions;
});
$.get(
'http://www.asdf.asdf'
).fail(function(jqXHR){
console.log(jqXHR.originalRequestOptions);
// -> Object {url: "http://www.asdf.asdf", type: "get", dataType: undefined, data: undefined, success: undefined}
});
http://api.jquery.com/jQuery.ajaxPrefilter/
It seems like the ajaxSend global handler (http://api.jquery.com/ajaxSend/) provides the url in its settings parameter. You could store a mapping from the xhr object to the url in your ajaxSend callback, then in your success callback look it up given the xhr object that it provides you with.
var mappings = {};
$.ajaxSend(function(event, xhr, settings) {
mappings[xhr] = settings.url;
});
$.ajax({
url: "http://test.com",
success: function(data, textStatus, xhr) {
console.log("url = ", mappings[xhr]);
delete mappings[xhr];
}
});
This has the advantage of not having to modify each $.ajax() object.
FYI, as an addition to airbai's comment -I cannot comment inside his answer,- you can add your own data to the call and retrieve it inside the callbacks. This way you don't have to parse the URL.
In this example JSONP request I have added the variable user_id (tested with jQuery 3.2):
var request = $.ajax({
dataType: "json",
url: "http://example.com/user/" + id + "/tasks?callback=?",
user_id: id,
success: function(data) {
console.log('Success!');
console.log("User ID: " + this.user_id);
},
timeout: 2000
}).fail(function() {
console.log('Fail!');
console.log("User ID: " + this.user_id);
});
I couldn't find it in the docs either. Maybe just add it to the jqXHR object through a "proxy" wrapper like...
I haven't tested this, so you may need to call
$.param() and concat to the url. See http://api.jquery.com/jQuery.param/
var myGet = function(url, data, success) {
$.get(url, data, function(data, textStatus, jqXHR) {
jqXHR.origUrl = url; // may need to concat $.param(data) here
success(data, textStatus, jqXHR);
});
}
usage:
var some_data_object = { ...all sorts of junk... }
myGet('/someurl.php',some_data_object, function(data, textStatus, jqXHR) {
var real_url = jqXHR.origUrl;
})

Reusable JS ajax pattern (jquery)

I'd like to know if there is a better approach to creating re-usable ajax object for jquery.
This is my un-tested code.
var sender = {
function ajax(url, type, dataType, callback) {
$.ajax({
url: url,
type: type,
dataType: dataType,
beforeSend: function() {
onStartAjax();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
callback.failure(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data, textStatus) {
callback.success(data, textStatus);
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjax();
}
});
},
function onStartAjax() {
// show loader
},
function onEndAjax() {
// hide loader
}
};
<script type="text/javascript">
var callback = {
success: function(data, textStatus) {
$('#content').html(data);
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')');
}
}
sender.ajax(url, type, dataType, callback);
</script>
You can set the basic options that you always have the same separately.
for instance if you always use the same thing here:
type: type,
dataType: dataType,
for those types, you can set them separately.
Here is how you do that type of thing:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}"
});
NOW those are set and you can simplify your individual ajax calls.
EDIT:
NOTE: Setting parameters to $.ajax override these defaults. Thus presetting “data” to an empty JSON string is safe and desired. This way, any $.ajax call that does specify a data parameter will function as expected, since the default will not be used. This helps avoid issues that can be difficult to find on a deployed site.
Here is what I did:
var ajaxclient = (function (window) {
function _do(type, url)
{
return $.ajax({
url:url,
type:type,
dataType:'json',
beforeSend: _onStartAjax
}).always(_onEndAjax);
}
function _onStartAjax()
{
console.log("starting ajax call");
}
function _onEndAjax()
{
console.log("finished ajax call");
}
return {
do:_do
}
}(this));
Example usage:
ajaxclient.do("get","http://...").done(function(data) {console.log(data);})
I'd probably go the whole hog and have an Ajax Object create.
var ajax = new MySuperAjax(url, data);
ajax.onComplete = function(){}
or similar. You seem to have a halfway between a function which has some defaults it extends with those you apss in and an object for it.

Categories