I want to consolidate my PHP files into a common class file, but I am not sure how to call the function instead of the .php page. How can I call sendEmail() in the form section of my HTML page?
HMTL
<form action="form_class.php" id="frmAirport" method="post">
Full Name: <span style="white-space: pre;">
</span><input name="name" type="text" /><br /><br />
Email Address: <input name="email" type="text" /><br /><br />
Subject: <span style="white-space: pre;">
</span><input name="subject" type="text" /><br /><br />
<textarea id="txtComments" cols="30" rows="10">Comments</textarea><br />
<input type="submit" value="Send" />
</form>
<?php
function addPerson() {
//do stuff here
}
function sendEmail() {
//do some stuff here
}
?>
You can't call PHP functions directly. However, if the php file is formatted how you displayed here with only two functions you could pass a flag in as a POST field and have a logic block determine which function call based on that flag. It's not ideal but it would work for your purposes. However, this would force the page to refresh and you would probably have to load a different page after the function returns so you may want to simply implement this as an ajax call to avoid the page refresh.
Edit based on your comment (Using jQuery Ajax):
I am using the .ajax() jQuery function. My intentions create one php file that contains multiple functions for different html forms. – tmhenson
Well in this case, you can have your file contain the logic block to "route" the request to the right function and finally return the result.
I'll try to provide an option for what you want to do based on some simple jQuery. Say you have something like this:
Java Script:
$("#button1").click(function(e){
e.preventDefault(); // prevents submit event if button is a submit
ajax_route('ap');
});
$("#button2").click(function(e){
e.preventDefault(); // prevents submit event if button is a submit
ajax_route('se');
});
function ajax_route(action_requested){
$.post("ajax_handler.php", {action : action_requested}, function(data){
if (data.length>0){
alert("Hoorah! Completed the action requested: "+action_requested);
}
})
}
PHP (inside ajax_handler.php)
<?php
// make sure u have an action to take
if(isset($_POST['action'])
switch($_POST['action']){
case 'ap': addPerson(); break;
case 'se': sendEmail(); break;
default: break;
}
}
function addPerson() {
//do stuff here
}
function sendEmail() {
//do some stuff here
}
?>
You CAN'T. PHP runs on the server only. You can use a javascript AJAX call to invoke a php script on the server, or use a regular form submission, but directly invoking a particular PHP function from client-side html? not possible.
I am not sure if I uderstand right, but to call function/method you can use hidden input:
<!-- form -->
<input type="hidden" name="action" value="sendEmail" />
// handle file
<?php
$actionObject = new Actions();
if (method_exists($actionObject, $_POST['action'])) {
$actionObject->{$_POST['action']};
}
?>
AddPerson and sendEmail doesn't sounds they should be method of one class. Try to use classes only with method witch are related. To call method, you can define it as static, or you must make instance of class and then call method.
Related
I'm currently trying to add a debug page to my website. This page is simply dedicated to running some of the tasks done by my plugin and outputting some results on the same page.
I currently have a separate page in my Wordpress admin, this page contains a form and button that should be linked to a function that will do various steps and then return a value that must be printed on that page.
Here's the current code for the page and button :
function actu_admin_menu_option()
{
add_menu_page('Scripts', 'Sahar actus plugin', 'manage_options', 'actu-admin-menu', 'actu_scripts_page', '', 200);
}
add_action('admin_menu', 'actu_admin_menu_option');
// HTML page of the plugin
function actu_scripts_page()
{
?>
<div class="wrap">
<h2>Sahar actus plugin</h2>
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
</div>
<?php
}
function start_test()
{
return ("test started!");
}
add_action( 'admin_post_start_test', 'start_test' );
What I would like is for example to run the following function when clicking on the button and then outputting the returned value on the page.
function start_test()
{
return("test started!");
}
So when I press the button I want "test started!" to be printed on the page, currently clicking on the button redirects me to /wp-admin/admin-post.php which is a blank page.
I have no idea what is the best course of action to do it, should I make an ajax request on my button to run the function and then get the return value from that ajax call ? Or is there a better way to go about this ?
Thanks for helping me, have a great day
EDIT : Updated code, no errors but output is still not printed to page or console.
function actu_scripts_page()
{
?>
<div class="wrap">
<h2>Sahar actu plugin</h2>
<form action="" method="post">
<?php wp_nonce_field('do_test', '_test_nonce') ?>
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
</div>
<?php
if (isset($_POST['start_test'])) {
if (isset($_POST['start_test'])) {
if (!wp_verify_nonce($_POST['_test_nonce'], 'do_test')) {
// error in nonce
} else {
start_test();
}
}
}
?>
<?php
}
function start_test()
{
echo("hhhhh");
die(); // tried with and without, no difference
}
add_action('admin_post_start_test', 'start_test');
There are two ways to acheive this, both are fine, it just depends on the user experience you desire. Use the normal http form submission (what you have already), or use ajax. The normal form submission is the easiest method.
Submit the form using the standard method (what you have there), which will reload the page. Important Note it would be better to leave the action attribute blank like action="" if you are submitting the page to itself.
You will also want to add a nonce to the form using wp_nonce_field() and check its value in the submission block with wp_verify_nonce().
So your form would like something like this:
<form action="" method="post">
<?php wp_nonce_field('do_test', '_test_nonce') ?>
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
Add a php block to check if the form has been submitted and do your script in there, printing any output with php.
function start_test() {
// do things. If successful, return true. Otherwise return false
return true;
}
if( isset($_POST['start_test']) ) {
if( ! wp_verify_nonce( $_POST['_test_nonce'], 'do_test' ) {
// error in nonce
} else {
if( start_test() )
echo '<p>Success!</p>';
else
echo '<p>Failure!</p>';
}
}
There is a redirection happening through /wp-admin/admin-post.php that will return you back to the previous screen.
Your results are being printed on this page, and since it's redirecting, you don't get to see anything.
All you need to do to solve this issue, is add this after your debugging code:
die();
Or
exit();
This will stop the PHP from executing anything after your code. Thus, stopping the page from redirecting. Also, any functions that will run after you function, will not run normally, so if you're expecting saving for example, it won't happen after this piece of code.
I've been working on php application and I've used a OO programming so far to develop it . I have declared a class like this
<?php
class User
{
public function Add_element()
{
//adds some element
}
public function Delete_Element($element_ID)
{
//delete the element with that ID
}
}
?>
I've created an object of user class (for example $user = new User()) in my index.php file which includes my view.index.php and the view.index file is organized as follow
<html>
<header></header>
<body>
<input type="button" id="ID" value='Delete Element' >
</body>
<html>
I know this question may seem repetitious but I want to know how can I call the $user->Delete_element($ID) method upon clicking the button .
You could do something along these lines:
First of all use a form:
<form method="POST" action="delete.php">
<input type="hidden" name="element_id" value="id">
<input type="button" name="delete" value="Delete element">
</form>
And create the following php script:
if(isset($_POST['element_id']))
{
$element_id = intval($_POST['element_id']);
$user->deleteElement($element_id);
}
OR use ajax, which is a bit more complicated.
Edit:
If you do not want to refresh the page you should use AJAX. Start off by including jQuery, which makes this a lot easier. Now you need something like this:
$("form").submit(function(e){
var data = {};
data.element_id = $(this).find("[name='element_id']").val();
$.POST("delete.php", data).done(function(response){
alert(response);
});
e.preventDefault();
});
edit your html file (change the "input" tag to an html form):
<form action="Delete_Element.php" method="POST">
<input type="button" name="ID" value='123456789' >
</form>
create a new php page called "Delete_Element.php":
<?php
if ( isset($_POST["ID"]) )
{
/* init the "user" object, assuming it is init to: $myUser */
//this line invokes your method, given the posed IP param. .
$myUser->Delete_Element($_POST["ID"]);
}
basically i want to have a link inside a div when clicked it will display a <form>
<sidebar>
<h2>Title</h2>
Display
<hr>
//display here
</sidebar>
display.php
function display() {
$test = echo '<input type="text" name="text">';
return
}
the logic goes like, if i clicked the href="display.php" it will display the function display();
how can i display the returned value in display() function below <hr>
i cant seem to figure our the correct logic for it,
<hr>
if (display() == true) {
$test = echo '<input type="text" name="text">';
return
}
You cannot do that, you need to submit the request to the server in order to process and get back that echo, here the way you are doing won't work, either use a form or a link with a parameter(If you are using GET method) with get or post method, and by using $_GET or $_POST, you can execute the function.
Also your function is wrong, you cannot write an echo like that, it should be
function display() {
$test = '<input type="text" name="text">';
return $test;
}
For example
If you are using GET than link with a parameter is sufficient, say
Display
<?php
if(!empty($_GET['true'])) {
echo display();
}
?>
Alternatively if you want to use a post method than you'll need a form as I specified before
<form method="post">
<input type="submit" value="Display" name="display" />
</form>
<?php
if(!empty($_POST['display'])) {
echo display();
}
?>
Use Javascript for this. Render the form always, hide is using using style='display:none;'. Add a click handler to the link having it show the form when the link is clicked. I recommend using jQuery to add the handler to make this task easier.
Normally, when I'm handling forms, in the "action" parameter, I usually have to reference a full PHP script, like this:
<form method="post" action="foo.php"></form>
Is there a way to tell the form to use a function or method rather than having to mention a whole script?
Not that I know of, but I'm pretty sure you could do something like this...
action="foo.php?fromForm=yes"
Then in your php code, you could have this...
if($_GET['fromForm'] == "yes") {
//put your function here, or call it here
}
else {
//rest of code goes here
}
imagining that your form looked something like:
<form name="form1" method="post" action="">
<p>
<label></label>
<input type="text" name="textfield" id="textfield" />
</p>
<p>
<label></label>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
then you could just put at the top of the php:
if (isset($_POST['textfield'])) {
foo();
}
replacing foo(); with the name of the function you want to execute.
This simply checks if there was any form data posted to the page with name="textfield".
No. What you're specifying is not a script, it's a URL. HTML/the browser doesn't know about server-side functions or methods, only about URLs.
You can use the onsubmit attribute to call a javascript method instead:
<form method="post" onsubmit="doSomething()"></form>
You can also use this to validate your form before passing it to a script such as the following:
<form method="post" action="foo.php" onsubmit="canSubmit()"></form>
NOTE: I'm assuming you're asking if you can access a method or function in the PHP code on the server-side, not call a JavaScript function on the client-side!
The client side cannot arbitrarily invoke methods on the server side. The URL or path to the resource, is what is used to identify a resource on the server.
If you want to perform different functionality in the same script, you could use if/else blocking and use query parameters to differentiate your URLs.
HTML:
<form method="post" action="foo.php?method=saveData"></form>
PHP:
<? /* foo.php */
if($_REQUEST['method'] == "saveData") {
// do stuff
} else if($_REQUEST['method'] == "doSomethingElse") {
// do other stuff
}
?>
This is at it's core a very basic example. For more complex needs, many frameworks can perform this level of branching, out of the box, and with much more sophistication.
If your PHP script is written as follows:
<?php
switch ($_GET ['f']) {
case 'do_one':
// do something
break;
case 'do_two':
// or use a callback
do_two_callback ();
break;
default:
// ...
}
?>
... you can always do this
<form method="post" action="foo.php?f=do_one"></form>
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 cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
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).
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 } ?>
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>
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>
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);
}
...
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>