Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery "Cannot read property 'defaultView' of undefined" error

Tags:

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?

like image 454
Pez Cuckow Avatar asked Oct 14 '10 18:10

Pez Cuckow


1 Answers

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().

like image 103
Nick Craver Avatar answered Oct 02 '22 16:10

Nick Craver