Stay on same page after form submit within WordPress - php

I've added my HTML page as part of the admin wordpress (see screenshot)
And I'm trying to get it so on each submit button, if the record is successfully added to the database a pop up shows up saying "Success!" and then clear the form data without leaving the page. At the moment my current set up tries to load the external page instead of remaining on the page in the screenshot. Here's my HTML and PHP:
<form class="pure-form" name="addAthlete" action="submitForm.php" method="POST">
<fieldset class="pure-group">
<input type="text" class="pure-input-2" name="membershipID" placeholder="Membership ID">
<input type="text" class="pure-input-2" required="required" name="firstName" placeholder="First Name">
<input type="text" class="pure-input-2" required="required" name="surname" placeholder="Surname">
</fieldset>
<button name="submitAthlete" type="submit" class="pure-button pure-input-2 pure-button-primary">Submit</button>
</form>
<?php
function showSuccess() {
echo "Success! One record added.";
}
if (isset($_POST['submitAthlete'])) {
addAthlete();
}
function addAthlete() {
include 'addAthlete.php';
showSuccess();
}
?>
I'm assuming the problem lies with the fact that the echo "Success" is trying to echo on the submitForm.php page which is how I've written it. This is because of the way the page is embedded into wordpress, you can see this below:
add_action( 'admin_menu', 'db_menu' );
function db_menu() {
add_menu_page(
'Database Form', // page title
'Database Form', // menu title
'manage_options', // capability
'database-form', // menu slug
'wpse_91693_render' // callback function
);
}
function wpse_91693_render() {
global $title;
print '<div class="wrap">';
print "<h1>$title</h1>";
$file = plugin_dir_path( __FILE__ ) . "submitform.php";
if ( file_exists( $file ) )
require $file;
print '</div>';
}
How can I get a pop up or something to show up within this WordPress page on each submit?
Thanks!

When you submit a form, it posts data to a new webpage by loading it. In order to stay on the same page, the action should take you to that same page ( move your processing logic there aswell, checking for posted arguments ) or if you don't want to see a reload, use ajax instead.

Related

Custom result page upon submitting search form

I'm running in circle, i'm trying to run a query from a custom search form and to display the result on a specific custom page.
I've created a custom search page called search-custom.php and i've registered it.
Now I don't understand why when I submit my seachform i'm getting a 404 error.
This is my searchform currently, upon submitting the form, the url path seems right, am I missing something?
<form action="<?php echo esc_url( home_url().'/search-custom' ); ?>" method="get">
<input type="hidden" name="s" value="<?php the_search_query(); ?>">
<input type="hidden" value="qcm" name="post_type">
<button type="submit"><span class="mr-2">Go</button>
</form>
I don't want to redirect it from the function.php file I need this current format. Thanks in advance for your lights.
You do not need to change the action of your form to the name of your template file. Inside of your search-custom.php there is:
<form action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<input type="hidden" name="s" value="<?php the_search_query(); ?>">
<input type="hidden" value="qcm" name="post_type">
<button type="submit"><span class="mr-2">Go</button>
</form>
With this template file having set, you can use it in your page template (the page you want the form to display, or maybe in a sidebar or something) with:
<?php get_template_part( 'search', 'custom' ); ?>
The default wordpress search template will be used to output the results.
If you want to use a different template file for the results, you can put this in the functions.php file of your theme and change the results page (i.e. search-results-custom.php):
add_action('template_include', 'search_custom_template');
function search_custom_template( $template ) {
if ( isset( $_REQUEST['search'] ) && is_search() ) {
$temp = locate_template('search-results-custom.php');
if ( ! empty($temp) ) {
$template = $temp;
}
}
return $template;
}
Multiple search results pages using different forms
If you want to set a value in your form, and using that to get to specific result pages:
Open the search.php file of your theme, make a copy for safety and replace the whole content of the file with the following code:
<?php
if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
if($type == 'qcm') {
load_template(TEMPLATEPATH . '/search-custom.php');
} elseif($type == 'another') {
load_template(TEMPLATEPATH . '/search-another.php');
}
}
?>
In this code we check what value is set for the field with the name post_type. In your question, you have set the value of qcm. When the field has this value on submit, you will load the search-custom.php. If you have other forms with other values, you can just add an elseif and load another search results template.
If you want to use another hidden input for checking the value, you can simply create one:
<input type="hidden" name="my-hidden-info" value="value-to-check" />
As you see, this way you can edit a value inside of your form and get different search results pages for the specific values. The action of the form is not changed and you will always use the search.php file. You just add other templates, which you are loading inside of this file in the if and elseif. So you get multiple search results pages using different forms.

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.

