Add a checkbox option to a PHP/MySQL form - php

I have the following form
<body>
<div class="container">
<div class="title pull-left"><img src="http://www.isfin.ro/images/institutul_de_studii_financiare_ISF.png" width="145px" height="80px" /></div>
<div class="title pull-right"><h1>Actualizare newsletter</h1></div>
</div>
<hr class="featurette-divider"></hr>
<div class="container">
<div class="col-sm-12">
GDPR text goes here
</div>
<div class="form-group">
<label for="email">Email:</label>
<input id="email" class="form-control" type="email" placeholder="Adresa Email">
</div>
<div class="form-group">
<label for="nume">Nume:</label>
<input id="nume" class="form-control" type="text" placeholder="Nume">
</div>
<p>Want to remain subscribed?</p>
<label class="radio-inline">
<input type="radio" name="optradio" value="yes">Yes
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="no">No
</label>
<br><br>
<button type="submit" id="submit" class="btn btn-default btn-block btn-primary">Trimite</button>
<div id="display"></div>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var em = $("#email").val();
var sub = $("#nume").val();
var com = $("#comments").val();
var dataString = 'em1='+ em + '&sub1='+ sub + '&com1='+ com;
if(em==''||sub==''||com=='')
{
$("#display").html("<div class='alert alert-warning'>Please Fill All Fields.</div>");
}
else
{
$.ajax({
type: "POST",
url: "processor.php",
data: dataString,
cache: false,
success: function(result){
$("#display").html(result);
}
});
}
return false;
});
});
</script>
</div>
</body>
And this is the content of processor.php
<?php
include_once('config.php');
$email=mysqli_real_escape_string($con, $_POST['em1']);
$emailclean = filter_var($email, FILTER_SANITIZE_EMAIL, FILTER_FLAG_STRIP_HIGH);
$sub=mysqli_real_escape_string($con, $_POST['sub1']);
$subclean = filter_var($sub, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
//insert into database
mysqli_query($con,"INSERT INTO contact(`email`, `nume`)VALUES('$emailclean','$subclean')");
//send message back to AJAX
echo '<div class="alert alert-success">Preferintele au fost actualizate.</div>';
$con->close();
?>
How can I insert the content of the radio buttons Yes / No into a database field?
My database have the following structure id, email, nume, subscription_status, i need to insert the value from radio buttons into subscription_status (Yes or No value).
Thanks!

Get the value of selected checkbox:
var data = document.querySelector('input[name="optradio"]:checked').value;
Now add this value to your data string which you are sending via ajax:
var dataString = 'em1='+ em + '&sub1='+ sub + '&com1='+ com + '&radio=' + data;
And get the value on PHP/server side:
$radio_value = $_POST['radio'];

Related

jQuery Ajax passing input values from one modal to another

I have a modal for entering user information. A user should be linked to a building. After user information has been entered and submit button has been clicked, I am preventing the default action and am overlaying/showing a building modal over the user modal.
Code for doing so follows.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
}
});
$('#modalConnectBuilding').modal('show');
});
})(window.jQuery);
console.log() logs the input information correctly, however in 'modalConnectBuilding.php' the following does not work:
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
?>
Producing the following errors:
Undefined index: name_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: address_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: city_user in
C:\laragon\www\modals\modalConnectBuilding.php
My intent is to do a classic 'form action="./php/processConnectBuilding.php" method="post"' but would need access to the three undefined variables as seen above. Adding users and buildings works in isolation but not when connected in this way. Any help would be greatly appreciated and if you need any more info, please ask. Thank you!
Code for the form (within the modal) I'm submitting follows (please note, default action is being suppressed by preventDefault() so action attribute is never "called", also the form for connecting a building is basically the same, but the action attribute is not suppressed):
<form role="form" id="formAddUser" action="./php/processAddUser.php" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form role="form" id="formAddUser" action="" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
</body>
</html>
<script>
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: 'tariffdetaildata.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function(data) {
alert(data)
}
});
});
</script>
tariffdetaildata.php
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
Try this way I think you need to open the modal popup once you get the response back from the ajax.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
$('#modalConnectBuilding').modal('show');
$("#modalConnectBuilding .modal-body #name_user").val( name_user);
$("#modalConnectBuilding .modal-body #address_user").val( address_user);
$("#modalConnectBuilding .modal-body #city_user").val( city_user);
}
});
});
})(window.jQuery);

send emails from phonegap android application

