I have this HTML
<li>
<a rel="1" href="/jobwall/job/1">
<img src="http://lcl.moovjob.com/media/images/employers/simonainleydotinfo.jpg">
</a>
</li>
and I have this javascript
$('ul#jobs li a').mouseenter(function(){
$(this).parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$(this).parent($(this)).addClass('added');
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});
On mouse enter I am wanting to add a class the li that holds the a that has the mouseenter event on it, however I cannot get it to add the class on mouseenter.
You have two calls to .addClass(). Which one are you talking about?
The first one should work.
The second one will not because the value of this has changed inside the success: callback. You can cache it in a variable and reference it inside.
$('ul#jobs li a').mouseenter(function(){
// cache the parent here, because "this" will have different
// meaning in the callback
var $parent = $(this).parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
// Inside here, "this" no longer references the DOM element
$parent.addClass('added'); // reference the parent you cached
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});
Another option would be to set the context: property of the AJAX call.
$.ajax({
type: 'POST',
context: this, // set the context to the current "this" for the callback
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$(this).parent().addClass('added');
}
});
And another option would be to use $.proxy() to retain the value of this.
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success: $.proxy( function(html) { // Have $.proxy return a function
$(this).parent().addClass('added'); // with the proper "this"
}, this )
});
Your this inside of the success event will be the window not the anchor element.
Take a ref of the anchor outside the .ajax call and use it in the success event.
$('ul#jobs li a').mouseenter(function(){
var $this = $(this);
$this.parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$this.parent().addClass('added');
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});
You're mis-calling the parent method.
Change it to
$(this).parent()
Try
$(this).closest('li').addClass('added');
Or just
$(this).parent().addClass('added');
Related
I'm making an $.ajax call, and the following code does not work as intended. The alert results in 'undefined'
$(document).ready( function {
$(".elem").on("click", function(e) {
e.preventDefault();
$.ajax( {
url: 'index.php',
data: {
'action': 'something'
},
success: function() {
alert($(this).data("foobar"));
}
});
});
)};
However, I was able to get it working by adding an alias to $(this) before entering the ajax function.
$(document).ready( function {
$(".elem").on("click", function(e) {
var old_this = $(this);
e.preventDefault();
$.ajax( {
url: 'index.php',
data: {
'action': 'something'
},
success: function() {
alert(old_this.data("foobar"));
}
});
});
)};
I can't assign unique IDs to the element being clicked, so accessing it via $("#id") isn't an option.
Is there a more standardized approach to accessing the $(this) that existed before entering the success function or does this way work just fine?
The way that you have it is just fine. By default this in jQuery ajax callbacks is the ajax settings object (you can set via $.ajaxSettings). $.ajax also has a context property that you can set:
$.ajax({
url: url,
data: data,
context: this,
success: success
});
Then you could use $(this) as expected, but personally I find the reassignment of this easier to understand. You may want to pick a better variable name than old_this, though.
I want to target some div in a class, i would use $(this), but that doesn't doesnt work since im calling that class from another function.
Sample Code.
$(document).on('click', '.Player', function(e){
var id = $(this).find('.Song_Id').html();
$.ajax({
type:"POST",
data: {data:id},
complete: function(){
$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png')
},
url:"php/player/get_song.php"
}).done(function(f){
$('#Song_info').html(f)
});
})
From above, the following is the line i don't know how to impliment.
$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png'),
it suppose to target class ".player", but not the entire class, only the element that was clicked.
Thanks.
You can store $(this) inside another variable and use this variable inside your function.
$(document).on('click', '.Player', function (e) {
var id = $(this).find('.Song_Id').html(),
that = $(this);
$.ajax({
type: "POST",
data: {
data: id
},
complete: function () {
that.attr('src', '../images/appicons/2/16x16/refresh - Red.png')
},
url: "php/player/get_song.php"
}).done(function (f) {
$('#Song_info').html(f)
});
})
When the ajax callback is executed, by default the execution context of the callback method is set to the ajax settings object.
You can use the context option of $.ajax() to pass a custom execution context
$(document).on('click', '.Player', function (e) {
var id = $(this).find('.Song_Id').html();
$.ajax({
type: "POST",
data: {
data: id
},
//use context to set the execution context of the callback
context: this,
complete: function () {
$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png')
},
url: "php/player/get_song.php"
}).done(function (f) {
$('#Song_info').html(f)
});
})
context:
This object will be made the context of all Ajax-related callbacks. By
default, the context is an object that represents the ajax settings
used in the call ($.ajaxSettings merged with the settings passed to
$.ajax). For example, specifying a DOM element as the context will
make that the context for the complete callback of a request
I have the following javascript, I don't want this mousedown function to fire if the user is clicking on a delete div inside the .field_trip_mini_div. The delete div id is 'delete'. What code should I add so the mouse down function does not procede if the user clicked on the delete div? I tried changing the first line to
$(".field_trip_mini_div :not('#delete')").live({
But that didn't work. Is there a way I could stop it on the second line of code?
$(".field_trip_mini_div").live({
mousedown: function(){
$.ajax({
type: "POST",
url: "/field_trips/"+selected_field_trip_id+"/reload_div",
data: {id: selected_field_trip_id},
success: function(response)
{
$('#selected_fieldTrip_div').html(response);
}
});
});
Edit: I used # originally, thank you for the answers but it was a Stack Overflow input error.
Is delete an element inside field_trip_mini_div? If so you can check the id of the target of the clicked element using e.target:
$(".field_trip_mini_div").live({
mousedown: function(e){
if ($(e.target).attr("id")!= "delete") // This line right here
{
$.ajax({
type: "POST",
url: "/field_trips/"+selected_field_trip_id+"/reload_div",
data: {id: selected_field_trip_id},
success: function(response)
{
$('#selected_fieldTrip_div').html(response);
}
});
}
});
Some info on events and the event object: http://www.w3schools.com/jsref/dom_obj_event.asp
Use this:
$(".field_trip_mini_div :not('#delete')").on({
Note: Don't use "live" as it is deprecated; use "on" instead.
As delete is id use #, I suggest you to use on as live is deprecated.
$(".field_trip_mini_div :not('#delete')").live({
or you can skip the code when delete is clicked
$(".field_trip_mini_div").live({
mousedown: function(evt){
if (evt.target.id == "delete")
return;
$.ajax({
type: "POST",
url: "/field_trips/"+selected_field_trip_id+"/reload_div",
data: {id: selected_field_trip_id},
success: function(response)
{
$('#selected_fieldTrip_div').html(response);
}
});
});
I have a function:
$(".delete").click(function() {
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$(this).parent().parent().remove();
alert("hi");
}
});
});
I have a problem when I delete the parent object. It just does not disappear. I tried to hide - did not help.
Alert is called normal.
How to solve?
Sorry for bad English.
You're inside another function with another this value by default. Pass the this value from the outer function with the $.ajax function as follows:
$.ajax({
context: this,
...
Because the this in the ajax success callback function is different from the click callback function. You could cache it to a local variable or use the $.ajax()'s context option.
$(".delete").click(function () {
var $this = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $this.attr("title"),
success: function () {
$this.parent().parent().remove();
alert("hi");
}
});
});
Have you tried setting the context: this, parameter in the ajax function.
When the success handler fires, the value of this won't be the same as it was before hand.
See here fore more: http://api.jquery.com/jQuery.ajax/
Try this:
$(".delete").click(function() {
$object = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$object.parent().parent().remove();
alert("hi");
}
});
});
How can I select parent element of $.ajax, or parent element of the element that triggered $.ajax. I need some kind of reference so I can apply result data to it:
var a = $a.val();
var b = $b.val();
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { a: a, b: b },
success: function (data) {
var values = data.values,
$elements = $();
for (i = 0; i < 142; i++) {
$elements = $elements.add($("<div class='single'>").css('height', values[i]).css('margin-top', 26 - valuesG[i]));
}
//Here it should reference $(this).parent().parent().. something
//and not :last, because there are many .second elems...
//not only :last is being changed?
$elements.appendTo($(".second:last"));
$(".second:last").children(".single").addClass("ui-selected");
},
traditional: true
});
$(this).parent() in ajax success function returns jQuery()
Any ideas?
Use the context option:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
jQuery Reference
because by default ajax call is asynch and so when you do $(this) inside success the this reference to ajax api and so $(this).parent() reference to jQuery().
to avoid this save the element reference in a variable before ajax call starts to use inside success.
target_element = $(this);
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { a: a, b: b },
success: function (data) {
// ....................
target_element.parent()
...............................
Put the call to ajax in a function, and pass an element argument to the function?
function doAjax(triggerElement)
{
$.ajax({
url: whatever,
context: triggerElement,
success : function (content) { $(this).html(content); }
});
}
$(function () {
$('#triggerElementId').click(function () { doAjax(this); });
});