tags:

views:

71

answers:

1

I am using jQuery to post a form field to a PHP file that simply returns 1/0 depending on whether it worked or not...

Extract of the code:

$.ajax({
    url: "ajax/save_text.php", //Relative?!?
    //PHP Script
    type: "POST",
    //Use post
    data: 'test=' + $(this).val(),
    datatype: 'text',
    //Pass value       
    cache: false,
    //Do not cache the page
    success: function(html) {
        if (html == 1) {
            $(this).hide().siblings('span').html($(this).value).show();
                    alert("awesome!");
        } else alert('It didn\'t work!');
    },
    //Error
    error: function() {
        alert("Another type of error");
    }
});

However everytime it is successful (html == 1) the console throws up the error "Uncaught TypeError: Cannot read property 'defaultView' of undefined" and the alert never happens...?

Google doesn't seem to have much info on this error and jQuery, who knows the cause?

+2  A: 

It's because this isn't what you were dealing with before, it's now tha ajax jQuery object, add the context option of $.ajax() like this:

$.ajax({
  context: this,
  url: "ajax/save_text.php",
  ...

This way this inside your callbacks refers to the same this as when you're calling $.ajax(). Alternatively, just hold onto a reference to this in a separate variable.

Also, you'll need to adjust $(this).value, you probably meant this.value or $(this).val().

Nick Craver
Many thanks, silly error, I promise I'm getting better :-)
Pez Cuckow
@Pez - not silly at all, I think it's rather counter-intuitive as well that this isn't the *default* context behavior.
Nick Craver
Yeah, this just bit me, too, after a bit of refactoring. Thanks for the answer. :)
Bombe