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.
Related
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.
I need to execute several jquery Ajax calls sequentially. I'm using callbacks, so every call has a success function that execute the next Ajax call and so on.
That was really a mess and very difficult code to read. After googling a find Frame.js that looks awesome but... i can't make it work.
To simplify the problem I'm just trying to call the first web service and I'm doing this:
File: MyPage.aspx:
Frame(function (next) {
this.request = { CodSeguro: 917766 };
Emision_ConsultarSeguro(request, next, next);
next();
});
Frame(function (next,ajaxResponse)
{
alert(ajaxResponse);
});
File: WebServices.js:
function Emision_ConsultarSeguro(requestData, okFunction, failFunction)
{
runAjax("Emision/emision.asmx/Consultar", request, okFunction, failFunction);
}
File: Common.js
function runAjax(url, request, okFunction, failFunction)
{
var dto = "{'request':" + JSON.stringify(request) + "}";
execAjax(url, dto, okFunction, failFunction);
}
File: Ajax.js
function execAjax(url, data, successFunction, errorFunction)
{
return $.ajax({
type: "POST",
url: GetUrl() + url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
successFunction(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown {
errorFunction(XMLHttpRequest, textStatus, errorThrown);
}
});
}
The Ajax calls is executed, but ajaxResponse is always undefined!!! Help please!
It looks like under WebServices.js, you should replace your request argument with requestData.
function Emision_ConsultarSeguro(requestData, okFunction, failFunction)
{
runAjax("Emision/emision.asmx/Consultar", requestData, okFunction, failFunction);
}
I use Backbone.js and jQuery 1.7 in my application and I have some problems in building collection. In collection I have the method, which should return some object. I do "return" in $.ajax(...) success() function.
In this case i receive "undefined" instead of expected object. I understand, that the problem is in the "return" - it make success() function return some value. But I need getDomainZones() method do a return. How can I do it?
window.DmnList = Backbone.Collection.extend({
model: DmnItem,
localStorage: new Store("hosting.WhoIs"),
destroyAll: function (options) {
while (this.models.length > 0) {
this.models[0].destroy(options);
}
},
getDomainZones: function(){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
success: function(data) {
console.log(data);
return data;//problem here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
});
"Where I should place return statement"
Nowhere. You can't return the result of an asynchronous AJAX request.
Any code that relies on the data, must be called inside the success callback.
One possibility is to have your getDomainZones method receive a function that will be called when the response is received.
getDomainZones: function( callback ){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
// success: callback, // alternative if there's no other work to do.
success: function(data) {
console.log(data);
callback( data ); // invoke the function received
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
So then you'd pass a function to getDomainZones, and when the response is received, getDomainZones will invoke the function you passed, passing it the data.
getDomainZones( function( d ) {
// do something with the data
console.log( d );
});
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;
})
can somebody please tell me, how can I display json data returning from the ajax call. I am new to this.
$.ajaxSetup({
cache: false,
timeout: 5000
});
//String.prototype.toJSON;
var the_object = {};
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + " value :" + obj[prop]);
}
return strArray.join();
}
//var ntid = "hhsh";
//document.writeln("httpRequest.responseText");
$(document).ready(function() {
$("button").ajaxStart(function() {
alert('Triggered ajaxStart handler.');
});
$("button").click(function() {
$.ajax({
type: "POST",
dataType: 'JSON',
//data: "{'ntid':'john'}",
//contentType: "application/json; charset=utf-8",
//processData: false,
url: "Testing.aspx/SendMessage",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(result, txtStatus, httpRequest) {
alert(txtStatus);
//$('#status').html(httpRequest.responseText);
//the_object = result;
$('#status').html(concatObject(result));
//$('#status').html(the_object);
//alert("hello" + concatObject(the_object));
//document.writeln(concatObject(the_object));
}
});
//alert(concatObject(the_object));
//$('#status').html(concatObject(the_object));
});
});
above is the js file. should i need to do something on asp file directly to display it. if yes, then how? please reply me soon. i m stuck here and unable to display data here. Its only diplaying this line:
toJSON value :function (key) { return this.valueOf(); }
Your result is most likely rooted with a property named d. Try modifying your success to use result.d;
This is usually a security measure that has to do with exploits which target a JSON collection with single root parent.