Insert data using ajax, json, and php - javascript

Intro I am doing an insert into the database using Ajax, PHP, and SQL.
Error: alert(data) says undefined:first_name.....I thought I defined using $first_name = strtoupper($_POST['first_name']) witin the add.php file.
Index.php
<script type="text/javascript">
$(document).on('click','#update_btn',function (){
$.ajax({
type:'POST',
url:'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
updated: $("#updated").val(),
},
success: function(data){
alert(data);
if (data=='ADD_OK') {
location.reload();
} else {
alert('something wrong');
}
}
})
});
<form id="form1" class="form-inline" method="post" action="">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<select name="position" id="multiple-select-optgroup-default2" class="custom-select">
<option selected>Admin</option>
<option value="Teacher">Teacher</option required>
<option value="Staff">Staff</option>
</select>
<input type="hidden" name="updated" value='<?php echo date("Y-m-d");?>' >
<button class="btn btn-success btn-sm active" type="submit" name="save" id="update_btn"><span class="glyphicon glyphicon-plus-sign"></span> Save</button>
</form>
</script>
Add.php
<?php
$first_name = strtoupper($_POST['first_name']);
$last_name = strtoupper($_POST['last_name']);
$position = strtoupper($_POST['position']);
$updated = $_POST['updated'];
$stmt = $conn->prepare("INSERT INTO employees (first_name, last_name, position, updated) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $first_name, $last_name, $position, $updated);
$add = $stmt->execute();
if($add) {
echo "ADD_OK";
}
?>

it's undefined:first_name given an error because you don't give indexing in form but you use in jquery. show use HTML code like this and check.
<input type="text" name="first_name" id="first_name" placeholder="First Name" required>
<input type="text" name="last_name" id="last_name" placeholder="Last Name" required>
<select name="position" id="position" class="custom-select">
<option selected>Admin</option>
<option value="Teacher">Teacher</option required>
<option value="Staff">Staff</option>
</select>
<input type="hidden" name="updated" id="updated" value='<?php echo date("Y-m-d");?>' >
and debug with your jquery code.

Here is your piece of code of jQuery:
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
updated: $("#updated").val(),
},
In this you are trying to get value via id of textbox as you mentioned
$("#first_name").val()
Change your code to this :
data: {
first_name: $('input[name="first_name"]').val(),
last_name: $('input[name="last_name"]').val(),
position: $('input[name="position"]').val(),
updated: $('input[name="updated"]').val(),
},
Hope it will help you.

Related

Populate form fields ending in number from pdo mysql using ajax

