WordPress wp_mail called from function - php

im trying to create a WordPress plugin for first time.
What i want from this plugin is really simple. I need to show form with 2 fields one for Subject second for message. Then take all registered users emails and use this data in wp_mail.
Then use short code soo i can display that form on front end. Just need to make possible send information imail to all registered users from front end.
Im trying this code:
if(isset($_POST['button1'])) {
showtext();
}
function show_form(){
echo ' <form method="post">
<input type="submit" name="button1" value="Button1"/>
</form>
';
}
function showtext(){
echo "text";
}
function group_email_shortcode() {
$odeslano=wp_mail( 'jindra.kos#seznam.cz', 'The subject', 'The message' );
if($odeslano) {
return "odeslano";
}//message sent!
else {
return "chyba";
}//message wasn't sent
}
add_shortcode( 'helloworld', 'show_form' );
If i call function for sending email in short code then it will send email and its working. When i try to call function where im showing form and from that form im calling function for sending email its not working and it shows me info about crytical error on page.. I have read a lots of stuffs, but i cant find any hint what im making wrong.

Related

PHP: Hide Form after validation (class)

I have a form that is mostly generated by a class named "buildform".
Now every part of the form validates itself on the position it is.
This looks like this:
echo $frm->create_input("customer_nr", "Customer Nr.", "text:empty:int");
The third attribute here are the conditions (here: text field, not empty only integer).
The function "create_input" calls some more function that are validating the form field directly on place when the form is submitted.
I do it this way for multiple reasons:
I can directly color the forms to red when there's an error
I only have to tell the form attributes one time instead of when creating it and validating.
This is really comfortable and until now has made creating forms very easy.
The validation errors for then the users will be stored in a class variable like this:
function add_err($n_errmsg) {
$this->errmsgs[] = $n_errmsg;
return;
}
At the end of the form I show the errors like this:
if(isset($_POST["sbm"])) {
$ret_err = $frm->ret_err();
if(!empty($ret_err)) {
echo $ret_err;
}
else {
// send success mail
}
}
This all works without any problems.
Now I had the idea to hide the form when it's submitted. But then I would have to make sure there are no errors before the form even is loaded!
I wanted to something like
else {
$hideform = true;
// send success mail
}
This currently is not possible as the errors are generated while "generating" the form fields.
If I move the errors to the top the errors are always "empty" there because the validation is done later below...
Do you have an idea how I can solve this?
Do I have to validate the forms before loading them or is there another way?
Thanks!
Best Regards
Toby
Ok, well there are a few ways to solve this.
Basically you are echoing the form html as you go along:
echo $frm->create_input(...);
echo $frm->create_input(...);
what you could do instead is save the html into a string:
$formhtml = '';
$formhtml .= $frm->create_input(...);
$formhtml .= $frm->create_input(...);
if($frm->ret_error()){
echo $formhtml;
//other logic
}else{
//send mail
}
Along the same lines, you could change your form class, so that this is done internaly, and add a show method:
private $html = '';
function create_input(...){
//retrun $ret;
$this->html .= $ret;
function show(){
echo $this->html;
}
$frm->create_input(...);
$frm->create_input(...);
if($frm->ret_error()){
$frm->show();
//other logic
}else{
//send mail
}

Unable to insert data with CodeIgniter

I am making a website in CodeIgniter and for one of these pages I need to insert information into a database, however every time I enter information into my form and submit it, the page refreshes like it had been submitted but nothing enters the database.
Controller:
public function insertjob()
{
$this->load->helper('form');
$data['title']="Add a new job";
$this->load->view("insertjob", $data);
}
public function addingjob()
{
$jobtype=$this->input->post('jobtype');
$jobinfo=$this->input->post('jobinfo');
$this->load->model("cmodel");
if($this->cmodel->addjob($jobtype, $jobinfo)){
$data['msg']="New job addition successful";
}else{
$data['msg']="There was an error please try again";
}
$this->load->view("confirmation",$data);
Model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob); exit;
View:
</p>
<?php
echo form_open('client/insertjob');
echo form_label('Job:', 'Job');
echo form_input('jobtype');
echo form_label('Job information:', 'Job information');
echo form_input('jobinfo');
echo form_submit('Add job', 'Submit Post!');
echo form_close();
?>
Try removing the exit from your model:
function addjob($jobtype,$jobinfo)
{
$newjob=array("jobtype"=>$jobtype,"jobinfo"=>$jobinfo);
return $this->db->insert('clientjobs', $newjob);
}
It's not neccessary and could be breaking the database class, as well as halting any execution for the application.
Here's your problem:
echo form_open('client/insertjob');
If you look at your HTML code in your browser, you'll see something like this:
<form action="client/insertjob">
There will probably be a whole bunch of other attributes in your form tag - they're not important for this answer.
That action attribute is telling the browser where to go after you click submit. Where is it going? Back to the insertjob method. But it needs to go to your addingjob method - that's where the database update is actually being done. So change the form_open call to:
echo form_open('client/addingjob');
As I see your are using 2 controller functions for posting, page 1 to page 2. You have error on form open you should post your data to addingjob not insertjob.
echo form_open('client/addingjob');
will fix your issue but I highly recommend you to use, one controller for form submit. Below code will send post to same url. And you could add some attributes on it.
<?php
$attributes = array('class' => 'form-horizontal');
echo form_open($this->uri->uri_string(),$attributes); ?>

Multiple the same forms and POST method?

I have multiple instances of the same form (name / email / message fields) on one page. They all share one class ('.contact-form') and different (dynamically generated IDs).
I validate them using jQuery Tools Validator (it's not relevant though as I have no problems with this at all):
$(".contact-form").validator();
The problem lies in my sendmail.php file I suppose, that's how I get all POST values & validate them:
//grab the fields
$address = trim($_POST['address']);
$title = trim($_POST['title']);
$message = $_POST['message'];
//check if empty
if(empty($name) || empty($title) || empty($message)) {
$wrong = true;
}
if($wrong) {
http_response_code(400);
} else {
// do stuff
http_response_code(200);
}
Now, the issues I'm facing are:
I can't send any other forms excepting the very first on the page, for the rest (even if they're properly filled) I'm getting this error:
Notice: Undefined index: address in mysitesaddress on line 3
after I send the first form - the other forms doesn't act like expected - they are getting through even if all fields are left empty (validator displays errors on front end but then fires "success" after a second because sendmail.php returns "200 OK".
Any ideas how to fix it / check every form instead of just the first one / clear POST data after sending? I'm sure there's an easy way to do that in PHP, I'm not that familiar with that language (mostly a front-end guy) so any help would be much appreciated.
Thank you!
(I've been Googling for an answer for a while now, but looks like "POST" is a tricky name and I'm getting Wordpress/blogs/forums related stuff mostly...)
[update]
Here's the HTML code of each form:
<div class="wrapper">
<form class="contact-form" action="sendmail.php" method="post" novalidate="novalidate">
<input name="title" type="text" required="required" />
<input name="address" type="email" required="required" />
<textarea name="message" required="required" ></textarea>
<input type="Submit" value="Submit" />
</form>
<div class="sucess">
Success message that replaces form ^.
</div>
</div>
The notice implies the 'address' key does not exist.
You should check if the indexes in the $_POST variables are set/exist, e.g. using the PHP isset() function.
This could be caused because you aren't sending the address in every form, just in the first or something like that.
Sample code on how you could use isset to check:
if ( isset($_POST['address']) ) {
//only set $address to the $_POST value if it is set
$address = trim($_POST['address']);
}
I can't see your HTML form code, but I'm guessing your form tag looks like this
<form action="sendmail.php" method="post">
This will take all the fields from the form that was submitted and send them via $_POST to your sendmail.php. After you process the data (edwardmp gave a great tip for making sure the data was there before trying to assign the variables), you would then redirect the page to some type of success landing or back to the original form page. The method I've been using to do this is:
if($wrong) {
$error = "Please check your entry and try again.";
header("Location: http://example.com/formpage.html?error=" . htmlencode($error),true,303);
exit();
} else {
// do stuff
$msg = "Your form was successfully submitted.";
header("Location: http://example.com/formpage.html?msg=" . htmlencode($msg),true,303);
exit();
}
This design makes it so the $_POST data is cleared by reloading the page, and allows you to send messages back to the originating page which you would display through $_GET['msg'], or $_GET['error']. This should stop the forms from submitting erroneously.

to display message in same form page

I need to add a notification to this page saying " Thank you for your feedback"
However,the notification did not appear at the correct place,which is above the form.
This is my code.
$message="tq 4 feedback";
$common->display_message($message);
This is where the feedback form.
The function i'm using is
function display_message($message) {
print $message;
}
Thanks
Not sure why if you have the message already you are passing it to a function to display, but you need to "return" the variable from the function. Then you can echo it out wherever you need to.
function display_message($message) {
return $message;
}
To call it:
$message="tq 4 feedback";
$returned_message = $common->display_message($message);
And place it where you want:
echo $returned_message;
or just:
$message="tq 4 feedback";
echo $common->display_message($message);
It's probably an issue with your view, to be honest. What's your view look like?

Post Back response from PHP to javascript

I'm new to forms and post data ... so I don't know how solve this problem!
I've a php page (page1) with a simple form:
<form method="post" action="/page2.php">
<input type="search" value="E-Mail Address" size="30" name="email" />
<input type="submit" value="Find E-Mail" />
</form>
How you can notice ... this form post the 'email' value to the page2. In the page2 there is a small script that lookup in a database to check if the email address exist.
$email = $_POST['email'];
$resut = mysql_query("SELECT * FROM table WHERE email = $email");
.
.
.
/* do something */
.
.
.
if($result){
//post back yes
}
else{
//post back no
}
I don't know how make the post back in php! And how can I do to the post back data are read from a javascript method that shows an alert reporting the result of the search?
This is only an example of what I'm trying to do, because my page2 make some other actions before the post back.
When I click on the submit button, I'm trying to animate a spinning indicator ... this is the reason that I need to post back to a javascript method! Because the javascript function should stop the animation and pop up the alert with the result of the search!
Very thanks in advance!
I suggest you read up on AJAX.
Here's a PHP example on W3Schools that details an AJAX hit.
Hi i think you can handle it in two ways.
First one is to submit the form, save the data in your session, check the email, redirect
back to your form and display the results and data from session.
Like
session_start();
// store email in session to show it on form after validation
$_SESSION['email'] = $_POST['email'];
// put your result in your session
if ($results) {
$_SESSION['result'] = 'fine';
header(Location: 'yourform.php'); // redirect to your form
}
Now put some php code in your form:
<?php
session_start();
// check if result is fine, if yes do something..
if ($_SESSION['result'] == 'fine) {
echo 'Email is fine..';
} else {
echo 'Wrong Email..';
}
?>
More infos : Sessions & Forms
And in put the email value back in the form field
<input type="search"
value="<?php echo $_SESSION['email']; ?>"
size="30"
name="email" />
Please excuse my english, it is horrible i know ;)
And the other one the ajax thing some answers before mine !
As a sidenote, you definitly should escape your data before using it in an SQL request, to avoid SQL injection
As you are using mysql_* functions, this would be done with one of those :
mysql_escape_string
or mysql_real_escape_string
You would not be able to post in this situation as it is from the server to the client. For more information about POST have a look at this article.
To answer your question you would want to do something like this when you have done your query:
if(mysql_num_rows($result)){ //implies not 0
$data = mysql_fetch_array($result);
print_r($data);
}
else{
//no results found
echo "no results were found";
}
The print_r function is simply printing all the results that the query would have returned, you will probably want to format this using some html. $data is just an array which you can print a single element from like this:
echo $data['email'];
I hope this helps!
<?php
echo " alert('Record Inserted ');"
OR
echo " document.getElementByID('tagname').innerHtml=$result;"
?>
OR
include 'Your Html file name'

Categories