Pass variable from JavaScript AJAX Form to PHP Function - javascript

On my website I have a login form which submits some data (e.g. email address) to a PHP function AND starts the function running, which creates a user.
I want to pass some additional information from the page where the form is t
This is the data I want to send through the form:
<?php
$variable = "Your Name Here"
?>
This is the form itself:
<form action='http://dev3.benefacto.org/wp-admin/admin-ajax.php' method='GET'>
<b>Work E-Mail: </b><input type='text' name='email' id='email' placeholder='Enter Your Work Email' />
<input type='text' style='display: none' name='action' id='action' value='logged_in_check2' />
<input type='text' name='variable' id='variable' value=$variable />
<input type='submit' value='Next' class='cta' />
Any for arguments sake let's say the PHP function is
function simple_name_return()
{
echo 'Hello'
$variable = $_GET["variable"];
echo $variable;
}
add_action("wp_ajax_nopriv_simple_name_return", "simple_name_return");
add_action("wp_ajax_simple_name_return", "simple_name_return");
I think this might be helpful but I am completely new to JavaScript so a bit stumped: Pass Javascript variable to PHP via ajax
Any thoughts much appreciated.

I answered a very similar question here.
Basically you need to pass the variable via POST/GET, check the result and respond. To check the email you would do something like this:
emailcheck.php
<?php
// Assume success by default
$result = true;
if (!filter_var($_GET['email'], FILTER_VALID_EMAIL)) {
$result = false;
}
// Other checks, such as domain here, set $result to false if check fails
// Throw error if email isn't valid so it can be picked up by $.ajax
if (!$result) {
http_response_code(500);
}
JS (requires jquery)
function isValidFormEmail()
{
// Perform ajax call to emailcheck.php
$.ajax({
url: '/emailcheck.php?email=' + $('#email').val(),
error: function() {
$('#custom-email-error').show();
},
success: function(data) {
// Submit form
$('form').submit();
}
});
// Prevent form from submitting on click
return false;
}
This should work with your HTML as it is currently providing the action URL moves to the next action.

Since you are submitting form to a page you need first receive the variable in admin-ajax.php then you can pass it to a function.

Related

Submit -> Execute PHP script -> Alert User -- while staying on same page