I want to send a feedback form from android PhoneGap application i have used following code which is not working
1) i have used bellow Ajax code and JQuery files to send ajax request and HTML form, i want to send the email of 4 html fields
<script type="text/javascript" src="assets/js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/geturi.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
var fullName = $("#fullName").val();
var emailId = $("#emailId").val();
var mobileNo = $("#mobileNo").val();
var message = $("#message").val();
var dataString = "fullName=" + fullName + "&emailId=" + emailId + "&mobileNo=" + mobileNo + "&message=" + message + "&send=";
if ($.trim(fullName).length > 0 & $.trim(emailId).length > 0 & $.trim(mobileNo).length > 0 & $.trim(message).length > 0) {
$.ajax({
type: "POST",
url: "https://www.activebittechnologies.com/phonegap/mail.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#send").val('Sending Enquiry...');
},
success: function(data) {
if (data == "success") {
alert("Mail Sent");
$("#send").val('submit');
} else if (data == "error") {
alert("error");
}
}
});
}
return false;
});
});
</script>
<div class="content form">
<div class="header">
<div class="header-overlay"></div><img src="assets/banner/5.jpg">
<div class="info">
<h3 class="title">Send Contact Enquiry</h3>
<span data-close="#enquirepop" class="closeit"><i class="fa fa-times" aria-hidden="true"></i></span>
</div>
</div>
<div class="form-group">
<input id="fullName" name="fullName" type="text" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input id="emailId" name="emailId" type="text" class="form-control" placeholder="Email Id">
</div>
<div class="form-group">
<input id="mobileNo" name="mobileNo" type="text" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Your Message" style="color:#fff;"></textarea>
</div>
<div class="text-right">
<input type="button" id="send" class="btn btn-primary" value="Send">
</div>
</div>
unable to go on this page from phone gap when installed on android phone bellow is php script which is on server
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
$toEmail = "hotelinkonkan#gmail.com";
$mailHeaders = "From: " . $_POST["fullName"] . "<". $_POST["emailId"] .">\r\n";
$sentml=mail($toEmail, $_POST["fullName"], $_POST["message"], $mailHeaders);
if($sentml)
echo"success";
else
echo"error";
?>
I use $("#form1").serialize() to get all the values from the form, and I validate the values on the server side. You should always validate your values server side, because users can send a direct post to your php without any javascript validation.
Hope it helps.
<script type="text/javascript" src="assets/js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.js"></script>
<script type="text/javascript" src="assets/js/geturi.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
$.ajax({
type: "POST",
url: "https://www.activebittechnologies.com/phonegap/mail.php",
data: $("#form1").serialize(),
crossDomain: true,
cache: false,
beforeSend: function() {
$("#send").val('Sending Enquiry...');
},
success: function(data) {
console.log(data);
if (data == "success") {
alert("Mail Sent");
$("#send").val('submit');
} else if (data == "error") {
alert("error");
}
}
});
return false;
});
});
</script>
<form id='form1' >
<div class="content form">
<div class="header">
<div class="header-overlay"></div><img src="assets/banner/5.jpg">
<div class="info">
<h3 class="title">Send Contact Enquiry</h3>
<span data-close="#enquirepop" class="closeit"><i class="fa fa-times" aria-hidden="true"></i></span>
</div>
</div>
<div class="form-group">
<input id="fullName" name="fullName" type="text" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input id="emailId" name="emailId" type="text" class="form-control" placeholder="Email Id">
</div>
<div class="form-group">
<input id="mobileNo" name="mobileNo" type="text" class="form-control" placeholder="Mobile No">
</div>
<div class="form-group">
<textarea class="form-control" id="message" name="message" placeholder="Your Message" style="color:#fff;"></textarea>
</div>
<div class="text-right">
<input type="button" id="send" class="btn btn-primary" value="Send">
</div>
</div></form>

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.

ajax code not work for 2nd list

my code works fine for the first list. But not work even other list if has more list. Could you please find out what happened with my code.
if I click on signOut it will be add to database and remove form the page with signOut value only. First Div list work,But other will not response anything.
Thank You
Here is my code:
Java Script Code:
$(function() {
$("#add").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("dataid");
var outime = $(this).parents("#list").find("#outtime").val();
//Built a url to send
var info = 'id=' + del_id+ '&singout=' + outime;
$.ajax({
type: "POST",
url: "signOut.php",
data: info,
success: function(){
}
});
// After success
$(this).parents("#list").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
});
});
HTML COde:
<?php
$comments = runQuery($conn, "SELECT * FROM `civ_in_out` WHERE `out_time` = 'null'");
//print_r($comments) ;
if(!empty($comments)) {
foreach($comments as $k=>$v) {
?>
<div id="list">
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<input class="form-control" type="text" name="name" value="<?php echo $comments[$k]['name']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control" type="time" name="signIn" value="<?php echo $comments[$k]['in_time']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control" id="outtime" type="time" name="singOut">
<input class="form-control" id="id" type="hidden" name="id" value="<?php echo $comments[$k]['id']; ?>">
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-block" dataid="<?php echo $comments[$k]['id']; ?>" id="add" >Sign Out</a>
</div>
</div>
</div>
</div>
<?php
} }
?>
signOut.php
include 'connect.php';
$data=$_POST['serialize'];
echo $id = $data['id'];
echo $outtime = $data['singout'];
$sql = "UPDATE `civ_in_out` SET `out_time`='$outtime' WHERE id = '$id'";
mysqli_query($conn, $sql);
The problem is that you are repeating the list id and all the other element ids, so the jQuery call and event binding will always refer to the first id found on the HTML.
Id’s must be unique on you html.
You can change your code to use a class name for example:
$(function() {
$(".add").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("dataid");
var outime = $(this).parents(".list").find(".outtime").val();
//Built a url to send
var info = 'id=' + del_id+ '&singout=' + outime;
$.ajax({
type: "POST",
url: "signOut.php",
data: info,
success: function(){}
});
// After success
$(this).parents(".list").animate({ backgroundColor: "#fbc7c7" }, "fast").animate({ opacity: "hide" }, "slow");
});
});
HTML/PHP:
<?php
$comments = runQuery($conn, "SELECT * FROM `civ_in_out` WHERE `out_time` = 'null'");
//print_r($comments) ;
if(!empty($comments)) {
foreach($comments as $k=>$v) {
?>
<div class="list">
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<input class="form-control" type="text" name="name[]" value="<?php echo $comments[$k]['name']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control" type="time" name="signIn[]" value="<?php echo $comments[$k]['in_time']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control outtime" id="outtime-<?=$k?>" type="time" name="singOut[]">
<input class="form-control" id="id-<?=$k?>" type="hidden" name="id[]" value="<?php echo $comments[$k]['id']; ?>">
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-block add" dataid="<?php echo $comments[$k]['id']; ?>>Sign Out</a>
</div>
</div>
</div>
</div>
<?php
} }
?>
You can change $("#add").click(function() to $(document).on('click', '#add', function()

Jquery ajax posts twice

I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice

Categories