Jquery form submit empty values to Mysql - javascript

My IntelXDK HTML5 mobile app form submitting empty values to the MySQL database.
My HTML (Single file app)
<label class="item item-input widget uib_w_6 d-margins" data-uib="ionic/input" data-ver="0" id="fullname">
<input type="text" placeholder="Fullname" name="fullname">
</label>
<label class="item item-input widget uib_w_7 d-margins" data-uib="ionic/input" data-ver="0" id="email">
<input type="email" placeholder="Email" name="email">
</label>
<label class="item item-input widget uib_w_8 d-margins" data-uib="ionic/input" data-ver="0" id="pass">
<input type="password" placeholder="Password" name="pass">
</label>
<button class="button widget uib_w_9 d-margins button-positive" data-uib="ionic/button" data-ver="0" id="signup">
Create Account
</button>
<span class="uib_shim"></span>
My JS
$(document).on("click", "#signup", function (evt) {
/* your code goes here */
//these two lines take the values from inputs using jquery
var input1 = $("#fullname").val();
var input2 = $("#email").val();
var input3 = $("#pass").val();
//jquery ajax to send values to php using POST
$.ajax({
type: 'POST',
url: 'http://localhost/signup.php',
data: {
fullname: input1,
email: input2,
pass: input3
},
success: function (response) {
//from php using echo
alert(response);
}
});
return false;
});
And the PHP file
<?php
// Create connection
$conn = new mysqli("localhost", "user", "pass", "dbname");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fullname = Trim(stripslashes($_POST['fullname']));
$email = Trim(stripslashes($_POST['email']));
$pass = Trim(stripslashes($_POST['pass']));
$sql = "INSERT INTO login (fullname, email, pass) VALUES ('$fullname','$email', '$pass')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Upon submitting this form, it is creating empty records in MySQL.
Any help appreciated.

This is happening because
<input type="text" placeholder="Fullname" name="fullname">
there is no id like id="fullname" available and you are referring to it.

Related

How to save data in my database with PHP

When I send data to my php file. Data is not getting stored in the database. My php code is below.
I am using one.com as my host. There I can use to php code using some components. So I gave an external link to the button to submit to php file.
But I cannot submit data to php code using button name or class attribute.
How can I store data in database using php file.
Please help me in this issue.Thank you in advance.
HTML:
<form method="post" action="register.php">
<div class="input-group">
<lable>Username</lable>
<input type="text" name="Username" required>
</div>
<div class="input-group">
<lable>Email</lable>
<input type="text" name="Email" required>
</div>
<div class="input-group">
<lable>Password</lable>
<input type="password" name="password_1" required></div>
<div class="input-group">
<lable>Confirm Password</lable>
<input type="password" name="password_2" required>
</div>
<p>Already a User?</p>
</form>
PHP:
<?php
$Username = "";
$Email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('hostname', 'root', 'password', 'dbname');
echo "database connected";
// if the register button is clicked
$username = $_POST['Username'];
$email = $_POST['Email'];
$password_1 = $_POST['password_1'];
$password_2 = $_POST['password_2'];
echo "data is taken";
// if there are no errors, save user to database
$sql = "INSERT INTO Users(Username, Email, password) VALUES('$username',
'$email', '$password_1')";
mysqli_query($db, $sql);
echo "data inserted successfully";
?>
Is your database correct?
// connect to the database
$db = mysqli_connect('hostname', 'root', 'password', 'dbname');
echo "database connected";
And remember it always printed "database connected".

Angularjs validate