I have a page with two submit buttons using if ($_POST['action'] == 'Test SMS') to executed code for my "Test SMS" button. I need to execute code from a PHP script then give an alert box while not leaving the page.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
//alert user that there message has been sent
$alert = "Your message has been sent to " . $phone;
echo '<script type="text/javascript">alert("'.$alert.'");';
echo '</script>';
header('Location: index.php');
} else {-----action for other submit button------}
I asked a similar question that was marked a duplicate at Alert after executing php script while not leaving current page but was able to come up with a solution so I wanted to share.
I was able to accomplish this by adding a URL query string in my header('location: index.php?text=success) function then using JS I was able to use an if statement to look for the query string and alert if so.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("settings=success") > -1) {
alert("Your settings have been saved");
}
else if(window.location.href.indexOf("text=success") > -1) {
alert("A SMS has been sent!");
}
});
</script>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
header('Location: index.php?text=success');
} else {-----action for other submit button------}
header('Location: index.php?settings=success');
The only downside to this solution is that I don't have easy access to my PHP $phone variable to tell the user what number the message was sent to.
AJAX is the method most suited to this job, because what you are trying to achieve is a frontend interaction. Php is a server side language.
AJAX will transmit form data to the backend php script. Once the the php script has handled the data on the server, it can return the data you require to the AJAX script. This is done sometimes using JSON, especially as you have multiple variables.
$formdata = array(
'ntid' => $_POST['ntid'],
'phone' => $_POST['phone']
);
return json_encode($formdata);
The returned JSON code will look something like:
{"ntid":"NT ID","phone":"Phone number"}
Tutorials similar to this are very useful:
[http://www.yourwebskills.com/ajaxintro.php][1]
I have found that taking a break from your main project and investing a little time in learning the mechanics behind what your trying to achieve, enables you to solve your problem faster.

AJAX form submission, solely to prevent page refresh and nothing else

I've built a simple HTML/PHP e-mail sign-up form to appear in the footer area of my website. There are only two fields: email and country.
The form works perfectly for my purposes. Data collection, validation, sanitization, error handling, clear fields, success notification, etc. -- ALL GOOD!
My final step is to implement AJAX to prevent a page refresh. This is all that is required from AJAX.
All tutorials, articles, and answers to related questions on this site I have found offer code that includes functions I've already handled with PHP.
I've gotten as far as the AJAX submission, which works. The page doesn't refresh, user input is inserted to the database, and I receive the confirmation e-mail.
I would appreciate some guidance (or a link to a tutorial) that can help me implement the PHP error logic and echo PHP success/error messages.
HTML
<form action="process_footer_form/" method="post" id="footer-form">
<ul>
<li>
<input type="email" name="email" id="email"
value="<?php if (isset($email)) {echo $email;} ?>">
</li>
<li>
<input type="text" name="country" id="country"
value="<?php if (isset($country)) {echo $country;} ?>">
</li>
<li>
<input type="submit" name="submit" id="submit">
</li>
</ul>
<?php if (isset($success_message)) {echo $success_message;} ?>
<?php if (isset($error_message)) {echo $error_message;} ?>
</form>
JQuery
$(function() {
// identify form
var form = $('#footer-form');
// create event listener
$(form).submit(function(event) {
// disable html submit button
event.preventDefault();
// serialize form data
var formData = $(form).serialize();
// submit form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// 1. echo PHP success message
// 2. fire PHP clear fields command
})
.fail(function(data) {
// 3. execute PHP error logic here
// 4. echo PHP error messages
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Load PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
// Create PHPMailer session
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
// SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.xxxxxxxxxx.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->Username = 'xxxxxxxxxxxxxxxxxx';
$mail->Password = 'xxxxxxxxxxxxxxxxxx';
$mail->setFrom('xxxxxxxxxxxxxxxxxx' , 'xxxxxxxxxxxxxxxxxx');
$mail->addAddress('xxxxxxxxxxxxxxxxxx');
$mail->isHTML(true);
// Sanitize & Validate Input
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$country = trim(filter_input(INPUT_POST, 'country', FILTER_SANITIZE_SPECIAL_CHARS));
// set connection to mysql server
$connection = mysql_connect("localhost","xxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxx");
// connect to database
mysql_select_db("xxxxxxxxxxxxxxxxxx", $connection);
// insert user input to table
$sql = "INSERT INTO email_subscribers (email,country) VALUES ('$email','$country')";
if (!$connection) {
$error_message = <<<ERROR
<div>ERROR. Form not sent. Please try again or contact us.</div>
ERROR;
// Send error notice to host
$mail->Subject = 'Website Error - Footer Form';
$mail->Body = ("Error Notice: A site user is having trouble on the footer form.");
$mail->send();
} else {
// run query
mysql_query($sql, $connection);
$success_message = <<<CONFIRMATION
<div>Subscription complete. Thank you!</div>
CONFIRMATION;
mysql_close($connection);
// Send confirmation notice to host.
$message = <<<HTML
<span>E-mail: {$email}</span><br>
<span>Country: {$country}</span>
HTML;
$mail->Subject = 'New E-mail Subscriber - Footer Form';
$mail->Body = $message;
$mail->send();
unset($email, $country);
}
} else {
header('Location: http://www.mywebsite.com/');
exit;
}
?>
You might try simplifying your life by using the FormData object. Then your code could look something like this. I have tested this out.
<form method="POST" id="subscription-form" enctype="multipart/form-data">
<input type="email" name="email" id="email" value="gulliver#tinyletter.com">
<input type="text" name="country" id="country" value="Lilliput">
<input type="button" value="submit" id="form-submit">
</form>
Below this you could put in a div for displaying messages:
<div id="messages"></div>
Then your jquery/javascript would look something like this:
<script>
(function(){
$("#form-submit").on("click", function(){ submitForm();});
})();
function submitForm(){
var form = document.getElementById("subscription-form");
var fd = new FormData(form);
$.ajax({
url: './PHPscript.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
$("#messages").html(data);
}
});
}
</script>
Regarding letting PHP "handle the messages" I think you're missing something about AJAX.
In your initial PHP page you are loading the html that PHP has generated and then PHPs part is finished. When you make the AJAX call you are asking the server to execute a different PHP script and then return the output of that script back to javascript.
At that point you need to put whatever message PHP has generated back into the current page, which has not and will not reload. That was the purpose of using AJAX in the first place. That is what the "messages" div is for.
As a way of completely understanding this create an extremely simple PHPscript.php file that looks like this and try it out:
<?php
print $_POST['email'] . ' ' . $_POST['country'];
?>
You will see your values returned in the current page inside that messages div.
The first request to, for example www.mysite.com/something.php will run the PHP and dump the result into the page. Ajax doesn't work this way. You send a request to your PHP file, and it sends a response that you can then inspect and do something with.
If ajax responses dumped their content into the page like an initial load, mayhem would ensue.
Try something like this:
$.ajax({
url: url,
type: type,
data: data
}).done(function (response) {
console.log(response);
});
then have a looksie in the console and see what goodness you're getting from the PHP script. Then build that .done callback up to process the results of your request and determine what to do.
Okay, first thing, var that = this is a trick when you loses context, but where you use it is not somewhere you can lose it .. so forget it :)
Then your find().each(), it's a good way of getting your values, but jquery offers a method which is $( this ).serializeArray() (it does kinda exactly what your want)
Also, you send your data with ajax, but you have no callback. Your ajax call need to have at least a function to call once everything went fine. This is done with done()
Finally, returning false does cancel the event in most cases but you will prefer preventDefault() as it disable default behavior, but still propagate event (for other handlers).
Sum it all:
$('form.ajax').submit( function(event) {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serializeArray()
}).done(function(data) {
alert("Ajax call successful");
console.log("Server answer:" + data);
});
event.preventDefault();
});
Edit: Nvm my first remark, I understood lately your that = this stuff.

