Submitting radio button using ajax and php into mysql database - php

I am working with sweetalert2 two trying to submit form data including radio button. I find that the other fields are recorded in the database but can find the radio button values. Can somebody help? Check the code below.
This is the form
<form class="login" method="post" action="register.php">
<h5>Please Sign Up</h5>
<div class="form-group">
<input id="f_name" class="form-control" type="text" name="f_name" placeholder="Your First Name" required>
<input id="l_name" class="form-control" type="text" name="l_name" placeholder="Your Last Name" required>
<input id="email" class="form-control" type="email" name="email" placeholder="Your email address" required>
<input id="pass" class="form-control" type="password" name="pass" placeholder="Your password" required>
<h4>I want to :</h4>
<div class="radio-toolbar">
<input class="user" type="radio" name="user" id="user1" value="user1">
<label class="radio-label" for="writer">User 1</label>
<input type="radio" name="user" id="user2" value="user2">
<label class="radio-label" for="client">User 2</label>
</div>
<button class="btn btn-secondary" name="submit" id="register">Sign Up</button>
</div>
<h6><span>Have an account?</span> </h6>
Log In
</form>
External js is this
$(function() {
$('#register').click(function(e){
var valid = this.form.checkValidity();
if (valid) {
var f_name = $('#f_name').val();
var l_name = $('#l_name').val();
var email = $('#email').val();
var pass = $('#pass').val();
var user = $("input[name='user']:checked").val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'process.php',
data: {f_name:f_name,l_name:l_name,email:email,pass:pass, user:user},
success:function(data){
Swal.fire({
icon: 'succes',
title: 'Check the below message',
text: data,
footer: 'Please Sign In'
})
},
error:function(data){
Swal.fire({
icon: 'error',
title: 'Errors',
text: data,
footer: '<a href>Why do I have this issue?</a>'
})
}
});
}else{
}
});
});
The php code is here
require_once('./config/db.php');
if (isset($_POST)){
$f_name = $_POST['f_name'];
$l_name = $_POST['l_name'];
$email = $_POST['email'];
$pass = sha1($_POST['pass']);
$user = $_POST['user'];
$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user) {
echo "Email already exists in the database! Please use another email!";
} else {
$sql= "INSERT INTO users(f_name,l_name,email,pass,user) VALUES(?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$results = $stmt->execute([$f_name,$l_name,$email,$pass,$user]);
if ($results) {
echo "Your registration has been submitted successfully.";
}else{
echo "There were errors while saving the data.";
}
}
}
?>
Please assist. I have been trying some of the solutions in the stackoverflow but can't get any help.

Related

cant send data using ajax showing some localhost alert(php)

I wrote a script which doesn't send the data from the AJAX to the PHP file. and showing error in alert box
HTML
<form id="contact-form" action="#" method="post">
<div class="single-contact-form">
<div class="contact-box name">
<input type="text" name="name" id="name" placeholder="Your Name*" style="width:100%">
</div>
</div>
<div class="single-contact-form">
<div class="contact-box name">
<input type="text" name="email" id="email" placeholder="Your Email*" style="width:100%">
</div>
</div>
<div class="single-contact-form">
<div class="contact-box name">
<input type="text" name="phone" id="phone" placeholder="Your Mobile*" style="width:100%">
</div>
</div>
<div class="single-contact-form">
<div class="contact-box name">
<input type="text" name="password" id="password" placeholder="Your Password*" style="width:100%">
</div>
</div>
<div class="contact-btn">
<button type="submit" name="register" id="register" class="fv-btn" >Register</button>
</div>
</form>
JS
<script>
$(function(){
$("#register").on("click",function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var password = $("#password").val();
if( name == "" || email == "" || phone == "" || password == ""){
alert("all field required");
}else{
$.ajax({
data: "ajax.php",
type: "POST",
data:{cname:name,cemail:email,cphone:phone,cpassword:password},
success: function (result) {
alert(result);
$("#contact-form").trigger("reset");
}
});
}
});
});
</script>
php
<?php
include "../inc/database1.php";
$name = $_POST['cname'];
$email = $_POST['cemail'];
$phone = $_POST['cphone'];
$password =$_POST['cpassword'];
$sql = "INSERT INTO tbl_user (name,email,phone,password) values('$name','$email','$phone','$password')";
$value = $this->db->conn->prepare($sql);
$data = $value->execute();
if($data == TRUE){
echo "successfully register";
}else{
echo "not sent";
}
?>
you have to do some changes in your ajax as you do not mention the url of ajax where it post the data and the variable data is reinitialised.
try this:
$.ajax({
url: "ajax.php", // its url you need to add
type: "POST",
data:{cname:name,cemail:email,cphone:phone,cpassword:password},
success: function (result) {
alert(result);
$("#contact-form").trigger("reset");
}
});
hope this helps you.

