Wordpress - shortcode executed after HTML form submit - php

I have a problem with Wordpress shortcode and Elementor. Let's say that I have the following shortcode inside functions.php:
function some_shortcode($atts) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'It works!';
}
}
add_shortcode('shortcode', 'some_shortcode');
Next, i put the following HTML code to page using Elementor:
[shortcode]
<form method="POST">
<button type="submit">Click me</button>
</form>
I'd really love to the shortcode function executes only when the user clicks the form button (so when the POST method happens) but in fact, the shortcode is executed all the time (looks like if the condition inside the shortcode function doesn't work). Could you tell me, please, how can I make the shortcode working only after the form button click?

First of all, give a name attribute to your submit button:
<form method="POST">
<button type="submit" name="trigger_shortcode">Click me</button>
</form>
Then in your shortcode, check if the name is available in the $_POST array:
function some_shortcode($atts) {
if (isset($_POST['trigger_shortcode'])) {
return 'It works!';
}
}
add_shortcode('shortcode', 'some_shortcode');
Note that for shortcodes, you must return the output, not echo it.

You must enter a field of the form to be submitted within your condition. For example, the name button of the submission button or the name of the input field.
[shortcode]
<form method="POST">
<button type="submit" name="my-form-submitted">Click me</button>
</form>
And use isset for if statement. So PHP code must changed like this:
function some_shortcode($atts) {
if ( isset( $_POST['my-form-submitted'] ) ) {
echo 'It works!';
}
}
add_shortcode('shortcode', 'some_shortcode');

Please put shortcode only to the page instead of HTML code and place following code to functions.php
function some_shortcode($atts) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
return 'It works!';
}
echo '<form method="POST"><button type="submit">Click me</button></form>';
}
add_shortcode('shortcode', 'some_shortcode');

Related

prevent page from refreshing after clicking a button

After a button is clicked, the page refreshes, which interferes with further functions of the page.
I tried changing the type from "submit" to "button", but then the button doesn't work at all. I also tried to return false the functions.
My simple code goes like this
<html>
<body>
<form method="Get" action="">
<input type="submit" name="buttonV" onclick="function1()"> <br>
<input type="submit" name="buttonS" onclick="funciton2()">
</form>
</body>
</html>
<?php
if ($_GET) {
if (isset($_GET['buttonV'])) {
function1();
} elseif (isset($_GET['buttonS'])) {
function2();
}
}
function function1()
{
// do stuff
}
function function2()
{
// do stuff
}
?>
What should I do in order to prevent the page to refresh?
I saw you are using php. I don't you use javascript.
You can use 'event.preventDefault()'.

How to run a function through my plugin page and print the result on that same page

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.

execute a function when a link is clicked

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.

jquery return value by php echo command

I have these codes:
Contents of main.php:
Javascript
function grab()
{
$("#div_id").load("/test.php");
}
HTML & PHP
<? $original_value = 'Original content'; ?>
<div id='div_id'><?=original_value;?></div>
<form action="javascript:grab($('#div_id').val())">
<input name="submit" type="submit" value="submit">
</form>
also test.php
<?...
$update_value = "Update content";
echo $update_value;?>
the result of test.php will be written into #div_id and the result for div content is:
Original content
Update content
But i like to overwrite original div value and the result should be:
Update content
I mean echo append a new line in #div_id, but i like to overwrite existing #div_id content.
Change the following in your code.
Remove the javascript in your action attribute. It doesn't look right.
<form action="">
<input name="submit" type="submit" value="submit">
</form>
Add the following javascript.
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault(); // Prevents the default submit action.
// Otherwise the page is reloaded.
grab();
});
});
The function grab will be called when the form is submitted. I'm not sure if this is what you want, but you should see the new contents in the div.
UPDATE 1:
I have removed the parameter from grab because the function doesn't need one.
You need to replace the content while the current code appends it, change code to:
$("#div_id").empty().load("/test.php");

Javascript Validation

I was just trying to submit a simple form to the same page but when it is submitted it will call PHP function on the same page. However I was trying to do some JavaScript validation before submission. So I want to know what the difference between using onSubmit call js function in the form tag and onClick call js function with button.... This is what I am currently trying to do.
<?php
function tobecalled()
{
echo "This was run";
}
?>
<html>
<head><title>Testing</title>
<script type="text/javascript">
function testResults (form)
{
var TestVar = form.inputboxname.value;
if(TestVar == '')
return false;
else
return true;
}
</script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST" onSubmit="return testResults(this);">
<input type="text" name="inputboxname" />
<input type="submit" value="Save" name="submit" />
<?php
if(isset($_POST['submit']))
tobecalled();
?>
</form>
</body
</html>
It works..
But if I make (Submit Via JS)
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
...
<input type="submit" value="Save" name="submit" onClick="return testResults(this);"/>
...
Its still calls the PHP function tobecalled()--Why? I am expecting it not call. How do it work?
The reason that it is allowing it to go through is because you are passing this in the onclick event. In this instance this is referring to the submit button not the form as required by the function.
Thus form.inputboxname.value returns undefined which is not '' (empty string) and therefore the testResults function returns true. So the submit is then activated.
The difference is this. this points to a different object in onClick than in onSubmit. Your function expects a form to be passed, but when you use onClick, you give it the submit button. That's why the second method doesn't work as expected.
Because regardless of whether you add your javascript to the onsubmit of the form or the onclick of the submit button the form will still be submitted by the submit button. That means that a request is being sent back to the server and $_POST['submit'] will be set. Since that variable is set you find your function being called.

Categories