emma
emma

Reputation: 759

Ajax execute php without refresh - how to set variables?

I have a very small php script which in which I have a few buttons and no form. When I press one button, I want a small php script to be executed based on the id that I'm trying to send using ajax.

Those buttons look like this:

<button onclick="deleteTask()" class="task" data-id="1">Task 1</button>
<button onclick="deleteTask()" class="task" data-id="2">Task 3</button>
<button onclick="deleteTask()" class="task" data-id="3">Task 4</button>
...

And I have this ajax function:

function deleteTask() {
    var id=$(this).data("id");
    var dataString='id='+ id;

    $.ajax({
        type: "POST",
        url: "test.php",
        data: dataString,
        cache: false,
        success:function(html) {
            alert(html);
        }
    });
}

The PHP script that is executed is just a test:

$id = $_POST['id'];
echo "Response: " . $id;

And the result is that alert box with a response of:

Response: undefined

What I want is to get that data-id of the button that was pressed as a response. If I press button 1 with data-id="1" I want to get a response of "1".

Upvotes: 1

Views: 65

Answers (2)

PajuranCodes
PajuranCodes

Reputation: 471

As @Andrew correctly said, $(this) is the window object.

So, in order to be able to reference the button object inside the function, you must pass it as function argument, e.g. as this in each function call:

<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function deleteTask(button) {
        var id = $(button).data("id");

        $.ajax({
            type: "POST",
            url: "test.php",
            data: {
                'id': id
            },
            cache: false,
            success: function (html) {
                alert(html);
            }
        });
    }
</script>

<button type="button" id="button1" name="button1" onclick="deleteTask(this);" class="task" data-id="1">Task 1</button>
<button type="button" id="button2" name="button2" onclick="deleteTask(this);" class="task" data-id="2">Task 3</button>
<button type="button" id="button3" name="button3" onclick="deleteTask(this);" class="task" data-id="3">Task 4</button>

Upvotes: 2

Andrew Chart
Andrew Chart

Reputation: 653

In this context, $(this) is the window object.

You may be thinking of using $(this) off the back of a jQuery event handler. When you do something like $('#myElement').click(function() {...});, $(this) will represent the element that has been clicked.

Is there a reason you cannot do something like this?

<button onclick="deleteTask(1)">Task 1</button>
<button onclick="deleteTask(3)">Task 3</button>

<script>
function deleteTask(id) {
    var dataString='id='+ id;

    ...
}
</script>

Upvotes: 1

Related Questions