AJAX does not POST results to php page

I'm trying to create a player edit system for an admin section of a football website. The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
form on coach-home.php
<form id="form1" name="form1" method="post" action="coach-player.php">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input type="text" name="pid" class="pid" id="pid" value="<?php echo $pid; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
JS request on coach-home.php
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").click(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "GET",
url: "username.php",
data: dataString,
cache: true,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
username.php
<?php
if($_GET['activity'])
{
$activity=$_GET['activity'];
$sql=mysql_query("SELECT pid, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$pid=$row['pid'];
$username=$row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coach-player.php Query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['username'])) {
// Connect to the MySQL database
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE username='$puser' LIMIT 1");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$username = $row["username"];
$pid = $row["pid"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
}
} else {
echo "That player does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
The issue here is that whilst it is defined in username.php, the pid does not get sent over and saved when the rest of the form on coach-home sends. I have tried changing from GET to POST with no avail. I have also just tried using the 'username' instead of 'pid' but I get "That player does not exist."; - meaning no variables outside of the ajax request is sending.
What is it that needs to be altered to save and post the data mentioned?
Looking at your code the $username and $pid variables are not being passed to either coach-home.php or coach-player.php, thus when you try to write to the database the parameter $_GET['username'] or $_GET['pid'] is set (because you have provided an input field in your form), but it has no value! and thus there is no player that exists with an empty pid or username.
Also note that in the form you have specified the method as post, but in the php you are referencing the get hash. If you submit by post you access variables with $_POST, submit with get you access with $_GET.
My suggestion is to use the session hash to store the username and pid of the user.
When the user logs in:
$_SESSION['username'] = 'jonnysmith'
$_SESSION['pid'] = '45'
This will mean when you initiate the database query you will just reference the session value instead of the get value for the parameter.
Delete your input field for username/pid in the form.
Call session_start(); in your config.php file to enable the session hash.
Call session_destroy(); when the user logs out to clear the session hash.
Also you will need to logout and log back in for the changes to take effect and the value of username/pid to be stored in the session hash.
Happy hunting!
Your regex is actually replacing your whole username variable with ''
Based on your comment, I've done a test match with the name 'Radamel Falcao' and echo-ed $puser and I got empty string, so apparently, this regex is your problem.
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);

jQuery Mobile submit with PHP without AJAX and JavaScript

