Reputation: 31
I have this following form:
<form class="friend_form" action="/friend" data-id="<?php echo $i;?>">
<input type="submit" value="no" name="hey"/>
</form>
and this following script:
$('.friend_form').on('submit', function(){
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
success: function(html)
{
console.log('foo'+$(this).attr('data-id'));
}
});
return false;
});
What I'm trying to do is to get the data-id attribute value but it returns the value undefined.
What's wrong with my code?
Upvotes: 0
Views: 11810
Reputation: 123749
You need to pass in the context to the success callback or just set up a variable in the method. this context inside the AJAX callback holds jqxhr object context and not the context of the element.
$('.friend_form').on('submit', function(){
var $this = $(this); //<-- Set up here.
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
success: function(html)
{
console.log('foo'+ $this.attr('data-id')); // access it using $this
}
});
return false;
});
You can also use $.proxy to pass in the context, but is not necessary here, but another option. Note this will change the context inside the call back altogether to the DOM element hence not desired.
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
success: $.proxy(function(html)
{
console.log('foo'+ $(this).attr('data-id')); // Now this here is the form element.
}, this)
});
Upvotes: 1
Reputation: 74410
'this' inside callback is not what you think it is:
$('.friend_form').on('submit', function(){
var self = this;
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
success: function(html)
{
console.log('foo'+$(self).attr('data-id'));
}
});
return false;
});
Or use a closure:
$('.friend_form').on('submit', function () {
(function (self) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
success: function (html) {
console.log('foo' + $(self).attr('data-id'));
}
});
})(this);
return false;
});
Or use ajax option context:
$('.friend_form').on('submit', function(){
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
context: this,
success: function(html)
{
console.log('foo'+$(this).attr('data-id'));
}
});
return false;
});
Upvotes: 2