I want validate my form using ajax , but the errors are not showing properly.
Here is my code:
Html
<body ng-app="app" ng-controller="dkController">
<form ng-submit="dk()">
<label>Username</label>
<input type="text" name="username" ng-model="formdata.user">
{{errorName}}
<label>Password</label>
<input type="text" name="password" ng-model="formdata.pass">
<label>Email</label>
<input type="text" name="email" ng-model="formdata.email">
<button type="submit" >Submit</button>
{{message}}
</form>
</body>
Js
function dkController($http,$scope){
$scope.formdata={};
$scope.dk = function(){
$http({
method:"POST",
url:"dk.php",
data:$.param($scope.formdata)
})
.then(function(response){
$scope.errorName = response.data.errors.username;
})
and PHP
$conn= new mysqli('localhost','root','','dangky');
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$sql="SELECT *FROM dangky where username='$username'";
$result= mysqli_query($conn,$sql);
$errors=array();
$data=array();
if(empty($username))
$errors['username']='user name is required';
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
if ($row['username'] == $username){
$errors['check'] = 'Tên đăng nhập đã tồn tại';
}
}
if(!empty($errors)){
$data['success']=false;
$data['errors']=$errors;
}
echo json_encode($data);
Error username is showing but errors check not showing .
This is the php output
{"success":false,"errors":{"username":"user name is required"}} .
The problem is youu passed $scope.formdata which contains
{ user : 'someone', pass: 'abc123!', email: 'me#medotcom' }
Your PHP script is looking for post data { username: 'someone' }
So rename your ng-model to ng-model="formdata.username" or change your PHP to find $_POST['user']. Your choice but they must match.

Need help inserting data to database using php,ajax,javascript

Recently, i take some template from the internet and trying to understand the code.
But i got stuck when trying to insert data to the database and the error message wont show.
Im sorry for my bad English
This is my piece of, master_menu.php
<div class="form-group">
<label for="first_name">Nama Menu</label>
<input type="text" id="first_name" placeholder="Contoh : Ayam Goreng" class="form-control"/>
</div>
<div class="form-group">
<label for="last_name">Harga Pokok</label>
<input type="text" id="last_name" placeholder="Contoh : 15000" class="form-control"/>
</div>
<div class="form-group">
<label for="email">Harga Jual</label>
<input type="text" id="email" placeholder="Contoh : 15000" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn-primary" onclick="addRecord()">Tambahkan Menu</button>
</div>
And this is my piece of, function_script_master.js
function addRecord() {
// get values
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
// Add record
$.post("ajax/addRecord.php", {
first_name: first_name,
last_name: last_name,
email: email
}, function (data, status) {
// close the popup
$("#add_new_record_modal").modal("hide");
//reload
readRecords();
// clear fields from the popup
$("#first_name").val("");
$("#last_name").val("");
$("#email").val("");
});
}
// READ records
function readRecords() {
$.get("ajax/readRecords.php", {}, function (data, status) {
$(".records_content").html(data);
});
}
And this is my piece of, addRecord.php
<?php
if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])){
// include Database connection file
include("function_connection.php");
alert('clcicked');
// get values
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$query = "INSERT INTO MENUS(NAMA_MENU, HARGA_POKOK, HARGA_JUAL, STATUS) VALUES('$first_name', '$last_name', '$email', 'aktif')";
if ($conn->query($query) === TRUE) {
alert("Registrasi Sukses!");
} else {
alert("Username Yang Anda Inginkan Sudah Terpakai");
}
$conn->close();
echo "1 Record Added!";
}
?>
Try below code hope this helps, i just replaced alert with echo.
<?php
if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])){
// include Database connection file
include("function_connection.php");
// get values
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$query = "INSERT INTO MENUS(NAMA_MENU, HARGA_POKOK, HARGA_JUAL, STATUS) VALUES('$first_name', '$last_name', '$email', 'aktif')";
if ($conn->query($query) === TRUE) {
echo "Registrasi Sukses!";
} else {
echo "Username Yang Anda Inginkan Sudah Terpakai";
}
$conn->close();
echo "1 Record Added!";
}
?>

Create modal alert instead of page redirect validation in PHP

I want to have server side validation. Is there a way how can I have the alert like this image whenever the user input the data like email that exist in my database, the alert will appear when I hit the sumbit button. Thanks in advance. :D
Here's my create_acc.html
<form action="create_acc.php" method="POST" id="fieldform">
<dl>
<p><dt>Email Address:</dt>
<dd>
<input type="text" name="e-mail" id="e-mail" class="text" placeholder="Your Email will be your log in" autocomplete="off">
</dd>
</p>
<p><dt>Create Password:</dt>
<dd>
<input type="password" name="password" id="password" class="text" placeholder="Remember your password" autocomplete="off">
</p>
<p>
<p><dt>Your Complete name:</dt>
<dd>
<input type="text" name="name" id="name" class="text" placeholder="Your Complete name" autocomplete="off">
</p>
<p>
<dt>
<input type="submit" value="Submit">
</dt>
</p>
</dl>
</form>
Here's my create_acc.php
<?php
session_start();
$email = $_POST['e-mail'];
$name = $_POST['name'];
$pass = $_POST['password'];
$hash = hash('sha256',$pass);
function createSalt(){
$text = md5(uniqid(rand(), true));
return substr($text,0,3);
}
$salt = createSalt();
$pass = hash('sha256',$salt.$hash);
$conn = mysqli_connect('localhost','root','','mydb');
$email = mysqli_real_escape_string($conn,$email);
$query = "INSERT INTO customers(Email,Password,Name,salt) VALUES('$email','$pass','$name','$salt')";
mysqli_query($conn,$query);
mysqli_close($conn);
header('Location: index.php');
?>
You could use ajax to do this. When the user submits the form you would send an ajax request with the form data to your php script, the script will then respond with a value that you use to deside if you should display an alert or not, here is a basic example using jquery:
$(document).ready(function() {
// catch submit events for your form
$('#your-form-id').submit(function() {
// make an ajax request to your validation script
$.ajax{(
url:'create_acc.php',
type:'POST',
data:$(this).serialize(),
dataType:'json',
success:function(response) {
if(!response.success) {
alert('Something went wrong!');
}
}
});
return false;
});
});
Then in your php script you return a code telling the client how it went:
// create_acc.php
// I assume the form only has one value 'email'
$success = false;
if(isset($_POST['email'])) {
// here you would check if the email already
// exists in the database
$query = "SELECT * FROM <table> WHERE email = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $_POST['email']);
// execute the query and check if a row was returned
}
// if everything went fine you should change success to true
// return json response to client
$response = array('success' => $success);
print json_encode($response);
exit;

