Prince Brucex
Prince Brucex

Reputation: 569

Display PHP output via Ajax under the button that was clicked--Not Working

I am trying to display PHP output via Ajax under the button that was clicked but my code is not working.

output.php

<?php
    if(isset($_POST['click_me'])){
        echo "<p>Something</p>";
    }
?>

HTML

<button class="same-class" name = "click_me" type = "button">Button 1</button>
<p> To display below me</p>

<button class="same-class" type = "button">Button 2</button>
<p> To display below me too</p>

Jquery

$(function(){
    $('.same-class').click(function(){
        $(this).next('p').append('Hello'); //Works
        $.ajax({
            url: 'output.php',
            type: 'POST',
            data: {click_me: 1},
            success:function(response){
                $(this).next('p').append(response); //Does not work--does not do anything, does not produce errors either.

                console.log(response); // works
                $('same-class').append(response); //works but all buttons get appended
                alert(response); //works
            }

        });

    });
});

It appears that the position of $(this) inside the success: function(response){} is the cause of the problem. The code does not produce errors either. A lot of search I have made on SO and else suggests that this should work. More than 2 hours now, I can't figure out why it does not work.

Upvotes: 2

Views: 93

Answers (1)

QnARails
QnARails

Reputation: 377

Your guess is correct. The $(this) in your callback function refers to the object you pass in. So you need to save the refence to the button before you make an ajax call.Update your javascript to below:

$(function(){
    $('.same-class').click(function(){
        $(this).next('p').append('Hello'); //Works
        //save a reference to the button clicked.
        var btn = $(this);

        $.ajax({
            url: 'output.php',
            type: 'POST',
            data: {click_me: 1},
            success:function(response){
               //use the button reference from above.
               btn.next('p').append(response); //Does not work--does not do anything, does not produce errors either.

                console.log(response); // works
                $('same-class').append(response); //works but all buttons get appended
                alert(response); //works
            }

        });

    });
});

Upvotes: 3

Related Questions