[php] Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.

The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).

Here is what I reach to:

In the test.php file:

<form action="test.php" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" onclick="test()" />
</form>

The PHP code [ test() function ] is in the same file also:

<?php
    function test() {
        echo $_POST["user"]; // Just an example of processing
    }
?>

However, I still getting a problem! Does anyone have an idea?

This question is related to php html forms post

The answer is


This is the better way that I use to create submit without loading in a form.

You can use some CSS to stylise the iframe the way you want.

A php result will be loaded into the iframe.

<form method="post" action="test.php" target="view">
  <input type="text" name="anyname" palceholder="Enter your name"/>
  <input type="submit" name="submit" value="submit"/>
  </form>
<iframe name="view" frameborder="0" style="width:100%">
  </iframe>

Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:

<?php
    function test() {
        echo $_POST["user"];
    }

    if (isset($_POST[])) { // If it is the first time, it does nothing
        test();
    }
?>

<form action="test.php" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" onclick="test()" />
</form>

You have a big misunderstanding of how the web works.

Basically, things happen this way:

  • User (well, the browser) requests test.php from your server
  • On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
  • The browser displays the form, the user can interact with it.
  • The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.

You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.

If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).


You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.

HTML

<form method = 'post' action = '' id = 'theForm'>
...
</form>

JavaScript

$(function() {
    $("#theForm").submit(function() {
        var data = "a=5&b=6&c=7";
        $.ajax({
            url: "path/to/php/file.php",
            data: data,
            success: function(html) {
                .. anything you want to do upon success here ..
                alert(html); // alert the output from the PHP Script
            }
        });
        return false;
    });
});

Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.

var data = "a=5&b=6&c=7";

If that is your data string, then the PHP script will see this as:

echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7

You, however, will need to construct the data from the form fields as they exist for your form, such as:

var data = "user=" + $("#user").val();

(You will need to tag each form field with an 'id', the above id is 'user'.)

After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.

...
success: function(html) {
    alert(html);
}
...

Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.

The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.

Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.

<?php
    function test() {
        header("Content-Type: text/xml");
        echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
    }
    if(isset($_GET["user"])){
        test();
    } else {
?><html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
            function do_ajax() {
                if(window.XMLHttpRequest){
                    xmlhttp=new XMLHttpRequest();
                } else {
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function(){
                    if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                        var xmlDoc = xmlhttp.responseXML;
                        data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
                        mydiv = document.getElementById("Test");
                        mydiv.appendChild(document.createTextNode(data));
                        mydiv.appendChild(document.createElement("br"));
                    }
                }
                xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
                xmlhttp.send();
            }
        </script>
    </head>
    <body>
        <form action="test.php" method="post">
            <input type="text" name="user" placeholder="enter a text" id="username"/>
            <input type="button" value="submit" onclick="do_ajax()" />
        </form>
        <div id="Test"></div>
    </body>
</html><?php } ?>

Use SAJAX or switch to JavaScript

Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh.


That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.

To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.


in case you don't want to use Ajax , and want your page to reload .

<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}    
?>

Take a look at this example:

<!DOCTYPE HTML> 
<html>
<head>
</head>
<body> 

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $name = test_input($_POST["name"]);
   $email = test_input($_POST["email"]);
   $website = test_input($_POST["website"]);
   $comment = test_input($_POST["comment"]);
   $gender = test_input($_POST["gender"]);
}

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   Name: <input type="text" name="name">
   <br><br>
   E-mail: <input type="text" name="email">
   <br><br>
   Website: <input type="text" name="website">
   <br><br>
   Comment: <textarea name="comment" rows="5" cols="40"></textarea>
   <br><br>
   Gender:
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time