Ajax request is retrieving an empy array in PHP

I have a "form" with this code:
<div class="form-wrap" id="contact-form">
<div class="form-innerwrap">
<div class="text-input">
<input type="text" name="name" id="name" required />
<label for="name"><?= CONTACT_FORM_NAME ?></label>
</div>
<div class="text-input">
<input type="email" name="email" id="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<label for="email">E-mail</label>
</div>
<div class="text-input">
<input type="text" name="contact" id="contact" required />
<label for="name"><?= CONTACT ?></label>
</div>
<div class="text-input text-textarea">
<textarea type="info" id="info" name="info">
</textarea>
<label for="email"><?= CONTACT_FORM_MENSSAGE ?></label>
</div>
<input type="hidden" name="lang" id="lang" value="<?= $_SESSION['language'] ?>">
<div class="form-button">
<button type="submit" class="btn contacts-button btn-gowe" id="btn-info" data-btnhover="<?= CONTACT_FORM_BTN ?>"> <span><?= CONTACT_FORM_BTN ?></span> </button>
</div>
</div>
</div>
Then I have a ajax request to sent the input values to php:
$("#btn-info").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var contact = $("#contact").val();
var info = $("#info").val();
var lang = $("#lang").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name='+ name + '&email='+ email +'&contact='+contact+'&info='+info+'&lang='+lang;
$.ajax({
type: "POST",
url: "includes/sendEmail.php",
data: dataString,
cache: false,
success: function(result){
var result = result.split("||");
if (result[0]== "true"){
$("#contact-modal").show();
}
}
});
return false;
});
However when I make a var_dump of $REQUEST the return is an empty array.
Can anyone help me with this problem?
I had already spent several hours to try to understand what is wrong in my code.
Thanks for helping.

Submitting a form without reloading the page

I have a form which works fine but after submitting it reloads the page. I want it to display the message under the form instead of reloading the page.
Here is my html code:
<form class=" form-horizontal" action="php/contact.php" method="post" id="contact_form" name="contact-form">
<fieldset>
<div class="form-group">
<input name="firstname" placeholder="First Name" class="form-control" type="text">
<input name="lastname" placeholder="Last Name" id="lastname" class="form-control" type="text">
<input name="email" placeholder="E-Mail Address" class="form-control" type="text">
<input type="text" name="mail"> <!-- anti spam - needs to stay non-filled - hidden by css -->
<input name="phone" placeholder="(+44) 020 1234 5678" class="form-control" type="text">
<input name="company" placeholder="Company name" class="form-control" type="text">
<input name="website" placeholder="Website or domain name" class="form-control" type="text">
<textarea class="form-control" name="message" placeholder="Your message"></textarea>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">
Thanks for contacting us, we will get back to you shortly.</div>
<button type="submit" class="btn btn-block btn-primary">Send <span class="fa fa-fw fa-lg fa-send"></span> </button>
</div>
</fieldset>
</form>
I also use jquery validation scripts and this is a quick summary to this script ( I believe the most of changes need to be done here):
$(function() {
$("form[name='contact-form']").validate({
rules: {
firstname: "required",
message: "required",
email: {
required: true,
email: true
},
},
messages: {
firstname: " Please enter your firstname",
email: " Please enter a valid email address",
message: " Please type your message"
},
submitHandler: function(form) {
form.submit();
}
});
});
And this is a php code, which reloads the page after submitting:
<?php
$adresdo = "info#tucado.com";
$temat = "Message from tucado.com";
$zawartosc = "First Name: ".$_POST['firstname']."\n"
."Last Name: ".$_POST['lastname']."\n"
."Company: ".$_POST['company']."\n"
."Email: ".$_POST['email']."\n"
."Telephone: ".$_POST['phone']."\n"
."Website: ".$_POST['website']."\n"
."Message: ".$_POST['message']."\n";
if(!$_POST['firstname'] || !$_POST['email'] || !$_POST['message']){
header("Location: ../contact.html");
exit;
}
$email = $_POST['email'];
if(mail($adresdo, $temat, $zawartosc, 'From: Contact <'.$email.'>')){
header("Location: ../msg-sent.html");
}
?>
Could you please help me in modifying this code to display a message (id="success_message") when the message is sent? Thank you for your help.
Try ajax submission. put ajax code inside submit handler, use serialise or formdata to fetch the whole form .See example.
submitHandler: function(form) {
$.ajax({
url: "name_of_file.php",
type: "POST",
data: new FormData($(form)),
cache: false,
success: function(data) {
$("#success_message").html(data);
}
});
return false;
},
echo desired output in the php file so as to retreive it in data.