Missing Variables in Contact Form Using Ajax and PHP

I have a contact form on a landing page that I want to send through with AJAX & PHP but for some reason, the variables are not passing. I am getting the email but the variables are blank. You can go to removed to see the text site, it's not set up with the database on this site though, so if you try to click through nothing will happen.
Does anyone have any idea what could be causing my form to not cooperate?
The HTML
<form role="form" id="form" name="form" action="submit.php" method="post">
<div class="form-group has-feedback">
<input type="text" class="form-control input-lg" id="name" name="name" placeholder="Full Name" />
<span class="help-block" style="display: none;">Please enter your full name.</span>
</div>
<div class="form-group has-feedback">
<input type="tel" class="form-control input-lg optional" id="phone" name="phone" placeholder="Phone (Optional)"/>
<span class="help-block" style="display: none;">Please enter a valid phone number.</span>
</div>
<div class="form-group has-feedback">
<input type="email" class="form-control input-lg" id="email" name="email" placeholder="Email" />
<span class="help-block" style="display: none;">Please enter a valid email address.</span>
</div>
<div class="form-group has-feedback">
<textarea rows="5" cols="30" class="form-control input-lg" id="message" name="message" placeholder="Message" ></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group has-feedback">
<label>
<input type="checkbox" class="form-control input-sm optional" id="newsletter" name="newsletter" checked="checked">
Opt-in to our newsletters to stay up-to-date with the latest information. </label>
<span class="help-block" style="display: none;">Would you like to sign up for our newsletter?</span>
</div>
<div class="form-group has-feedback">
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg pull-right" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Submit</button>
</div>
</form>
The Script
//*Form*//
$('document').ready(function(){
$('#form').validate({
rules:{
"name":{
required:true,
maxlength:40
},
"phone":{
required:false
},
"email":{
required:true,
email:true,
maxlength:100
},
"message":{
required:false
},
"newsletter":{
required:false
}},
messages:{
"name":{
required:"This field is required"
},
"phone":{
required:"This field is required"
},
"email":{
required:"This field is required",
email:"Please enter a valid email address"
},
"message":{
required:"This field is required"
},
"newsletter":{
required:"This field is required"
}},
submitHandler: function(form){
$.ajax ({
type: "POST",
url: "submit.php",
dataType: "json",
data:{"name":$("#name").text(),"phone":$("#phone").text(),"email":$("#email").text(),"message":$("message").text(),"newsletter":$("#newsletter").checked},
target: '#preview',
success: function(Result) {
alert(Result[0]);
$('#formbox').slideUp('fast');
$('#success').html();
$('#success').show();
},
failure: function (arg1, arg2) {
alert(arg1 + '\n\n' + arg2);
},
error: function (Result, Error, arg3, arg4) {
alert(Result + '\n\n' + Error + '\n\n' + arg3 + '\n\n' + arg4);
}
});
}
});
});
</script>
The PHP
<?php
require_once 'db.php';
header('Content-Type: application/json');
/*
$checkemail = $_POST['email'];
if (filter_var($checkemail, FILTER_VALIDATE_EMAIL)) { echo ""; }
else { die ("Invalid email, form processing has not completed.");
}
*/
// check email validity. clean name, phone, and message.
$name = htmlspecialchars(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$phone = htmlspecialchars(filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING));
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$newsletter = htmlspecialchars(filter_input(INPUT_POST, 'newsletter', FILTER_SANITIZE_STRING));
// commit to database
require_once 'db.php';
$stmt = $pdo->prepare("INSERT INTO contact (name, phone, email, message, newsletter) VALUES (?,?,?,?,?)");
$stmt->bindParam(1, $name, PDO::PARAM_STR, 50);
$stmt->bindParam(3, $phone, PDO::PARAM_STR, 50);
$stmt->bindParam(2, $email, PDO::PARAM_STR, 50);
$stmt->bindParam(4, $message);
$stmt->bindParam(5, $newsletter, PDO::PARAM_STR, 64);
$pdo->beginTransaction();
$stmt->execute();
$pdo->commit();
//form email
$today = date("Y-m-j");
$body = "";
$body .= "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Phone: $phone\n";
$body .= "Message: $message\n";
$body .= "Newsletter: $newsletter\n";
//send email 'change me to clients address'
mail("angela#etvsoftware.com","Dogwood Hills Gun Club Contact Form",$body,"angela#etvsoftware.com");
$stmt = null;
$pdo = null;
#What we say when everything goes right
$result = array(
"message" => "Your message has been sent. We will respond to you as soon as possible."
);
print json_encode($result);
?>
Instead of:
data:{"name":$("#name").text(),"phone":$("#phone").text(),"email":$("#email").text(),"message":$("message").text(),"newsletter":$("#newsletter").checked}
You should consider something cleaner and more flexible using serialize() like that:
data: $('#form').serialize()
This will send all the form fields in the POST request with your ajax call. If this is not working, Please try to var_dump($_POST) to make sure what you are getting.

Categories