I have some ajax queries that create & manipulate (external) DOM elements during different stages of the AJAX query (beforeSend, success, failure, complete). Multiple queries can be fired while others are still processing, and I'm wondering how to identify the DOM elements for each query to trigger the events for the correct one.
So, does jQuery .ajax provide access to a unique query identifier that I can parse into an ID for each respective DOM element?
$.ajax({
UNIQUE_ID_NEEDED_HERE = ??? # Need to get unique identifier for this AJAX query
url: '/my/query',
data: my_data,
dataType: "json",
beforeSend: function (response) {
$('#ajax_messages').append('<div class="loadingStatus" id="' + UNIQUE_ID_NEEDED_HERE + '">Re-ordering tasks</div>');
},
success: (message, text, response) {
$(UNIQUE_ID_NEEDED_HERE).attr('class', 'successfulStatus');
$(UNIQUE_ID_NEEDED_HERE).html('Tasks re-ordered');
}
});
If not, any alternative ideas appreciated.
What is AJAX? AJAX = Asynchronous JavaScript and XML. In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page. Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.
get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler. $(selector). load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).
The dataType option specifies the type of response data, in this case it is JSON. The timeout parameter specifies request timeout in milliseconds. We have also specified callback functions for error and success. The ajax() method returns an object of jQuery XMLHttpRequest.
Have you tried something like this?
var constructRequest = (function() {
var startNumber = 0;
return function() {
var local = "request_id_"+(++startNumber);
$.ajax({
url: "someurl.php",
cache: false,
success: function(html){
/**
* Every time on success callback
* you will have unique local variable
* like this:
* request_id_1, request_id_2, request_id_3
* and so on.
***/
alert(local);
}
});
}
})();
$(document).ready(function() {
constructRequest();
constructRequest();
});
If I understand your purpose there's really no need to do this. All you need to do is create a standard "loading..." div template and clone it. store the clone in a variable and write it to the appropriate location in your document. When the AJAX success method fires it will do so inside the scope where it was created meaning you still have access to the same clone and can call any appropriate methods necessary on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With