Html form refuses to be submitted via JQuery - javascript

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>

The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

Related

Provide a valid password before proceeding (Codeigniter)

Newbie here. I have a modal where staff can transfer fund to a client. Before transferring fund, the staff must input his/her password before proceeding to transaction. My goal is to have a WORKING FUNCTION about the password validation. I made a slightly working function. I have provided a video below for better explanation.
https://streamable.com/z4vgtv //Correct or wrong password, the result is the same. "Password not match"
Controller:
public function form_validation($userID)
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$password = $this->input->post('password');
$exists = $this->networks->filename_exists($password);
$count = count($exists);
if($count >=1)
{
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI-0000' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
?>
<script> alert("password match");</script>
<?php
$this->networks->insert_data($data1);
redirect(base_url() . "network/agents");
}
else
{
$this->index();
}
}
else
{
?>
<script> alert("Password not Match");</script>
<?php
}
}
Model:
function filename_exists($password)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('password', $password);
$query = $this->db->get();
$result = $query->result_array();
return $query->result();
}
Views:
<form id="doBetting" method="post" action="<?php echo base_url('network/form_validation');?>/<?php echo $rows->userID; ?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<div class="col-lg-12" >
<input type="number" placeholder="Enter Amount" name="amount" class="form-control" id="box" required>
<br>
<input type="password" placeholder="Enter Password" name="password" class="form-control" id="cpass" required onblur="check_if_exists();">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Ajax:
<script>
<script>
function check_if_exists() {
var password = $("#cpass").val();
$.ajax(
{
type:"post",
url: "<?php echo site_url(); ?>network/form_validation",
data:{password:password},
success:function(response)
{
// remove alert();
}
});
}
check_if_exists();
</script>
User always saved password on database with encoded form,but in your case,firstly you need to encode your password(format md5 or which format you are using to encode) and then check with your user password.
public function form_validation($userID)
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$password = md5(trim($this->input->post('password')));
$exists = $this->networks->filename_exists($password);
.........
}

Hide error text until box / button clicked on

I'm wanting the errName errEmail errMessage text to not be displayed until the user clicks on the Name, Email, or Message box. Also I'm wanting to not show $result until the submit button is pressed. As of right now it just displays the errName, errEmail, errMessage, and the alert even if the user is not interacting with the submit form.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
global $result;
if (isset($_POST["submit"])) {
$errName ="";
$errEmail ="";
$errMessage ="";
$result="";
$name = $_POST['name'];
$business = $_POST['business'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = '------';
$to = '-----';
$subject = 'Message from user on website';
$body ="-------";
}
// Check if name has been entered
if (!isset($_POST) || !key_exists('name', $_POST) || !filter_var($_POST['name'])) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST) || !key_exists('email', $_POST) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST) || !key_exists('message', $_POST) || !filter_var($_POST['message'])) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!isset($errName) && !isset($errEmail) && !isset($errMessage)) {
$result .= '<br><div class="alert alert-success">Thank You! We will be in touch</div>';
} else {
$result .= '<br><div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
}
<div class="container" id="contact">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<h1 class="page-header text-center">Email Form</h1>
<form class="form-horizontal" role="form" method="post" action="index.php#contact">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php showPost('name'); ?>">
<?php if (isset($errName)) {
echo "<p class='text-danger'>$errName</p>";
}?>
</div>
</div>
<div class="form-group">
<label for="business" class="col-sm-2 control-label">Business</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="business" name="business" placeholder="Business name" value="<?php showPost('business'); ?>">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="example#domain.com" value="<?php showPost('email'); ?>">
<?php if (isset($errEmail)) {
echo "<p class='text-danger'>$errEmail</p>";
}?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea class="form-control" rows="4" name="message"><?php showPost('message');?></textarea>
<?php if (isset($errMessage)) {
echo "<p class='text-danger'>$errMessage</p>";
}?>
</div>
</div>
<div class="form-group text-xs-center">
<div style="margin: 0 auto" class="g-recaptcha" data-sitekey="----------"></div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
</div>
</div>
</form>
</div>
</div>
</div>```
You need to put all your php code inside if (isset($_POST["submit"])) ,because the condition !isset will always be true when you load your php page . Do below change in your code :
if (isset($_POST["submit"])) {
$errName ="";
$errEmail ="";
$errMessage ="";
$result="";
$name = $_POST['name'];
$business = $_POST['business'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = '------';
$to = '-----';
$subject = 'Message from user on website';
$body ="-------";
// Check if name has been entered
if (!isset($_POST) || !key_exists('name', $_POST) || !filter_var($_POST['name'])) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!isset($_POST) || !key_exists('email', $_POST) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
//Check if message has been entered
if (!isset($_POST) || !key_exists('message', $_POST) || !filter_var($_POST['message'])) {
$errMessage = 'Please enter your message';
}
// If there are no errors, send the email
if (!isset($errName) && !isset($errEmail) && !isset($errMessage)) {
$result .= '<br><div class="alert alert-success">Thank You! We will be in touch</div>';
} else {
$result .= '<br><div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
}
} // end of isset

PHP,jQuery,HTML form with ajax is not working

I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax
From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH

Perform two task with jQuery and php

I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.

Ajax URL with variable form location

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.
I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.
This should be the minimum needed code to show my issue.
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
echo json_encode($errors);
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "action.include.php",
dataType: "json",
success: function(data){
alert(data);
}
})
});
</script>
<!-- END Action Form -->
My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.
My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.
not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php
Try with this...
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
exit(json_encode($errors)); // exit so it doesn't send the form below
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$("#actionForm").on('submit', function(event){
event.preventDefault(); // so it doesnt reload the page
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
dataType: "json",
success: function(data){
alert(data);
}
});
});
</script>
<!-- END Action Form -->
Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?
EDIT:
Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

Categories

Resources