I several HTML elements that initiate ajax when clicked. How can I check which element was clicked inside the ajaxComplete event?
I tried event.target but it returns the entire document.
$( document ).ajaxComplete(function( event, xhr, settings ) {
if ( settings.url.indexOf("somelink/hello") > -1) {
console.log("return here element that initiated ajax")
}
});
Note: The tricky part - I don't have access to the ajax request that is sent on click. I can't configure the code that makes the request. I can only check when the ajax is complete.
I first need to run the ajaxComplete event then check which element initiated ajax because I need to add some html to that element. For this reason I'm trying to check in the ajaxComplete event.
The $.ajaxComplete() handler is not an object-specific handler; you attach it to the document to be notified whenever any AJAX request completes. From the jQuery docs:
If you must differentiate between the requests, use the parameters passed to the handler. Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request.
So, since settings is a plain Object, you can extend it with a property that will then be passed to the handler, as you can see below with requestingObjectId. DEMO
var onComplete = function(event, jqXHR, ajaxOptions) {
alert("Requested with " + ajaxOptions.requestingObjectId);
};
var makeRequest = function() {
var id = $(this).attr('id');
$.ajax({
url: '/path/to/server',
data: { foo: 1 },
requestingObjectId: id
});
};
$('button').click(makeRequest);
$(document).ajaxComplete(onComplete);
Best and easiest way is to store the element in a global variable when you send the ajax call. Set it to the event.target.activeElement. Then in your ajaxComplete you can just access that var to change CSS etc.
Upon further consideration, if you use my solution you would have to limit it to one ajax request at a time. Otherwise a new ajax request would overwrite variable if the initial ajax request hadn't completed yet. I'd take Palpatime's answer.
An jQuery AjaxRequests is NOT send by an control itself. It is send by the code that the developer wrotes as event function onto this Dom element.
Means the best thing you can get is the callee of $.ajax() by overwriting and wrapping it. And only if the callee is not written in strict mode.
I would prefer to read the documentation of that framework who is building your controls or if it is built by another company/guy contact them.
As the element is not the direct caller of the $.ajax, I see no other way.
Related
I've been trying to execute an AJAX call inside an event handler function for about a day, trying lot of when(), then() and done() stuff and also to set async: false but I am still ending up with undefined errors. My code looks like this:
$('#id').on('itemMoved', function (event) {
console.log(event);
$.ajax({
type: "POST",
url: "create.php",
data: event
});
});
I need to pass the event object to create.php to do some server-side stuff. As console.log(event) is printing the object correctly, I guess the reason is the asynchronous behaviour of ajax - but have still no idea how to solve it.
Edit: First of all, sorry for not making it complete. Lack of knowledge makes it more difficult to decide what is relevant.
itemMoved is an event of jQuery UI Widget jxqkanban. It is triggered when a Kanbanitem is dragged and holds information about old and new column and itemdata (Documentation). I think AJAX is running before the objects content is completely resolved, causing
Uncaught TypeError: Cannot read property 'target' of undefined.
Thanks for your time.
Just been having a play in js fiddle link here.
https://jsfiddle.net/WillCodeForBeer/29kqpo58/1/
$("#click").click(function(event){
console.log(event)
data = {};
data.timestamp = event.timeStamp
$.post('/echo/js/?js=hello%20world!', { data : data } );
});
I'm not sure what error you are getting but when I tried to only send the event data I was getting a type error. After some reading, it turns out you cannot be sent the event object as
it contains HTML as it will reference the event target.
I would suggest something similar to the above code and extract the data you need out of the event object into another data object and post that.
NB. The post does not complete due to the url being a fake url. The triggering event is also different but the concept is the same.
let me know how you get on.
Here there is fiddle that maybe can be useful to you:
Fiddle
$('#id').on('click', function (event) {
$.post( "https://httpbin.org/post", event).
done(function( data ) {
console.log( "Data Loaded: " + data );
$( "#results" ).append( "Origin: "+ data.origin );
});
});
In Ajax, and in javascript, in general, is essential the concept of callback.
So in the example above the function inside done is executed only when the server responds.
Hi I am running an AJAX Post to my PHP url and when done I am returning a document.ready function with my appended jQuery page.
I want to make sure if I am doing this correctly when placing the function in the success part of my AJAX post. It will not work at the minute. Any help would be great?
function loadJobRequests() {
/ /AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/json-data-
jobrequests.php",
data: { userEmail: localStorage.getItem("email") },
cache: false,
success: function() {
$(document).ready(function(){
I just need to find out if i have to pass any parameters into the function at success and then same same parameter into document.ready. Thanks
Short answer: no, you shouldn't use $(document).ready(...) here. The function you put inside that is only executed at the moment the DOM is first "readied", shortly after page load - this will be long since past by the time your script has been loaded, executed, fired an Ajax call and then returned the response (all of which needs to happen before your success callback happens).
But the very reason that $(document).ready(...) doesn't work also means that you don't need it here. The only reason it's used is to make sure that any DOM elements you refer to (typically to attach event handlers to) actually exist and the point this code is executed. Since the "ready" event has long since fired by the time the Ajax response comes in, the DOM will accurately reflect the current content of the page, and you can safely do whatever you want to manipulate it.
So whatever function you were going to put inside there, just put directly in the success callback.
Using jQuery (v2.1.4), is there any difference between these two methods?
1) $.ajaxSetup(beforeSend)
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
}
});
2) $(document).ajaxSend
$(document).ajaxSend(function (event, jqXHR, settings) {
// whatever you need to do before
// any jQuery Ajax request is sent
});
Is there any reason to prefer one over the other?
Thanks!
From jQuery $.ajaxSetup() documentation:
All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().
The $.ajaxSetup() does something like this:
ajaxExtend(jQuery.ajaxSettings, target);
From $.ajaxSend() documentation:
Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.
And the jQuery source for $.ajaxSend():
function (fn) {
return this.on(type, fn);
}
So, basically the $(document).ajaxSend() adds an event listener to all the document where you can make any handler to execute anytime a jQuery Ajax call is about to be sent (the handler intercepts it, but XMLHttpRequest.readyState value is already 1 - "Opened").
This means that if $.ajax() is called with the global option set to false, the ajaxSend() method will not fire.
While on the $.ajaxSetup() you are in fact creating defaults for every single jQuery Ajax call's settings, and the callback defined through the beforeSend option will always be called (XMLHttpRequest.readyState value is 0 - "Unsent").
From JQuery's documentation:
There are two types of events:
Local Events
These are callbacks that you can subscribe to within the Ajax request
object, like so:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});
Global Events
These events are triggered on the document, calling any handlers which
may be listening. You can listen for these events like so:
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
Global events can be disabled for a particular Ajax request by passing in the global option, like so:
$.ajax({
url: "test.html",
global: false,
// ...
});
for more information
Both do very similar function , but it always depend on the need
There are some key points , on which you may focus
ajaxSend() method, must be attached to document only.
if $.ajax() is called with the global option set to false, the ajaxSend() method will not fire.
the beforeSend option will be called regardless of the type of request.
From the perspective of priority, you can use in such a manner, do all setup options in ajaxSend and for custom or specific ajax request override it with beforeSend in $.ajax().
HTML
<body>
<div><h2>Let AJAX change this text</h2></div>
<button id="btn1">Change Content</button>
<button id="btn2">Change Content Override</button>
</body>
JS
$(document).ajaxSend(function(e, xhr, opt){
$("div").append("<p>Requesting " + opt.url + "</p>");
});
$("#btn1").click(function(){
$("div").load("yourpage.html");
});
$("#btn2").click(function(){
$.ajax({
global: false,
beforeSend:function(){$("div").append("<p>Overriding</p>");}
});
$("div").load("yourpage.html");
});
LIVE http://jsfiddle.net/mailmerohit5/w8t44247/
Is there any way to intercept an ajax request being made via jquery, to insert additional variables into it?
I know that .ajaxStart() lets you register a callback which triggers an event whenever an ajax request begins, but what I'm looking for is a way to cancel that ajax request if it meets certain criteria (e.g url), insert some more variables into its content, and then submit it.
This is for a plugin for a 3rd party software whose own code can't be changed directly.
Edit: Seems like .ajaxSetup() lets you set some global variables related to ajaxRequests. If I registered a beforeSend function, would that function be able to cancel the request to make a different one on meeting certain criteria?
Figured it out, this was the code I used:
jQuery(document).ready(function()
{
var func = function(e, data)
{
//data.data is a string with &seperated values, e.g a=b&c=d&.. .
//Append additional variables to it and they'll be submitted with the request:
data.data += "&id=3&d=f&z=y";
return true;
};
jQuery.ajaxSetup( {beforeSend: func} );
jQuery.post('example.php', {a : 'b'}, 'json');
} );
To cancel the request, returning false from func seemed to work.
I'm unsure of the best practice for modifying the DOM based on an ajax response. I'll try to let the code do the talking because it's hard to explain.
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
var cb = $(this); // for the sake of discussion i need this variable to be in scope
$("form").ajaxSubmit({ dataType: "script" });
}
The server sends a response back, and the js gets eval'd and that means "cb" is out of scope.
What I've done so far is create a couple of helper functions:
var target = undefined;
function setTarget(val) {
target = val;
}
function getTarget() {
return target;
}
And that turns the first snippet of code into this:
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
setTarget($(this));
$("form").ajaxSubmit({ dataType: "script" });
}
Then on the server's response I call getTarget where I need to. This seems hackish... Any suggestions?
It's unclear what you're actually trying to do, but I feel like you want to be looking at the success parameter for that AJAX call. The success callback function should execute in parent scope and do what you're looking for.
See 'success' on this page in the jQuery docs.
So what you are trying to do is get the form to submit the content via ajax whenever the user checks/unchecks a checkbox? And because there are several checkboxes, you need to find out which one triggered the submit, so you can change its value to whatever is stored on the server?
If you submit the entire form everytime, why don't you reply with all the checkboxes values, and then change each and every one of them? If not, get the server to reply with the id and the value of the checkbox, then use jquery to find the checkbox with that ID and then change it's value.
How about:
jQuery(function($) {
// give it scope here so that the callback can modify it
var cb,
cbs = $('input[type="checkbox"]');
cbs.live('click', function {
// taking away var uses the most recent scope
cb = $(this);
// disable checkboxes until response comes back so other ones can't be made
cbs.attr('disabled', 'true'); // 'true' (html5) or 'disabled' (xhtml)
// unless you are using 'script' for something else, it's best to use
// a callback instead
$('form').ajaxSubmit({
success : function(response) {
// now you can modify cb here
cb.remove(); // or whatever you want
// and re-enable the checkboxes
cbs.removeAttr('disabled');
}
});
}
});