Trying to submit a form to MySql with AJAX - javascript

I am trying to post from a form to SQL by using Ajax.
However, when clicking the button to submit the form, no error is shown in the chrome console and it looks like the PHP is also not being called in the network tab. Could anyone please help me out or point me in the right direction?
HTML
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/signup.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body background-color="#000000">
<section class="section section-full bg-secondary overflow-hidden z-2">
<div class="container z-2">
<div class="row justify-content-center pt-6 pt-md-5 pb-0 mb-2">
<div class="col-12 col-xl-7">
<div class="card card-tertiary">
<div class="card-header text-center">
<span>Register</span>
</div>
<div class="card-body">
<p class="font-weight-bold">
</p>
<p class="card-text text-center">
Please enter your Email:
</p>
<form class="d-flex justify-content-between mb-2" method="POST" name="email-form" id="email-form">
<div id="name-group" class="form-group">
<p>Name: <input type="text" id="uname" name="uname" class="form-control w-75" required/>
</div>
<div id="email-group" class="form-group">
<p>Email: <input type="text" id="uemail" name="uemail" class="form-control w-75" required/>
</div>
<div class="form-group">
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="button" action="submit" id ="submit" name="submit">
<span class="btn-text">Sign-Up</span>
</button>
</div>
<div id="message"></div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
signup.js Javascript
$(document).ready(function() {
$('#email-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: 'emailsend.php',
data: {
'uname': $('#uname').val(),
'uemail': $('#uemail').val()
}
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
if(result == 1) {
str = 'User record saved successfully.';
} else if( result == 2) {
str == 'All fields are required.';
} else{
str = 'User data could not be saved. Please try again';
}
$("#message").css('color', 'red').html(str);
})
})
});
emailsend.php PHP
<?php
$dbhost = "localhost";
$dbuser = "------";
$dbpass = "------";
$db = "signup";
$data = '';
$result = 0;
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connect failed: %s\n". $conn -> error);
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$uname = $_POST['uname'];
$email = $_POST['uemail'];
/* validation */
if(!$uname || !$email){
$result = 2;
}elseif (!strpos($email, "#") || !strpos($email, ".")) {
$result = 3;
}else {
//SQL query to get results from database
$sql = "INSERT INTO emails (name, email) VALUES ('$uname', '$email')";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $uname, $email);
if($stmt->execute()){
$result = 1;
}
}
echo $result;
$conn->close()
?>

since you have
$(document).ready(function() {
$('#email-form').submit(function(e) {
and
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="button" action="submit" id ="submit" name="submit">
i dont see how will be submited when button type is not submit
change the button type to submit like this
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="submit" action="submit" id ="submit" name="submit">

First, change your button type attribute to submit instead of button:
<button class="btn btn-sm mr-2 btn-tertiary border-dark" type="submit" action="submit" id ="submit" name="submit">
Second, change your JQuery version as
Bootstrap's JavaScript version 3.3 requires jQuery version
1.9.1 or higher, but lower than version 3

Related

JsTree submit form when a node is selected

I am using JsTree to create a tree structure to display folder hierarchical order.
What I want to do is, when the user selects a node and move button is clicked, a form will be submitted.
<?php
echo $this->Form->create("MediaDirectory", ['type' => 'post', 'class' => 'form-horizontal','autocomplete' => "off",'novalidate' => "novalidate"]);
?>
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="col-4 col-form-label">Testing</label>
<div class="col-8">
<?php
$folderData = $hah;
$folders_arr = array();
foreach($folderData as $row)
{
$parentid = $row['MediaDirectory']['parent_id'];
if($parentid == null) $parentid = "#";
$folders_arr[] = array(
"id" => $row['MediaDirectory']['id'],
"parent" => $parentid,
"text" => $row['MediaDirectory']['name'],
);
}
?>
<div id="folder_jstree"></div>
<textarea id='txt_folderjsondata' hidden><?= json_encode($folders_arr) ?></textarea>
</div>
</div>
</div>
</div>
<button type="button" name="cancel" class="btn btn-secondary btn-rounded btn-bordered waves-effect" onclick="window.history.back();">Cancel</button>
<button type="submit" name="submit" class="btn btn-primary btn-rounded waves-effect waves-light">Move</button>
<?php echo $this->Form->end(); ?>
Script
<script type="text/javascript">
$(document).ready(function(){
var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());
$('#folder_jstree').jstree({ 'core' : {
'data' : folder_jsondata,
'multiple': false
} });
});
</script>
I don't have any experience expereience with Javascript and JsTree. Can someone help me.

Submitted Information from a Modal Into mySQL

I was having some problems submitted information from a modal into mySQL, this is what I have tried.
<script>
var cells = document.querySelectorAll('.table-row > td');
var cellIndex = -1;
cells.forEach((e, index) => {
e.addEventListener("click", () => {
//show modal
$('.modal').modal("show");
//update grid
// This is the row number
console.log("Row number: ", index)
cellIndex = index
})
})
function updateTable(e) {
let name, email, phonenumber, tableRow, row;
name = document.getElementById("name").value;
console.log(name, email, phonenumber);
// Get the row that you want
row = cells[cellIndex];
$(row).html(name);
$('.modal').modal("hide");
}
document.getElementById("submit-btn").addEventListener("click", updateTable);
//store in database
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
alert('form was submitted');
}
})
</script>
This is my insert.php:
<?php
$conn = new
mysqli("127.0.0.1","root","password");
if($conn->connect_error){
die("Connection failed: " . $conn-
>connect_error);
}
if(!empty($_POST))
{
$output = '';
$name =
mysqli_real_escape_string($connect,$_POST["name"]);
$phonenumber =
mysqli_real_escape_string($connect,$_POST["phonenumber"]);
$email =
mysqli_real_escape_string($connect,$_POST["email"]);
$query = "INSERT INTO users(name,phonenumber,email) VALUES('$name',
'$phonenumber','$email' )";
}
echo "Connected successfully";
?>
My understanding of the problem is that I need to use ajax to send a request to the web server that would store the information from the modal to the mySQL database with the given query in php. Perhaps I don't have a good understanding of the problem. I am not sure how to get the values from the modal, and in conjuction use ajax to send a post to the server. Any help would be appreciated.
Here is my Modal:
<div class="row">
<div class="col-md-12">
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1>Reservation</h1>
</div>
<div class="modal-body">
<input type="text" name="field1" placeholder="Name" id="name">
<input type="text" name="field2" placeholder="Email" id="email">
<input type="text" name="field3" placeholder="PhoneNumber" id="phonenumber">
</div>
<div class="modal-footer">
<input id="submit-btn" name="submit" class="btn submit" value="Submit">
<input class="btn btn-default" data-dismiss="modal" value="Close">
</div>
</div>
</div>
</div>
</div>
</div>