how do I get the message after submit to appear inside the pop up instead of on a different page

I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.

I want to convert a php/mysql application to a wordpress plugin

I have a php/mysql web application.I want to convert it in a wordpress plugin.How can I make link of one php file to another file.
For example I have plugin tw. tw.php is its index file and the other file name is tw1.php.
first page
/* plugin name:tw
plugin url:httpL://csr.estheticsolutions.com.pk
*/
//tell wordpress to register the demolistposts shortcode
add_shortcode("demo-list-posts", "demolistposts_handler");
function demolistposts_handler()
{
//run function that actually does the work of the plugin
$demolph_output = my_function();
//send back text to replace shortcode in post
return $demolph_output;
}
function my_function()
{
?>
<html>
<body>
<form action="tw1.php" method="post">
<input type="text" name="fname" >
<input type="submit" value="Submit" >
</form>
</body>
</html>
<?php
}
?>
second page
<?php
$First_Name=$_POST['fname'];
echo $First_Name;
?>
when i submit value in tw.php ,an error appears tw1.php not found(404) in wordpress folder,then i paste the file tw1.php in that(wordpress) folder and submit, posted value get in new page without wordpress theme.
Create a table with name=people with columns: id, firstname, lastname, DateofBirth, addressid, fatherid, motherid. Have suitable column properties with each column.
You can use the plugin url function to link to the second file:
<form action="<?php echo plugins_url( 'tw1.php', dirname(__FILE__) ); ?>" method="post">
<input type="text" name="fname" >
<input type="submit" value="Submit" >
</form>

Input validation displays error message that should only show up in an if statement

I am putting together a WordPress theme options page. I am trying to figure out if a url entered into a text field passes a validation. If it doesn't, I want to display a message at the top of the admin page to correct what is entered.
In this case, I want to display File type must have the file extension .jpg, .jpeg, .gif or .png at the top of the page when a user enters a file with any other extension. This message is within an if statement, but it is showing up regardless of what is typed into the field. I would like to know what mistake I am making here or if the input is even being validated.
Here is the code within the initialization of the options page
add_action('admin_init', 'theme_admin_init');
function theme_admin_init() {
register_setting(
'coolorange_theme_options',
'coolorange_options',
'coolorange_options_validate'
);
// what each parameter represents:
// add_settings_field($id, $title, $callback, $page, $section, $args);
add_settings_section(
'coolorange_logo_main',
'Logo Section Settings',
'logo_section_text',
'coolorange'
);
add_settings_field(
'upload_image_button',
'<strong>Upload logo to the Media Folder</strong>',
'file_upload_button',
'coolorange',
'coolorange_logo_main'
); // Upload Logo button
add_settings_field(
'logo_textfields',
'<strong>Logo location</strong>',
'file_location',
'coolorange',
'coolorange_logo_main'
); // logo url, width and height text fields
add_settings_field(
'restore_selectbox',
'<strong>Restore original heading</strong>',
'restore_dropdown',
'coolorange',
'coolorange_logo_main'
);
}
Here is the code for the input box (this is within a file_location() function):
<strong>File URL:</strong> <input id="image_url" type="text" value="<?php $options['image_url']; ?>" size="60" name="coolorange_options[image_url]" />
And this is the validation code:
//Validation
function coolorange_options_validate($input) {
$options = get_option('coolorange_theme_options');
//check filetypes for image url
$options['image_url'] = trim($input['image_url']);
if ( !preg_match ( '/\.(gif|jpg|jpeg|png)$/', $options['image_url'] ) ) { //opens if statement
$options['image_url'] = '';
echo '<div id="message" style="color: red;"><p>File type must have the file extension .jpg, .jpeg, .gif or .png</p></div>';
} // closes if statement
else {
}
return $options;
}
add_action('admin_notices', 'coolorange_options_validate');
//shows validation errors at the top of the page
Looks like problem is in the html name in following line
<strong>File URL:</strong> <input id="image_url" type="text" value="<?php $options['image_url']; ?>" size="60" name="coolorange_options[image_url]" />
It should be like following
<strong>File URL:</strong> <input id="image_url" type="text" value="<?php $options['image_url']; ?>" size="60" name="coolorange_theme_options[image_url]" />
As you are expecting $options = get_option('coolorange_theme_options');.

Categories