I'm processing a form using PHP and JQuery and it's not processing the way it should normally process. My HTML is:
<form action="" method="POST" name="forgot_pass_form">
<label><h3>Please Enter your email!</h3></label><br>
<input type="text" name="email_pass" id="email_pass" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
My JQuery code which is in the same page as HTML code:
<script type="text/javascript">
$(document).ready(function($) {
var email = $('#email_pass').val();
$("#submit").live('click', function(){
$.post('email_password.php',
{
'email_pass' : email
},
function(data) {
alert(data);
});
return false;
});
});
</script>
My PHP code which is on email_password.php:
<?php
$email = $_POST['email_pass'];
if(empty($email)){
echo 'empty';
} else {
echo 'Not';
}
?>
The problem here is it always alert me with empty even if I've entered something in the text box
I even tried this way:
if(empty($_POST)){
echo 'empty';
} else {
// process the form
$email = $_POST['email'];
if(empty($email)){
echo 'Email is empty';
} else {
echo 'Email is not empty';
}
}
By trying this way, it alerts me with Email is empty. Please help
When you try to capture a field value, it must be the same name. The name you have in your form is 'email_pass' and in your PHP code you are waiting for 'email'
This should be:
if(empty($_POST)){
echo 'empty';
} else {
// process the form
$email = $_POST['email_pass']; // The field form name
if(empty($email)){
echo 'Email is empty';
} else {
echo 'Email is not empty';
}
}
Sorry for my english :s
use this code
<script type="text/javascript">
$(document).ready(function($) {
$("#submit").live('click', function(){
var email = $('#email_pass').val();
$.post('email_password.php',
{
'email_pass' : email
},
function(data) {
alert(data);
});
return false;
});
});
</script>
The issue is that your making a $_POST call with jQuery and in that function you "post" under the new name email_pass. Update your PHP file to reference $_POST['email_pass'] and you'll be good to go.
Use 0n() and get email value inside the click function
<script type="text/javascript">
$(document).ready(function($) {
$("#submit").on('click', function(){
var email = $('#email_pass').val();
$.post('email_password.php',
{
'email_pass' : email
},
function(data) {
alert(data);
});
return false;
});
});
</script>
Related
Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.
Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");
HTML code:
<div class="small-3 columns">
<input type="submit" id="join" class="button postfix " value="Join »">
<span id="error"></span>
</div>
I am using jQuery ajax post data method to print "Subscription successful" when user clicks on join button.
jQuery code:index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#join").click(function() {
var vemail = $("#emailaddy").val();
if(vemail=='') {
alert("Please enter email address");
} else {
$.post("join.php", //Required URL of the page on server
{
// Data Sending With Request To Server
emailaddy:vemail
},
/*function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
$("#form")[0].reset();
});*/
}
$("#error").text("hello");
});
});
</script>
I have created another page which is requested by index.php.
<?php
if($_POST["emailaddy"])
{
$email = $_POST["emailaddy"];
// Here, you can also perform some database query operations with above values.
echo "Welcome ". $email ."!"; // Success Message
}
?>
You can uncomment this
/*function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
$("#form")[0].reset();
and if the response is true show a div with a "Subscription successful" text-message.
Close $.post() method properly.And set subscription message from function inside post method.Like this..
$.post("join.php", //Required URL of the page on server
{ // Data Sending With Request To Server
emailaddy:vemail
},
function(response,status){
alert(response);//alerts welcome email..
$("#error").text("Subscription successful");
$("#form")[0].reset();
});*/
First of all make a file named functions.php if you dont have one.
Then make a function SetFormMsg($msg) and one ViewFormMsg().
Code:
function SetFormMsg($msg) {
if(!isset($_SESSION)){
session_start();
}
$_SESSION['formMsg'] = $msg;
}
function ViewFormMsg() {
if(!isset($_SESSION)){
session_start();
}
if(isset($_SESSION['formMsg'])
{
$message = $_SESSION['formMsg'];
}
else
{
$message = "";
}
return $message
}
and in your html code at the end of the form make a element that contains:
*If you want all of these to work include the 'functions.php' at the beginning of both html and php/sql documents.
Try the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#join").click(function(){
var vemail = $("#emailaddy").val();
if(vemail=='')
{
alert("Please enter email address");
}
else{
$.post( "join.php",{ 'emailaddy': vemail})
.done(function( data ) {
$("#error").html(data);
$("#success").html('Subscription successful');
});
}
});
});
</script>
<div class="small-3 columns">
<span id="success"></span>
<input type="email" name="emailaddy" id="emailaddy">
<input type="submit" id="join" class="button postfix " value="Join »">
<span id="error"></span>
</div>
If the response is success you can use .html instead of .text
$("#error").html("Subscription successful"); for $("#error").text("Subscription successful");
I am doing form validation through ajax and php and it works fine.
Now there are two files i.e., ajax.html and codeValidate.php.
html form is in ajax and it checks the code validation using another file i.e. codeValidation.php.
Now I would like to have both in the same file and name it as Ajax.php. The code is as below.
//Ajax file
<html>
<form id="form_submit">
<input id="coupon" name="coupon" type="text" size="50" maxlength="13" />
<input id="btn_submit" type="button" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("form_submit").submit(function(e){ e.preventDefault(); return false;});
$("#btn_submit").click(function(e) { e.preventDefault();
var coupon = $("#coupon").val();
// validate for emptiness
if(coupon.length < 1 ){ window.location.href="success.html"; }
else{
$.ajax({
url: './codeValidate.php',
type: 'POST',
data: {coupon: coupon},
success: function(result){
console.log(result);
if(result){ window.location.href="success.html"; }
else{ alert("Error: Failed to validate the coupon"); }
}
});
}
});
</script>
</html>
My working php file :-
<?php
require("dbconfig.php");
if(isset($_POST['coupon']) && !empty($_POST['coupon']) ){
$coupon = trim($_POST['coupon']);
$checkcoupon = "SELECT couponCode FROM cc WHERE couponCode='".$coupon."'";
$results_coupon = mysqli_query($dbc,$checkcoupon);
if(mysqli_num_rows($results_coupon)) { echo true; }
else { echo false; }
}
?>
I'm new with PHP and JavaScript. I eant to validate form, and if the form input fields are correct, then send it to php external script. I've tried something like this:
<head>
<script type="text/javascript">
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
} else if(y==null || y=="") {
alert("Input surname!");
} else if(z==null || z=="") {
alert("Input age!");
} else {
// IS IT POSSIBLE TO SEND FORM HERE FORM VARIABLES TO PHP SCRIPT?
}
}
</script>
</head>
<body>
<form name="forma" action="validate.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
Since you are not returning false from your function, the form should be being submitted anyway. You can stop it from being submitted by having your validate() function return false.
Your code looks correct, other than the fact you probably want to return false on failure to prevent the form from submitting. When not returning false, the form will simply continue to submit.
I also think you probably meant to name your form form not forma
You should validate the input server-side (php), even if you did it client-side (javascript).
You do this by checking on $_POST in validate.php:
Quite at the beginning of your script:
if (isset($_POST)) { // form has been sent
if (!isset($_POST['firstname']) || strlen($_POST['firstname'])==0) { // no entry
$e['firstname']='please enter a firstname!'; // prepare error-msg
}
if (!isset($e)) { // no error, continue handling the data
// write data to database etc.
}
}
// in your form...
if (isset($e)) echo "there were errors: ". implode(',',$e);
You need to put this code:
function Validate(){
var x=document.forms["form"]["firstname"].value;
var y=document.forms["form"]["lastname"].value;
var z=document.forms["form"]["age"].value;
if(x==null || x=="") {
alert("Input name!");
return false;
} else if(y==null || y=="") {
alert("Input surname!");
return false;
} else if(z==null || z=="") {
alert("Input age!");
return false;
} else {
return true;
}
}
I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>