Maybe i get minuses for this question, but i have problems with success
and i really don't see differences between example of using success
from jQuery documentation:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
and my code:
$('#my_form').live('submit', function(){
var data = $("#form_for_item").serialize();
var url = '/something/add_something/' + $('#form_for_item').attr('name') + '/';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(){
alert('problem!')
},
dataType: 'json'
});
return false;
});
For more i can say that data is sent via post and save in my database, and for more than more i can say that when i have success: alert('problem!')
there is no problem.
What is wrong with my success
?
The problem is that this
in your AJAX callback is something entirely else than this
in your .live
callback, since this
changes dynamically with context. To get the right object, you need to save a reference to it:
.live('submit', function () {
var that = this;
...
success : function () {
$(that).addClass("done");
}
...
}
You're overlooking the most important aspect in the documented code:
context: document.body,
context
as it suggests, specifies the context of the callbacks - success
, error
, complete
.
So in the documented code's success block, $(this)
means $(document.body)
.
By default, the context is $.ajaxSettings
merged with the settings passed to .ajax()
and not a DOM object.
Another issue I see with your code is this:
var url = '/something/add_something/' + $('#form_for_item').attr('name') + '/';
You're using an absolute url (which doesn't resolve as it lacks FQDN) which is resulting in an error, hence your success never executes. To verify, add an error handler and see.
Your url ideally should be somthing like:
// relative path
var url = 'something/add_something/' + $('#form_for_item').attr('name') + '/';
or
// complete path
var url = 'http://domain.com/something/add_something/' + $('#form_for_item').attr('name') + '/';
Perhaps your server isn't returning JSON data. Usually you can leave it up to $.ajax
to figure out what sort of data the server is responding with by checking the Content-Type header and possibly other means. Try dropping the dataType
.
Also, using:
success: alert('problem!')
Gets you your alert
because that will be executed while the $.ajax
call's options object is being built and there won't be a success callback at all.