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.
Related
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');
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 wrote this form using html and PHP on my webpage. This form receives a number as input. and adds the desired number to 2. And prints the output.
For example, if we put the number 5 at the input and press the submit button , The page refreshes to this URL : mysite.com/page1/?sen=5&sub=Submit
And the number 7 is printed on the output.
So far so good. But when we refresh the page in this case , The submitted information will not be deleted and the url will remain "mysite.com/page1/?sen=5&sub=Submit" .And the output is not cleared and still remains 7.
In this case, I want the page to return to its original state, (mysite.com/page1) . And the output is cleared.
what's the solution?
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php if ( isset($_GET['sub'])){
//$sen1=0;
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
else {
echo $sen1 + 2; }
}
?>
This can easily be achieved with Javascript. Here's a very basic example.
You could make this a function. Then call it once to invoke it on a page refresh, and if you want to invoke it on button actions, you can use an html onclick attribute, or an event listener.
<script>
function clearFormAndParams() {
// Target each form input and set the value to "".
document.querySelector("input[name='sen']").value = "";
// Split the url by the "?" and then set the value to the first half.
window.location = window.location.href.split("?")[0];
}
clearFormAndParams(); // runs on refresh
var submitButton = document.querySelector("input[name='sub']");
submitButton.addEventListener("click", function() {
clearFormAndParams();
});
</script>
You could achieve your goal by modifying your code to store the results of calculation in a cookie / session variable and redirecting to the same page without the extra parameters like so:
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php
if ( isset($_GET['sub'])){
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
setcookie("result", $sen1 + 2);
header("Location: " . $_SERVER['PHP_SELF']);
}
echo $_COOKIE['result'];
?>
http://alpha.ripfy.com/
As seen in the following demo, I have a YouTube video that I want to be able to play while adding items to the array in PHP. Sadly, this isn't possible from what I've tried because the page refreshes every time I add an item to the array.
Would there be any way of achieving this without the page refreshing (forcing the video to restart?)
Code:
<?php
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method="post">
<?php
foreach($playlist as $song) {
?>
<input type="hidden" name="playlist[]" value="<?php echo $song?>">
<?php
}
?>
<input type="text" name="name1"/>
<input type="submit" name="submit1"/>
</form>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
Thanks for helping me out!
if you need that these information be storaged in database or anything on server sider don't use the convencional form post, use AJAX with JQuery.
First create a div(container)to render the list content where you need the information apears:
<div id="list_musics"></div>
Then create a page(i.e. page.ajax.php) that will treat your request. If you need you can put the information in a database or anything you want by this page. This page must return the content you want to render.
HTML:
<input type="button" id="ajaxcaller">
JQUERY:
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
$.post(page.ajax.php,text,function(data){
//Render your content in the container created on HTML
$("#list_musics").html(data);
});
});
If you just need to show what you wrote on text input instead of storage or treat the information, you may just use JQUERY to render the information in the container you created.
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
// PUT THE TEXT RIGHT AFTER THE CONTENT THAT ALREADY EXISTS IN THE CONTAINER
$("#list_musics").append(text);
});
Take a look here to see the sencond option:
https://jsfiddle.net/wqLf65ox/
Here's my answer. That fully works. In this script, the server checks the presence of a name1 request (post or get). If exists, it returns the string posted (only) and if doesn't, it returns what already was there. And the post() method posts (gets) the data and appends to the container using innerHTML+= data + "<br>";
evaluate the code, it should be self explanatory.
<?php
if (isset($_REQUEST['playlist'])) {
$playlist = $_REQUEST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_REQUEST['name1'])) {
// if exists, return plain text responce. NOT HTML
$playlist[] = $_REQUEST['name1'];
echo $_REQUEST['name1'];
}
else{
?>
<html>
<head>
<title>Demo</title>
<script src="jquery.js"></script>
</head>
<body>
<script>
text= ""
function onUpdate(){
text = document.getElementById("name1").value;
}
function handler(data){
document.getElementById('container').innerHTML += data+"<br>";
}
function post(){
onUpdate();
$.get("index.php", name1="+text, handler);
}
</script>
<input type="text" name="name1" id="name1"/>
<input type="submit" name="submit1" onclick="post()"/>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<br>
<div id="container">
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
</div>
</body>
<?php };?>
Although, it works as intended, i don't see the point of using it. just plain js should work
You have to send your form using Ajax, eg. via jQuery.post() method.
After that you have to reload your container with list or add new item there with JavaScript.
Try using the $.post and $.get JQuery methods. One method might be to $.post back to a .php page that renders a container of html, then use $.get to retrieve just that html container and insert into the DOM.
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.