Apparatus17
Apparatus17

Reputation: 39

Ajax request with PHP on MySQL DB

what my goal is to use AJAX to call my php function:

function getAns($mysqli)
{
    $stmt = $mysqli->prepare('
    SELECT `user_id`,`user_name`, `user_ans`
    FROM `tbl_user`
    WHERE `user_ans` != ""');
    $stmt->execute();
    $stmt->bind_result($id, $user, $ans);
    $O ="";
    $x = 1;
    $O.="<table><form action=\"#\" method=\"POST\">";
    while($stmt->fetch())
    {
        if($x%2)
        {
            $O.= "<tr>
                    <td>".$user."</td><td>".$ans."</td><td><input id=".$id." type=\"submit\" name=\"pts\" href=\"#\" value=\"+\"></td>
                </tr>";
            $x++;
        }
        else
        {
            $O.= "<tr>
                    <td>".$user."</td><td>".$ans."</td><td><input id=".$id." type=\"submit\" name=\"pts\" href=\"#\" value=\"+\"></td>
                </tr>";
            $x++;
        }
    }
    $O.= "</form></table>";
    // close statement
    $stmt->close();
    return $O;
}

at a set time interval,say every 5 seconds, using AJAX/jQuery. I am trying to have an answer section, which is in a div, auto grab things from my database and echo them onto the page.

My HTMLthat i was trying to have them put into looks like this:

 <div id="ans" class="box3"><!--PHP Students answers -->
    <form id="ans" action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
        <?php echo getAns($mysqli);?>
    </form>
</div>

I understand a little bit how it works but I don't understand the code it takes to get there. I am new to JavaScript/jQuery/AJAX but I am trying to use more of it in my code, so if anyone could elaborate it would be much appreciated, thanks!

Upvotes: 0

Views: 113

Answers (2)

Zakaria M. Jawas
Zakaria M. Jawas

Reputation: 477

You can use ajax to call a php file that includes your php code it will execute it in the server then it will returns the result back to you

$.ajax({
        url:"your_php_file_path.php",
        success: function(result){
               //result is a variable that stores the value sent back from your php 
              // in your case $O
        }
 });

You can put this code in a js function, finally you will have to include Jquery library so you can use ajax

Upvotes: 0

vijay rami
vijay rami

Reputation: 535

with this function you can run ajax after every 5 minutes. You just need to pass user id value in ID variable, which will fetch all answer of that user after every 5 minutes.

And run your sql query in get_data.php file.

$(document).ready(function(){
var timer, delay = 300000; //5 minutes counted in milliseconds.
var ID = $( "td :submit" ).val();
var info = 'userID=' + ID ;
timer = setInterval(function(){
   $.ajax({
            url: "get_data.php",            
            type: "POST",
            data: info,
            success:function(data){
                $("#ans").html(data);
            }
            });
}, delay);
});

Upvotes: 2

Related Questions