0

I have a jQuery code like this:

$("#erase").click(function(){
        $("#erase").attr("disabled", "disabled"); // Prevent double-clicking
        $(this).html("Erasing...");
        $.post("erase.php", {target: $("#target").val(), criteria: $("#criteria").val()}, function(data){
            $(this).html(data); // Change the button's caption to whatever erase.php echoes.
            setTimeout(function(){
                window.location.href = "index.php";
            }, 3000);
        });

The target and criteria are both HTML input tags and the button is declared with the button tag. I was expecting these would happen when user clicks the button:

  1. Button will be greyed out and its text will say 'Erasing...'
  2. erase.php will be called via AJAX. erase.php will delete a row from a database, and takes several seconds to complete.
  3. When the AJAX call is completed, the button text will be the output of erase.php. It will be either "Success" or "Failure"
  4. After 3 seconds, user will be brought back to home page.

But in my case, step 3 fails. The button gets stuck in 'Erasing....' (The request does complete, however.)


Side note: I can't really think of a better title for this question. If you can come up with one for me. Please let me know in the comments. I'd appreciate it.

4
  • Any error messages in console? Commented Oct 8, 2014 at 3:50
  • @Gowri There is no error in the console. Commented Oct 8, 2014 at 3:52
  • provide alert message to check response. alert(data); before $(this).html(data); Commented Oct 8, 2014 at 3:54
  • console.log(this); Commented Oct 8, 2014 at 4:01

1 Answer 1

5

$(this) inside of $.post is not the one that you had before. Try this way

$("#erase").click(function(){
    $("#erase").attr("disabled", "disabled"); // Prevent double-clicking
    $(this).html("Erasing...");
    $this = $(this);
    $.post("erase.php", {target: $("#target").val(),
           criteria: $("#criteria").val()}, function(data){
            $this.html(data); 
            setTimeout(function(){
                window.location.href = "index.php";
            }, 3000);
        });
Sign up to request clarification or add additional context in comments.

1 Comment

Cheery is correct. The "this" that you are trying referencing inside the callback function is out of scope. Once inside the new function, I believe what you are referencing by "this" is the function itself - which in JS is an object. In cheery's example you are creating a new variable that is accessible lower in the scope. In short, that this ain't what this used to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.