Sound of Speed
Sound of Speed

Reputation: 61

How to call a PHP function from a HTML button click?

Can someone help me with some javascript that will allow me to call a function when I click on a button?

I know this has been posted before, but every answer I have seen is too vague and I have been at this for 8 hours now :(

Please bear in mind I am a javascript beginner.

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <?php include 'connect.php'; ?>
    <table border cellpadding=5>
        <div>
            <tr>
                <th>Report</th>
                <th></th>
            </tr>
            <tr>
                <td>Students with highest scores</td>
                <td>
                    <button type= button>Generate report</button>
                </td>

        </div>
    </table>
    <?php   

        function highestScore()
        {
            $data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
                                 FROM Tests t 
                                 JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
                                 JOIN Students s ON sc.Students_id_Students = s.id_Students
                                 WHERE t.id_Tests = 1
                                 ORDER BY sc.Result DESC");
                    if(!$data)
                    {
                        die("Invalid Query: " . mysql_error());
                    }
            Print"<table border cellpadding=5>";
            while($info = mysql_fetch_array($data))
            {
            Print"<tr>";
            Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
            Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
            Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
            Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
            }
            Print "</table>";
        }

    ?>
</body>

I want to use the "Generate report" button I have made, to execute the "highestScore" function.

The function creates a table of values from a mySQL database.

There will eventually be more buttons which bring up different tables.

Any help is appreciated.

Upvotes: 0

Views: 27424

Answers (5)

Pravin Bhosale
Pravin Bhosale

Reputation: 1950

HTML and JavaScript run on the browser while PHP runs on the server. You have to write Ajax or java-script.In java-script you can call the php page and do your stuff in that page.And it would be the better approach.You can pass the variable also.I post a example here.

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function removeItem(oButton) 
{
var hello = "hello";
var world = "world";
window.location.href = "trytest.php?w1=" + hello + "&w2=" + world;//Your page location
}       
</script>
</head>
<body>
<form>
<h2>This is the test </h2>
<button type="show" onclick="removeItem(this); return false;">Test</button>
</body>
</html> 

Upvotes: 0

Yotam Omer
Yotam Omer

Reputation: 15366

HTML and Javascript run on the browser while PHP runs on the server. You will have to make another server call either by using AJAX or refreshing the page. Here's how to do it with AJAX without refreshing the page. ($.ajax docs)

  1. Create a new PHP page: query.php with the following code:

    <?php   
    
            $data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
                                 FROM Tests t 
                                 JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
                                 JOIN Students s ON sc.Students_id_Students = s.id_Students
                                 WHERE t.id_Tests = 1
                                 ORDER BY sc.Result DESC");
                    if(!$data)
                    {
                        die("Invalid Query: " . mysql_error());
                    }
            Print"<table border cellpadding=5>";
            while($info = mysql_fetch_array($data))
            {
            Print"<tr>";
            Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
            Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
            Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
            Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
            }
            Print "</table>";
    
    ?>
    
  2. Use the button's click event to run an ajax request: (Add the following script to your HTML page)

    $(function(){
        $('button').click(function(){
            $.ajax({
                url:'query.php',
                success:function(response){ alert(response); }
            }); // this will alert the code generated in example.php
        });
    });
    

Upvotes: 2

Cup of Java
Cup of Java

Reputation: 1808

So you want this all on one page so the first thing you need is form html tag wrapped around the button, I have named mine 'submit' and set the action to the page itself <?php echo $_SERVER['PHP_SELF']; ?>. When the button is clicked it will preform your php code

Script

<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php include 'connect.php'; ?>
<table border cellpadding=5>
    <div>
        <tr>
            <th>Report</th>
            <th></th>
        </tr>
        <tr>
            <td>Students with highest scores</td>
            <td>
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- Calls for the PHP script on the page-->
                <button type= button>Generate report</button>
                </form>
            </td>

    </div>
</table>
<?php  
    //Script that is called

    if(isset($_POST['submit'])){ //The ID of the form we used is 'submit' so when that is clicked it will execute this
    function highestScore()
    {
        $data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
                             FROM Tests t 
                             JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
                             JOIN Students s ON sc.Students_id_Students = s.id_Students
                             WHERE t.id_Tests = 1
                             ORDER BY sc.Result DESC");
                if(!$data)
                {
                    die("Invalid Query: " . mysql_error());
                }
        Print"<table border cellpadding=5>";
        while($info = mysql_fetch_array($data))
        {
        Print"<tr>";
        Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
        Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
        Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
        Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
        }
        Print "</table>";
    }


    highestScore(); //executes your function you created
    }

?>
</body>

Upvotes: 0

SteAp
SteAp

Reputation: 11999

A raw button doesn't make sense in pure HTML. It does just nothing - except looking like a button.

You may use it in conjunction with JavaScript:

<form action="input_button.htm">

    <textarea cols="20" rows="4" name="field1"></textarea>

    <input type="button" name="Text 1" value="Add some new Text"
      onclick="this.form. field1.value='Some new Text'">

</form>

This button executes a JavaScript through a click on it - and replaces the textarea named field1.

Upvotes: 1

weiver
weiver

Reputation: 226

Instead of using button, use a form with a submit button. Send a request by POST, and detect that in PHP using isset($_POST['report']) and then display your report.

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <?php include 'connect.php'; ?>
    <table border cellpadding=5>
        <div>
            <tr>
                <th>Report</th>
                <th></th>
            </tr>
            <tr>
                <td>Students with highest scores</td>
                <td>
            <form method="POST">
                            <input type="submit" name="report">Generate report</button>
            </form>
                </td>

        </div>
    </table>
    <?php   

        function highestScore()
        {
            $data = mysql_query("SELECT t.Test_name, s.Student_firstname, s.Student_surname, sc.Result
                                 FROM Tests t 
                                 JOIN Scores sc ON t.id_Tests = sc.Tests_id_Tests
                                 JOIN Students s ON sc.Students_id_Students = s.id_Students
                                 WHERE t.id_Tests = 1
                                 ORDER BY sc.Result DESC");
                    if(!$data)
                    {
                        die("Invalid Query: " . mysql_error());
                    }
            Print"<table border cellpadding=5>";
            while($info = mysql_fetch_array($data))
            {
            Print"<tr>";
            Print "<th>Test:</th> <td>" . $info['Test_name'] . "</td> ";
            Print "<th>First Name:</th> <td>" . $info['Student_firstname'] . "</td> ";
            Print "<th>Surname:</th> <td>" . $info['Student_surname'] . "</td> ";
            Print "<th>Result:</th> <td>" . $info['Result'] . "</td> ";
            }
            Print "</table>";
        }

    if (isset($_POST['report'])) {
        highestScore();
    }

    ?>
</body>

Upvotes: 1

Related Questions