Here is my basic form:
<form id="mgstaskvuephonecall" name="contactform" method="POST" >
<div class="mb-3">
<div class="input-group" id="fld1">
<input type="text" name="contact1" id="contact1" class="form-control tvc username" placeholder="Contact" aria-label="Username" alt="1">
<input type="text" name="phone1" id="phone1" class="form-control phone-number tvp" placeholder="Ex: +(000) 000-00-00" alt="1">
</div>
</div>
<div class="mb-3">
<div class="input-group" id="fld1">
<input type="text" name="contact2" id="contact2" class="form-control tvc username" placeholder="Contact" aria-label="Username" alt="2">
<input type="text" name="phone2" id="phone2" class="form-control phone-number tvp" placeholder="Ex: +(000) 000-00-00" alt="2">
</div>
</div>
<!-- ... a total of 5: contact1-contact5, phone1-phone5 -->
</form>
I am using AJAX to call php to pull data from the database, how then would I use the result to populate my form. I am stuck on handling the fields with same names just differenced by the sequential number on the end of it. Here's what I have so far, just stuck on how to manipulate results:
// fetch table data based on date
$("#form-date").on('change', function(){
var date = $(this).val();
$.ajax({
url: 'dynamic-pop-form.php',
method: 'POST',
data:{
"date":date
},
success: function(data){
var len = data.length;
...
}
}
});
});
dynamic-pop-form.php:
include('connection.php');
$formDate = $_POST['date'];
$formDate = strtotime($formDate);
$formDate = date('Y-m-d', $formDate);
$stmt = $conn->prepare("SELECT * FROM `my_table` WHERE `form_date` = ? LIMIT 5");
$stmt->bindParam(1,$formDate,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode( $result );

Undefined Index error php (Submit tag doesn't enter the information in mysql table)

I have to enter the data from a form to a database table. I created the test database and the employee table in phpMyAdmin. When I run it on localhost I get the undefined index error for variables Name, Surname..., and the submit tag doesn't upload the form info into the table in the database. How can I solve this problem?
This is my code:
page.php
<?php
include_once('db.php');
$sql = " ";
$vlere = mysqli_query($sql,$conn);
if (isset($_POST['submit'])) {
$Name = $_POST['name'];
$Surname = $_POST['surname'];
$Birthday = $_POST['birthday'];
$Email = $_POST['email'];
$Telephone = $_POST['telephone'];
$Address = $_POST['address'];
$Company = $_POST['company'];
$Role = $_POST['role'];
$sql = "INSERT INTO employee(Name, Surname, Birthday, Email, Telephone, Address, Company, Role) VALUES('$Name', '$Surname', '$Birthday', '$Email', '$Telephone', '$Address', '$Company', '$Role')";
$vlere = mysqli_query($sql,$conn);
}
if (!empty($vlere)) {
echo "Empty";
}
else {
echo "Inserted";
}
?>
index.html
<html>
<head>
<title>Human Resource</title>
</head>
<body>
<h3><center>Enter the <b>EMPLOYEE</b> information</center></h3>
<form action="page.php" method="post">
Name:
<input type="text" name="name" ></br></br>
Surname:
<input type="text" name="surname" ></br></br>
<div>
Birthday:
<input type="date" name="birthday" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"/>
</div>
</br></br>
<div>
Email:
<input type="email" name="email" size="40" maxLength="40" required placeholder="username#gmail.com" pattern=".+#gmail.com">
</div>
</br></br>
<div>
Telephone:
<input type="tel" name="telephone" max="15" required placeholder="xxx-xxx-xxxx" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
</div>
</br></br>
<div>
Address: <input type="address" name="address" required />
</div>
</br></br>
Company Name:
<form>
<select id="company">
<option value="AT Consulting">AT Consulting</option>
<option value="IKUB.al">IKUB.al</option>
<option value="InfoSoft">InfoSoft</option>
<option value="ATOM Computers">ATOM Computers</option>
</select>
</form>
Field:
<input type="text" id="field" />
<button onclick="func1()">Add</button>
<script>
function func1(){
var x = document.getElementById("company");
var option = document.createElement("option");
option.innerHTML = document.getElementById("field").value;
x.add(option);
}
</script>
</br></br>
Role: <input type="text" name="role" >
</br></br>
<input type="submit" name="submit" value="submit" />
</form>
<script src="script/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="script/first_script.js" type="text/javascript"></script>
</body>
first_script.js
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function() {
return false;
});
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
db.php
<?php
$conn = mysqli_connect('localhost', 'root', '');
$db = mysqli_select_db('test');
?>
Thank you for taking your time to answer me.

Using AJAX to populate a form with data pulled from mysql database

I'm trying to populate a form with data automatically when a gymnast is selected from a dropdown box. I understand that I need to use AJAX, and have tried - however my Javascript is terrible so low and behold; my code is abysmal.
ajax_populate_gymnasts.php:
<?php
require('../includes/dbconnect.php');
$gymnastid = $_POST['gymnast'];
$sql = "SELECT * FROM gymnasts WHERE id='$gymnastid'";
$result = mysqli_query($GLOBALS['link'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
foreach($result as $row)
{
//Change to populate fields on form with data.
echo ($row);
}
}
else{
$msg .="<option>No Gymnasts were found!</option>";
echo ($msg);
}
mysqli_close($GLOBALS['link']);
?>
function getGymnasts(val){
$.ajax({
type:"POST",
url:"ajax_populate_gymnasts.php",
data: 'gymnast='+val,
success: function(data){
$("#dob").value(data['dob']);
$("#gender").value(data['gender']);
$("#parent").value(data['parent']);
$("#email").value(data['email']);
$("#phone").value(data['phone']);
$("#address").value(data['address']);
$("#status").value(data['status']);
}
});
}
<?php require('adminheader.php');
?>
<script>
</script>
<h1>Edit Gymnast</h1>
<form method="post">
<label for="gymnast">Gymnast:</label>
<select id="gymnast" name="gymnast" onChange="getGymnasts(this.value)" required/>
<option value="0">None yet</option>
<?php
$gymnasts = mysqli_query($GLOBALS['link'], "SELECT * FROM gymnasts;");
foreach($gymnasts as $gymnast){
echo("<option value=".$gymnast['id'].">".$gymnast['name']."</option>");
}
?>
</select><br>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required/>
<label for="gender">Gender:</label>
<select id="gender" name="gender" required />
<option value="F">Female</option>
<option value="M">Male</option>
</select><br>
<label for="parent">Parent's Name:</label>
<input type="text" id="parent" name="parent" required /> <br>
<label for="email">Contact Email:</label>
<input type="text" id="email" name="email" required /> <br>
<label for="phone">Contact Phone:</label>
<input type="text" id="phone" name="phone" required /> <br>
<label for="parent">Contact Addres:</label>
<textarea id="address" name="address" required /></textarea><br>
<select id="status" name="status" required />
<option value="0"></option>
<input type="submit" id="saveChanges" name="saveChanges" />
</form>
Your AJAX function needs to be like
function getGymnasts(val){
$.ajax({
type:"POST",
url:"ajax_populate_gymnasts.php",
data: 'gymnast='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
var data = result.rows;
$("#dob").val(data[0].dob);
$("#gender").val(data[0].gender);
$("#parent").val(data[0].parent);
$("#email").val(data[0].email);
$("#phone").val(data[0].phone);
$("#address").val(data[0].address);
$("#status").val(data[0].status);
}else if (result.response == false) {
$('#gymnast').append('<option>No Gymnasts were found!</option>');
}
}
});
}
and your ajax_populate_gymnasts.php
<?php
require('../includes/dbconnect.php');
$sql = "SELECT * FROM gymnasts WHERE id='$gymnastid'";
$result = mysqli_query($gym, $sql);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode(['rows' => $data, 'response' => true]);
} else {
echo json_encode(['response' => false]);
}
mysqli_close($GLOBALS['link']);
exit();
?>
}
To set the value of an element with jQuery you need to use .val() http://api.jquery.com/val/
So all of those lines need to change from value to val, e.g.
$("#dob").val(data['dob']);