Fill html input from sql query using button in PHP

I have 2 inputs with name and surname, from a database I bring all the values ​​and when pressing a button on the form I would like the inputs to be completed with the data. When there is no data left to show, it should throw a warning. I leave the code of what I have done so far.
<?php
function customersData(){
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store= 1150";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $customers;
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
$data=customersData();
?>
<html>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="ficha">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="ficha">
</div>
</div>
<button type="submit" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
var btnData = document.getElementById("btnData");
btnData.addEventListener("click",function(e){
e.preventDefault();
});
</script>
</body>
</html>
You probably want to use Ajax, I added JQuery to simplify it.
Try it, and manage your id_store variable.
<?php
function customersData($id) {
try {
$pdo = conect();
$sql = "Select CTE_LASTNAME,CTE_NAME
From customers
Where id_store=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'Error: '.$e->getMessage();
}
}
if (!empty($_GET["get_data"])) {
$data = customersData(intval($_GET["get_data"]));
echo json_encode($data);
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
</head>
<body>
<form>
<div class="form-group">
<div class="col-xs-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="mb-3">
<label for="lastname" class="form-label">Lastname</label>
<input type="text" class="form-control" id="lastname">
</div>
</div>
<button type="button" class="btn btn-primary" id="btnData">Show Data</button>
</form>
<script>
$("#btnData").click(function (ev) {
$.get(window.location.href, {
"get_data": 1150
}, function (result) {
let obj = JSON.parse(result);
$("#name").val(obj.CTE_NAME);
$("#lastname").val(obj.CTE_LASTNAME);
});
});
</script>
</body>
</html>

Php form emailing but $_POST['email'] is failing

I have a form on my site that I want to send an email on submit. The email gets sent but none of the content gets sent along with it. It seems that isset($_POST['email']) is failing.
Here is my form:
<form id="sponsorForm" name="sponsor" role="form">
<div class="modal-body">
<div class="form-group col-md-12">
<label for="sponsorname">Name</label>
<input type="text" name="sponsorname" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsoremail">Email</label>
<input type="email" name="sponsoremail" class="form-control">
</div>
<div class="form-group col-md-12">
<label for="sponsormessage">Message</label>
<textarea class="form-control" name="sponsormessage" rows="7" placeholder="Message...">
</textarea>
</div>
</div>
<div class="modal-footer" style="border: none;">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" data-toggle="modal" data-target="#sponsor-thanks" id="sponsor-submit">
</div>
</form>
Here is some javascript to call the php:
$(document).ready(function(){
$("#sponsorForm").submit(function(event){
submitSponsorForm();
return false;
});
});
function submitSponsorForm(){
$.ajax({
type: "POST",
url: "sendSponsor.php",
cache:false,
data: $('form#sponsorForm').serialize(),
success: function(response){
$("#sponsor").html(response)
$("#sponsor-modal").modal('hide');
},
error: function(){
alert("Error");
}
});
}
And here is the php:
<?php
if (isset($_POST['email'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
}
mail("xxx#xxx.com", "subject", $message, "from: xxx");
?>
In your form, the name of your email input field is 'sponsoremail'
So you should use the name sponsoremail as the index of $_POST variable as $_POST['sponsoremail'] to check if user fill the email or not but you have used $_POST['email'] which is not found in your form.
Use if (isset($_POST['sponsoremail'])) instead of if (isset($_POST['email'])) and it should work.
Try this
<?php
if (isset($_POST['sponsoremail'])) {
$sponsorname = strip_tags($_POST['sponsorname']);
$sponsoremail = strip_tags($_POST['sponsoremail']);
$sponsormessage = strip_tags($_POST['sponsormessage']);
$message = "Name: ".$sponsorname."\r\nEmail: ".$sponsoremail."\r\nMessage: ".$sponsormessage;
mail("xxx#xxx.com", "subject", $message, "from: xxx");
}
?>

jquery .post can't pass the value into php for checking

I have a question in jquery - Post . when I input the email in the form, the js - jquery will pass the email into sendResetPasswordMail1.php to check email is valid or not.
but now, $.post("sendResetPasswordMail1.php",mail:email},function(resetPasswordMsg) can not work in js.
I can't find what wrong. Distress.
Could you help me please.
Many Thanks.
php
<!--reset Password Popup start-->
<div class="resetPasswordLayer" id="resetPassword" tabindex="-1">
<div class="resetPasswordLayerWall" id="resetPasswordLayerWall">
<button type="button" class="close resetPasswordCloseButton" aria-label="Close"><span aria-hidden="true">×</span></button>
<p><h3 class="layerTittle">Reset Password</h3></p>
<div class="row">
<!--<form class="form-horizontal" action="ResetPassword/sendResetPasswordMail.php" method="post" id="login-form">-->
<div class="form-horizontal form-group">
<div class="input-group">
<p><strong>User can retrieve the password through the mailbox</strong></p>
<!--<p><strong>Enter your registered e-mail, retrieve your password:</strong></p>-->
<p><input type="text" class="form-control" name="resetPasswordEmail" id="resetPasswordEmail" placeholder="Enter your registered e-mail, retrieve your password."><span id="chkresetPasswordMsg"></span></p>
</div>
</div>
<div class="form-group">
<div class="input-group"><!--<div class="col-md-11 col-md-offset-1">-->
<p><input type="button" class="btn btn-success" id="subSendResetPassword_btn" value="Reset"></p>
<!--<button type="submit" class="btn btn-success"id="subSendResetPassword_btn">Reset</button>-->
<span id="resetPasswordMsg"></span>
</div>
</div>
<!--</form>-->
</div>
</div>
</div>
<!--reset Password Popup End-->
js - jquery
$(function(){
$("#subSendResetPassword_btn").click(function(){
var email = $("#resetPasswordEmail").val();
var preg = /^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/; //match Email
if(email=='' || !preg.test(email)){
$("#chkresetPasswordMsg").html("Please fill in the correct email!");
}else{
$("#subSendResetPassword_btn").attr("disabled","disabled").val('Submit......').css("cursor","default");
alert(email);
$.post("sendResetPasswordMail1.php",{mail:email},function(resetPasswordMsg){
if(resetPasswordMsg == ""){
alert("No Msg Return!");
}
if(resetPasswordMsg=="noRegister"){
$("#chkresetPasswordMsg").html("The mailbox is not registered yet!");
//$("#subSendResetPassword_btn").removeAttr("disabled").val('Submit').css("cursor","pointer");
}else{
$(".resetPasswordLayer").html("<h3>"+resetPasswordMsg+"</h3>");
}
});
}
});
})
php - sendResetPasswordMail1.php
$email = stripslashes(trim($_POST['mail']));
$sql = "select * from user where email='$email'";
$query = mysql_query($sql);
$num = mysql_num_rows($query);
if($num==0){//The mailbox is not registered yet! Return 'noRegister'
$resetPasswordMsg = "noRegister";
echo $resetPasswordMsg;
exit;
}
Prevent the default click event
$("#subSendResetPassword_btn").click(function(e){
e.preventDefault()
});

Categories

Resources