Sorry, I consider myself as a real newbie around jQuery Mobile. I'm not good at all regarding JavaScript. Here's the thing. I want to build a jQuery Mobile site without using AJAX. Just want the nice design from jQuery Mobile and then use PHP to submit forms etc.
I tried to build a simple page that submit first and last name to a MySQL database. It will submit, tell the user that it's submitted and then the user can press [Page 2] to see all the results. Now I use if(isset()) to display the message and else to display the form. So, the user who enter the site will get the form, when press [Submit] he/she will get the message that first and last name was submitted. Then press the button [Page 2] to see all the first and last names.
PHP (index.php)
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add">
</form><br>';
}
Page 2
PHP (page2.php):
$query = $db->query("SELECT * FROM name");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['fname'] . ' ' . $row['lname'] . '<br>';
}
$db = NULL;
echo 'Index';
Let's say I enter "Test" as first and last name. It will echo out "Test Test was added!". If I now press [Page 2] I will see that "Test Test" was added. BUT when I then press [Index] to go back I want it to display the form again, but the message "Test Test was added!" is displayed again instead of the form, why? I have to update the page to get the form. Now, if I enable data-ajax it's working with submitting and back-button. BUT then I have to press update at page2.php when I get there to see all the first and last names. Do I make myself understood what's the problem?
Sorry, really new at jQuery Mobile and I can't find the answer at Google. Everyone is using JavaScript to submit data. Is it possible this way or do I have to learn JavaScript to submit forms? Read somewhere that using buttons instead of submit-buttons affect it.
Thanks in advance! :)
I think you are looking to modify the DOM after the request? So post the form, add the user then display the results without having to click the button.
So on your ajax call use the done function to hide the form and show the results.
Take a look below and let me know if it helps.
EDIT: Added the .on click for the button. You may also want to look at adding a keypress checker to the inputs or an onsubmit on the form.
<div id="content">
<?php
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false" id="contentForm">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add" id="sendButton">
</form><br>';
}
?>
</div>
<script type='text/javascript'>
<!-- https://api.jquery.com/jQuery.ajax/ -->
$('#sendButton').on("click", function(){
$.ajax({
type: "POST",
url: "page2.php",
data: $('#contentForm').serialize()
})
.done(function( msg ) {
$('#content').html( msg );
});
});
</script>

validate captcha before submit

I've use captcha for form registration, within that I have validation engine for form inline validation. I'm stuck in validating the equity of captcha.
<p class="veriText">
<label>Enter the Verification Text </label> <span style="color:red;">*</span>
<input class="validate[required] text-input" type="text" name="captcha" id="captcha" class="text" value="" />
</p>
<img src="<?= get_bloginfo('template_url'); ?>/captcha_code_file.php?rand=<?php echo rand();?>" id='captchaimg'><br/>
PHP validation: (works perfectly)
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
}
But the same thing in js I have tried like
var session = <?php echo $_SESSION['code'] ?>; // this value is different
// from captcha image
Is it possible to validate captcha before submitting the form in Javascript/jQuery?
Assuming the line var session = <?php echo $_SESSION['code'] ?>; is in your html page.
When the page is generated your captcha image script is not invoked and thus $_SESSION['code'] is not initialized. The value you are getting is the code from the previous request to captcha_code_file.php. Once your page is loaded (at-least the html part) and the browser decides to call captcha_code_file.php your captcha image gets invoked and a new $_SESSION['code'] is created.
I don't recommend this, but if you want to get the current $_SESSION['code'] try to use an Ajax request to retrieve the new $_SESSION['code'] from another php file (don't call captcha_code_file.php or your session will be reset again.
Note: Never try to validate your captcha at user end. You are defeating the main purpose of captcha.
Create one ajax request for checking capcha using JavaScript, example is provided below:
var postData = $("form").serialize();
var requestUrl = '/check_capcha.php';
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: requestUrl,
success:function(data){
// success or fail message
}
});
check_capcha.php contains:
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
echo 0;
}else{
echo 1;
}
exit;
You can put the javascript code before (although session is same throughout the page).
Just try a dummy code in a plain file and check the session value
OR
You can use $.ajax() to call PHP page for captcha validation
html look like this
$rand = mt_rand(100000,999999);
<span class="captcha"><?php echo $rand; ?></span>
<input name="captcha" type="text" id="captcha-compare" />
In javascript use something like that for validation engine
$('#frm-register').submit(function() {
if( $('#captcha-compare').val() != $('.captcha').text() ) {
$('#captcha-compare').validationEngine('showPrompt', 'Invalid captcha', 'load');
return false;
}
});
and in php first take $rand in session then submitting capture the input text captcha and session
You can try the below code to validate the captcha or you can also use AJAX code to validate the values before submitting the code.
<script language="JavaScript">
var session = '<?php echo $_SESSION['code'] ?>';
if(Form.captcha.value == session)
{
return true;
}
else
{
Form.submit();
}
</script>

Categories