PHP and Live Data Input
PHP has many great features lending to it's secure nature, however, it lacks any native ability to interact with stored data live (or, put another way without loading the entire page again). This is due to PHP's nature as a server-side interpreted language which causes it to run once before the webpage is displayed. No PHP code will run again unless a new webpage is requested. While this may not seem like a big deal for most sites this paradigm does not allow for any verification or processing of user input with live feedback.
Consider a site that needs to present a menu based on user input. It would be rather disruptive to reload the page every time a character is entered, or an option is selected.
Unfortunately native PHP code has no way to do, so an interim language is needed to call PHP code to be run again whenever certain events are triggered on a webpage. Fortunately JavaScript is very good at handling many events on webpages and with a very popular library JQuery we can use Ajax, a function that can call other pages behind the scenes and pass data back to our page without reloading it!
Now for some code...
I will provide some instructions on how to add this functionality to an existing webpage that uses PHP and stores its data in a database.
Download the latest JQuery library (link below) and save the file among the source files for your webpage.
NOTE: I recommend having a sub-folder in your site to separate your site files. In this case JavaScript files, .js extension, should be placed in a "js" folder.
https://code.jquery.com/jquery-3.6.3.js (Latest as of Feb-21-2023)
Create a new, empty, JavaScript file and reference both the JQuery library and your new .js file in the last two lines of the main page <body> section. It should look like the following.
<?php
/*Your PHP code here*/
?>
<html>
</body>
//Your HTML code here
<script src="js/jquery-3.6.3.js"></script>
<script src="js/script.js"></script>
</body>
</html>
--> The JQuery file provides the code for Ajax to function. This is the mechanism that we are going to use to silently pass data to a different PHP page that will not be displayed for the user.
--> The script.js file is where we will create our custom function that is called by the JavaScript event handler, this in turn calls the Ajax function and specifies its parameters so it behaves how we need it to for our test.
Below is a diagram on how this interaction works.
Locate the element of your webpage that you want to collect user input and add the following JavaScript event handler(s) appropriate for that object.
Below is an example of HTML code for a text box where I want to gather input. To do this I need to have JavaScript trigger on specific events, or actions, associated with the text box that can occur related to the data I am looking for. To provide some contrast, triggering on "mouseover" wouldn't be very helpful, however, keyboard actions would.
NOTE: For keyboard input the only event I strongly recommended is "onchange" the others are extras to ensure no possible input is missed.
<input type='text' name="text" onchange="unsavedTaskText(value);" onkeypress="this.onchange(value);" onpaste="this.onchange(value);" oninput="this.onchange(value);"/>
Now in the JavaScript file that was newly created add the following function.
function unsavedInput(inputDataVariable) {
$.ajax({
url: './Silent_Page_Gathering_Input.php',
type: 'POST',
data: {ObjectVariableName: inputDataVariable},
success: function(result){
//This Is Empty on purpose.
}
});
return false;
}
Now that we have a connection in place between our user input and the JavaScript trigger for Ajax lets better understand some of the parameters at play.
url: A 'String' input that specifies the webpage that you want to call when this event is triggered. This can be a page on your site, or any other website. If it is a page on your server remember its path is relative to the page you are calling this function from. In my example above the page "Silent_Page_Gathering_Input.php" is in the same directory as the page calling it so "./" will reference the current folder.
type: A 'String' that specifies the the call used to pass data to the page specified in the 'url:' field. This variable name can also be method: I recommend 'POST' as is the best way to pass inputs. Other options are 'GET' and 'PUT'.
data: Can accept a PlainObject, String, or Array. All inputs will be converted to a string unless the processData: false variable is included in the settings and set to false.
success: is a function that is called if the requests succeeds. It can receive any input back from the initial Ajax request that can be formatted according to the dataType parameter specified in a different setting not shown above.
return false; is required so the requesting webpage is not refreshed. If you want this to happen leave this out.
NOTE: This example is designed to silently take user input and request a separate webpage which performs an action. If you needed to receive data back, or wanted a user interaction the "success" function will need to be filled in.
Now that we have handed data to the page Silent_Page_Gathering_Input.php it can parse the POST array for the data from the input field by reading the variable $_POST['ObjectVariableName']. Every time the input above is changed this Ajax call is triggered passing a new variable to the Silent_Page_Gathering_Input.php page.
For a testing environment preforming repeated Ajax calls like this only serves to demonstrate the capability. In a real-world site you would want to try and limit the Ajax calls as much as possible. This can be done by waiting for a certain number of characters, or a specific type of character to be entered before calling the Ajax function. Another option would be to wait for a user to click a button that would signal that they are done providing input.
The Ajax method is used on many webpages to verify user input, or to provide feedback from the server when a page cannot, or should not be reloaded. This is often true of forms, or other complicated webpages where it isn't reasonable to reload them every time.
I hope this helps someone figure out a way to do something neat with their own webpage.
References:
https://api.jquery.com/Jquery.ajax/ : This is the documentation that lists all variables for Ajax and provides some examples for their use.
https://stackoverflow.com/questions/18722028/sending-data-to-database-using-jquery-ajax : This provides a real-world example on when to use Ajax and how it can be called.
https://riptutorial.com/ajax : This site provides a ton of information on Ajax (almost too much) but demonstrates how to pass it data, then how to receive that data back.
https://netbeans.apache.org/kb/docs/php/ajax-quickstart.html : This site provides some nice high-level views on how Ajax works. Some of the technical information is a little outdated or too specific to be generally used.