Apparatus17
Apparatus17

Reputation: 39

Button for php function doesnt work after ajax call

I am attempting to add, or subtract a pts field in a database based on if you press a button and then update the content on the page, I also have the fields that the pts are being display in , on a timer with Ajax to auto-refresh.

I am using this script to call the page:

$(document).ready(function(){
        var timer, delay = 1000;                // 1 second(s) counted in milliseconds
        var Pts = '';                          //ID value of users answer
        var info = {'userPts': Pts};           //naming POST for php
        timer = setInterval(function(){
            $.ajax({
                url: "inc/ans.php",            //sends to ans page where php function updates DB
                type: "POST",
                data : info,                   //stuff being sent to php
                success:function(data)
                {
                    $("div #ans").html(data);  //Retrieves answers made by user
                }
            });
        }, delay);

My issue is when I make this call the only way currently to click the buttons is to manually refresh the entire page and then I am able to click the buttons and update the users pts value. I am able to do one or the other but not at the same time, I can have it where it auto-refreshes the content but I can’t have the button press complete the action. And I can have the buttons be able to be pressed but I can’t have the content auto-refresh.

The PHP functions to add and subtract are about the same they are like this:

    function addPoint($mysqli, $id)
    {
        $stmt = $mysqli->prepare('
        UPDATE tbl_user 
        SET user_pts = user_pts + 1
        WHERE user_id = ?');
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $rows = $stmt->affected_rows; 
        $stmt->close();
        if($rows == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Only difference between the two functions is the fact that its -1 or +1. Any ideas on why this happens? Is it the Ajax call this is interfering with the PHP function or vic. versa?

EDIT: This is the code that is being displayed to the instructor with the buttons

    function getScore_I($mysqli)
    {
        $stmt = $mysqli->prepare('
        SELECT user_name, user_pts, user_id
        FROM tbl_user');
        $stmt->execute();
        $stmt->bind_result($user, $pts, $id);
        $O ="";
        $x = 1;
        $O.="<table style=\"text-align:center;width: 100%\"><form action=".$_SERVER['PHP_SELF']." method=\"POST\">";
        while($stmt->fetch())
        {
            if($x%2)
            {
                $O.= "<tr style=\"text-align:center;width: 100%\">
                        <td>".$user."</td>
                        <td>
                            <button name=\"userIDmiunus\" type=\"submit\" value=\"".$id."\">-</button>
                        </td>
                        <td>".$pts."</td>

                        <td>
                            <button name=\"userIDplus\" type=\"submit\" value=\"".$id."\">+</button>
                        </td>
                    </tr>";
                $x++;
            }
            else
            {
                $O.= "<tr style=\"text-align:center;width: 100%\">
                        <td>".$user."</td>
                        <td>
                            <button name=\"userIDmiunus\" type=\"submit\" value=\"".$id."\">-</button>
                        </td>
                        <td>".$pts."</td>

                        <td>
                            <button name=\"userIDplus\" type=\"submit\" value=\"".$id."\">+</button>
                        </td>
                    </tr>";
                $x++;
            }
        }
        $O.= "</form></table>";
        // close statement
        $stmt->close();
        return $O;
    }

Upvotes: 0

Views: 103

Answers (1)

cssyphus
cssyphus

Reputation: 40106

Is it the case that the button elements are included in the code brought in via AJAX? If so, you need to use .on(), as in:

$(document).on('click', '.buttonClassName', function(){
    //do your click code here
});

Reviewing your code, it looks like you are just doing a .load(), which is a shortcut version of $.ajax(). I also prefer using $.ajax() in all circumstances - use $.load(), $.get() and $.post() are not as well structured as the full $.ajax()

When the new data is injected into the DOM via .html(), any controls are not bound to javascript code, since the binding code was run prior to their injection. Two solutions: you can also inject some additional javascript and recreate those bindings -- which means much duplicate code in the DOM -- or you can use .on() which works for the elements currently in the DOM, but also for all future elements injected into the DOM that have that specific class or ID or whatever jQuery selector you use.

Another possibility could be that you need to use AJAX to access your PHP function. See this post and the post it references/links to regarding AJAX. Check out the examples.


Yes, you can call another AJAX function inside the .on(), and that is probably what you need to do.

Recall that AJAX is just a method for running PHP code after the web page has been rendered, and without refreshing/leaving the current page.

Code could look something like this:

$(document).on('click','.buttonClass', function(){
    var Pts = '';                          //ID value of users answer
    var uid = $('hidden_input_where_you_stored_userID').val();
    var info = {'userID': uid, 'userPts': Pts};           //naming POST for php
    $.ajax({
        url: "inc/another_file.php",
        type: "POST",
        data : info,
        success: function(data) {
            //whatever you need to do after updating point score
        }
    });
});

another_file.php:

<?php
    $id =  $_POST['userID'];
    $pts = $_POST['userPts']; 
    //do your DB update

Upvotes: 2

Related Questions