No recaptcha in POST var being sent

The code below is the code for my form on my webpage, then test.php. The issue is there is no recaptcha var being sent in the $_POST. I have ensured the tag for the recaptcha is with in the form tag, the call to googles .js is in the head. I cannot find the reason my form is not sending the var.
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<div id="contact" class="form-contain">
<fieldset>
<div id="message"></div>
<form method="post" action="js/test.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="g-recaptcha" data-sitekey="6LcMRQ0UAAAAACB1GVYh0oIQezzFcNmpsy0a7Sqx"></div>
<div class="form-group">
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</fieldset>
</div>
test.php:
<?php
$email;$comment;$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['comment'])){
$email=$_POST['comment'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "Put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
} else {
echo '<h2>Thanks for posting comment.</h2>';
}
?>
After looking at your website that you provided in the comments, I noticed your submit form handler is only submitting 4 fields (name, email, phone, and comments). This needs to be modified to include g-recaptcha-response.
From http://zacktarrcreations.com/AFK/js/plugins.js on line 1141:
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(500,function() {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
Change to:
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(500,function() {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
"g-recaptcha-response": $('#g-recaptcha-response').val(),
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
Tested and it worked for me.

Contact Form Not Working JS/PHP

I'm having trouble getting this contact form working on an HTML site and I can't figure out why :/
I manage to get the email to my mailbox, but it only displays the subject (which isn't that useful as it's plain text, and sometimes I get the name.
Thanks in advance if you can help.
DIV:
<div id="contactForm" class="shadow">
<div class="sepContainer"></div>
<form action="process.php" method="post" id="contact_form">
<div class="name">
<label for="name">Your Name:</label>
<p> Please enter your full name</p>
<input id="name" name="email" type="text" placeholder="e.g. Mr. John Smith" required />
</div>
<div class="email">
<label for="email">Your Email:</label>
<p> Please enter your email address</p>
<input id="email" name="emai" type="email" placeholder="example#domain.com" required />
</div>
<div class="message">
<label for="message">Your Message:</label>
<p> Please enter your question</p>
<textarea name="messagetext" id="message" cols="30" rows="4"></textarea>
</div>
<div id="loader">
<input type="submit" value="Submit" />
</div>
</form>
</div>
JS:
// Activate the contactform
$(document).ready(function() {
$(function(){
$('#contact_form').submit(function(e){
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader', form).html('<img src="images/loader.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
});
});
PHP:
<?php
$toemail = 'myemailaddress#whatever.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if(mail($toemail,'CFUSU Online',$message,'From:'.$email)) {
echo 'Your email was sent succesfully.';
} else {
echo 'There was a problem sending your email.';
}
?>
Correct php code
$toemail = 'myemailaddress#whatever.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['messagetext'];
if(mail($toemail,'CFUSU Online',$message,'From:'.$email)) {
echo 'Your email was sent succesfully.';
} else {
echo 'There was a problem sending your email.';
}

Categories