Access POST values sent by Ajax in PHP

I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font><br>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
My JS (the first console.log does go through and work):
if (validForm)
{
console.log("valid form");
console.log(JSON.stringify($('#home-sign-up-form')[0].seriaize()));
$.ajax(
{
type:'POST',
url:'form-submit.php',
data:$('#home-sign-up-form')[0].serialize(),
success:function(response)
{
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
$emailSentTextEmail.text($suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
}
And my PHP/MySQL:
<?php require 'dbconnect.php'; ?>
if (isset($_POST['suEmail']))
{
echo "<script type='text/javascript'>alert('got');</script>";
$suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($_POST['suLastName']);
$suEmail = mysqli_real_escape_string($_POST['suEmail']);
$suPassword = mysqli_real_escape_string($_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}
The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D
$("#home-sign-up-form").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
$.ajax({
type: 'POST',
url: 'form-submit.php',
data: $('#home-sign-up-form').serialize(),
success: function(response) {
console.log(response);
var data = JSON.parse(response);
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
//$emailSentTextEmail.text($suEmail);
$emailSentTextEmail.text(data.suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font>
<br>
<label>
<input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font>
</label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<?php
if (isset($_POST['suEmail']))
{
$con=mysqli_connect("localhost","root","cakpep","backoffice");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$suFirstName = mysqli_real_escape_string($con,$_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($con,$_POST['suLastName']);
$suEmail = mysqli_real_escape_string($con,$_POST['suEmail']);
$suPassword = mysqli_real_escape_string($con,$_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($con,$_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
echo json_encode($_POST);
}
?>
add this to trigger when submit form
$("#home-sign-up-form").submit(function(event) {
and then on php return the response with json string
echo json_encode($_POST);
and then in the response ajax parse json text to object like this
var data = JSON.parse(response);
$emailSentTextEmail.text(data.suEmail);
i hope this what you want..

Submit a Form with jQuery and Ajax

Trying to get my register page posting the data to the database using Ajax and jQuery but having great difficulty.
I'm very new to ajax and cane seem to get my head around how to do this insert.
Would be very grateful of any advice regarding how to do this. Im not sure if what i have got is even remotely close at the moment.
As current when I click the submit button the page refreshes but there is no change to the database.
*html code
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="../css/stylesheet.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="../js/validation.js"></script>
<script type="text/javascript" src="../js/registerpost.js"></script>
</head>
<body>
<div id="container">
<div id="mainContent")>
<form class="basic-grey" method="post">
<h1>Registration Form<span>Please complete all fields.</span></h1>
<p>
<label><span>First Name:</span>
<input name="firstname" id="firstname" type="text" size="40" maxlength="40" placeholder="First Name" required/>
</label>
<label><span>Surname:</span>
<input name="lastname" id="lastname" type="text" size="40" maxlength="40" placeholder="Surname" required/>
</label>
<label><span>Username:</span>
<input name="username" id="username" oninput="checkUsername();" type="text" size="40" maxlength="40" placeholder="Username" required/>
</label>
<label><span>Email:</span>
<input name="email" id="email" oninput="checkEmail();" type="email" size="40" maxlength="40" placeholder="Email" required/>
</label>
<label><span>Password:</span>
<input name="password1" id="password1" type="password" size="40" maxlength="40" placeholder="********" required/>
</label>
<label><span>Confirm Password:</span>
<input name="password2" id="password2" oninput="checkPassword();" type="password" size="40" placeholder="********" required/>
</label>
</p>
<div align="center"><span align = "center" id="user-result"></span><br><br><br>
</div>
<div align="center">
<span> </span><input type="submit" class="button" id="submit_btn" value="Submit" />
</div>
</form>
</form>
</div>
</div>
</body>
</html>
php code
<?php
include 'connection.php';
$hash = password_hash($_POST['password2'], PASSWORD_DEFAULT, ['cost' => 11]);
$sql = "INSERT INTO members(firstname, lastname, username, email, password )
VALUES(:firstname, :lastname, :username, :email, :password )";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$stmt->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':password', $hash, PDO::PARAM_STR);
$results->$stmt->execute();
if($results) {
echo 'Welcome new member, and thanks you for registering with the website.';
echo '<br><br>Click here to return to the login page';
} else {
echo 'Did not work.';
}
?>
js code
$(document).ready(function() {
$('#submit_btn').click(function(){
var data = {};
data.firstname = $('#firstname').val();
data.lastname = $('#lastname').val();
data.username = $('#username').val();
data.email = $('#email').val();
data.password2 = $('#password2').val();
$.ajax({
type: "POST",
url: "../php/newuser.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
Any help would be greatly appreciated.
Thanks
Solved it was a simple error that i had made in the PHP file.
This
$results->$stmt->execute();
To this
$results = $stmt->execute();
Thanks all
You can do something like this. See details here:
https://webdevideas.wordpress.com/2013/07/30/n-forms-one-javascript/
$(document).ready(function(){
$(".ajaxform").bind("submit",function(e){
e.preventDefault();
var ajaxurl = $(this).attr("action");
var data = $(this).serialize();
$.post(ajaxurl,data,function(res){
$("#message").html(res.message);
},'json');
});
});

Categories

Resources