Need help inserting data to database using php,ajax,javascript - 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!";
}
?>

Related

How to set cookies for remember me checkbox after login in codeigniter?

view:
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
remember_me = $("#remember_me").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin,"remember_me":remember_me},
url:"<?php echo base_url(); ?>login_redirect",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$(".login_success").html('<p>' + data.error + '</p>');
}
}
});
});
});
</script>
<div class="login_success"></div>
<label class="control-label">Your Email</label>
<input class="form-control" placeholder="" type="email" id="elogin">
<label class="control-label">Your Password</label>
<input class="form-control" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox"> Remember Me
<button class="btn btn-lg btn-primary full-width" id="login">Login</button>
Controller:
public function login_redirect()
{
$email = $this->input->post('elogin');
$password = $this->input->post('plogin');
$remember = $this->input->post('remember_me');
$this->db->select('*');
$this->db->from('user');
$where = "email='".$email."' and password='".$password."' and status='1'";
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$this->session->set_userdata('user_id',$result);
if (!isset($_POST))
{
header ("Location:".base_url()."thankyou");
}
else
{
echo json_encode(array('redirect' => base_url().'thankyou'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
In this code, I simply create a login form and do login via jquery ajax which is successfully working. Now, I want to set cookie after successful login via jquery ajax and cookie available only for one day after the day cookie expires. So, How can I do this? Please help me.
Thank You
View Page - Login.php :
<input type="email" class="form-control" name="email" placeholder="Enter Email" value="<?php if(isset($_COOKIE["email"])) { echo $_COOKIE["email"]; } ?>" required>
<input type="checkbox" name="remember" <?php if(isset($_COOKIE["email"])) { ?> checked <?php } ?> > Remember Me
Controller - LoginController.php
$email = $this->input->post('email');
$password = md5($this->input->post('password'));
$remember = $this->input->post('remember');
if(!empty($remember)) {
setcookie ("email",$email,time()+ 3600);
setcookie ("password",$password,time()+ 3600);
}else{
if(isset($_COOKIE["email"] && isset($_COOKIE["password"])) ){
setcookie ("email",""); setcookie ("password","");
}
}

How to get the success message in the same page after submitting the form?

I'm trying to display a success and error message in the same page. What do i need to change?
The form is to send the data to the database and then show a success message in the same page, then redirect to another page. I've tried changing the ID value in the form and the java script, i still get the same results, the data is sent to the database, it redirects to another page, but it doesn't show the success message before redirecting.
Controller:
public function register_ajax() {
//form validation rules
$this->form_validation->set_rules('org_name', 'Organisation Name',
'trim|required');
$this->form_validation->set_rules('email', 'Email',
'trim|required|valid_email|is_unique[new_church.email]',
array('is_unique' => "This email address is already registered
with this application.")
);
$this->form_validation->set_rules('password', 'Your Password',
'trim');
$this->form_validation->set_rules('c_password', 'Confirm Password',
'trim|required|matches[password]',
array(
'matches' => 'Password does not match'
)
);
if ($this->form_validation->run()) {
$this->registration_model->update_church(); //insert the data
into db
echo 1;
redirect(site_url('registration/payment'));
} else {
echo validation_errors();
}
}
Model:
public function update_church() {
$org_name = ucwords($this->input->post('org_name', TRUE));
$email = $this->input->post('email', TRUE);
$password = ucfirst($this->input->post('password', TRUE));
$c_password = ucfirst($this->input->post('c_password', TRUE));
$data = array (
'org_name' => $org_name,
'email' => $email,
'password' => $password,
'c_password' => $c_password,
);
$this->db->insert('new_church', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
JavaScript:
//Registration
$('#registration_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'registration',
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>').fadeIn( 'fast' );
$('#registration_form')[0].reset(); //reset form fields
} else {
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
}
});
});
View:
<?php
$form_attributes = array("id" => "registration_form");
echo form_open('registration/register_ajax', $form_attributes); ?>
<div class="login100-form validate-form">
<div class="wrap-input100 validate-input" data-validate = "First
name is required">
<label class="form_header">Organisation Name</label>
<input class="input100" type="text" name="org_name" value="<?php
echo set_value('org_name'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid
email is required: ex#abc.xyz">
<label class="form_header">Your Work Email Address</label>
<input class="input100" type="email" name="email" value="<?php
echo set_value('email'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Password
is required">
<label class="form_header">Your Password</label>
<input class="input100" type="password" name="password" value="<?
php echo set_value('password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Confirm Password">
<label class="form_header">Confirm Password</label>
<input class="input100" type="password" name="c_password" value="<?php echo set_value('c_password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="text-center p-t-12">
<p>By clicking the button below, you agree to StreamApp's terms of acceptable use</p>
</div>
<div class="m-t-20">
<div id="status_msg"></div>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn"> NEXT </button>
</div>
</div>
<?php echo form_close(); ?>
I expect a success message to appear before redirecting to another page
what happened to your code is when your try to run the form validation it get always true because you set a condition where not executing if the result is true or false.
if ($this->form_validation->run() == TRUE) { //you should change it to this
$this->registration_model->update_church();
$data['success'] = 1;
} else { //if the form validation run false it will display the error.
$data['error'] = validation_errors();
}
echo json_encode($data);
And if you are going to send back a message to your AJAX code you should encode it first using JSON.
To display it.. do this.
if (msg.success == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>');
$('#registration_form')[0].reset(); //reset form fields
setTimeout(function(){
window.location.replace("<?php echo base_url('registration/payment') ?>");
}, 3000); //set it to your time
} else if(msg.error){
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg.error + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
Hope that helps.Let me know the result.
Remove this line:
redirect(site_url('registration/payment'));
And in your ajax success function add this:
if (response == "1") {
// todo set timeout maybe and show a success message then redirect.
window.location.href = siteUrl+"registration/payment";
}
And just make sure to define siteUrl in your js file:
const siteUrl = "http://localhost/";

Submit Contact Form w/o Reloading Page Using Ajax

I am following a guide to build a bootstrap contact form and submit it through mail.php without having to reload the page using ajax. I am able to get the form to work up until I try implementing ajax. I get stuck because the instructions arent clear as to which code exactly needs to be replaced and where the new code is supposed to go. Here is a link to the guide I am following and the section I am stuck at:
Sending email without reloading page using AJAX
This is the site I am trying to get it to work on: CRANE TECH. NET
I am not so familiar with php so I'm thinking that is where I am messing it up at.
Here is the exact code I am using:
HTML
<section class="section">
<h2 class="section-heading text-muted h4 pt-4">Free Consultation</h2>
<!--CONTACT DESCRIPTION-->
<p class="section-description">Are you ready to turn your vision into a reality? Fill out the contact form below and a member of our team will get back to you as soon as possible. Let's bring your idea to life!</p>
<div class="row">
<div class="col-12">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row">
<!--NAME INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="name" name="name" class="form-control" placeholder="* NAME" required>
<label for="name" class=""></label>
</div>
</div>
<!--EMAIL INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="email" name="email" class="form-control" placeholder="* EMAIL" required>
<label for="email" class=""></label>
</div>
</div>
</div>
<div class="row">
<!-- PHONE NUMBER INPUT -->
<div class="col-12">
<div class="md-form">
<input type="text" id="clientPhone" name="clientPhone" class="form-control" placeholder="PHONE" required>
<label for="phone number" class=""></label>
</div>
</div>
<!--SUBJECT INPUT-->
<div class="col-12">
<div class="md-form">
<input type="text" id="subject" name="subject" class="form-control" placeholder="* SUBJECT" required>
<label for="subject" class=""></label>
</div>
</div>
</div>
<div class="row">
<!--MESSAGE INPUT-->
<div class="col-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="3" class="form-control md-textarea" placeholder="* MESSAGE" required></textarea>
<label for="message"></label>
</div>
</div>
</div>
</form>
<!-- SUBMIT BUTTON -->
<div class=" col-3 offset-3 offset-md-4 mb-4">
<button class="btn btn-warning" onclick="validateForm()">Send <i class="fa fa-paper-plane ml-1"></i></button>
</div>
<div id="status" class="text-muted col-12 col-md-8 offset-md-2 my-1"></div>
</div>
JS
function validateForm() {
var name = document.getElementById('name').value;
if (name == "") {
document.getElementById('status').innerHTML = "Name cannot be empty";
return false;
}
var email = document.getElementById('email').value;
if (email == "") {
document.getElementById('status').innerHTML = "Email cannot be empty";
return false;
} else {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!re.test(email)) {
document.getElementById('status').innerHTML = "Email format invalid";
return false;
}
}
var subject = document.getElementById('subject').value;
if (subject == "") {
document.getElementById('status').innerHTML = "Subject cannot be empty";
return false;
}
var message = document.getElementById('message').value;
if (message == "") {
document.getElementById('status').innerHTML = "Message cannot be empty";
return false;
}
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'clientPhone': $('input[name=clientPhone]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
document.getElementById('contact-form').submit();
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
}
MAIL.PHP
<?php
if(isset( $_POST['name']))
$name = $_POST['name'];
if(isset( $_POST['email']))
$email = $_POST['email'];
if(isset( $_POST['clientPhone']))
$clientPhone = $_POST['clientPhone'];
if(isset( $_POST['subject']))
$subject = $_POST['subject'];
if(isset( $_POST['message']))
$message = $_POST['message'];
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty', 'code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty', 'code' => 0));
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.', 'code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty', 'code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty', 'code' => 0));
exit();
}
// if ($name === ''){
// echo "Name cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($email === ''){
// echo "Email cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// } else {
// if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
// echo "Email format invalid.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// }
// if ($subject === ''){
// echo "Subject cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
// if ($message === ''){
// echo "Message cannot be empty.";
// echo "<br>";
// echo "<br>";
// echo "<a href='index.html'>GO BACK</a>";
// die();
// }
$content="From: $name \n Email: $email \n Phone #: $clientPhone \n Subject: $subject \n Message: $message";
$recipient = "support#crane-tech.net";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!', 'code' => 1));
exit();
?>
Main Issue
You main issue is that there is a missing semcolon (;) and the end of line 15 in the php code.
Other Issues
Your website is using JQuery Slim, $.ajax is not included in the slim version so you are getting an error due to that. To fix this just include the full JQuery or do the ajax without JQuery.
You may also want to get rid of this line:
document.getElementById('contact-form').submit();
because it is causing a redirect when you are already manually submitting your data.
You should remove these lines because you have already set them:
$name = $_POST['name'];
$email = $_POST['email'];
$clientPhone = $_POST['clientPhone']
$message = $_POST['message'];
$subject = $_POST['subject'];
Unrelated note:
If you are already using JQuery, you should be using it - instead of doing this:
document.getElementById('status')
You should be using:
$('#status')

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.

Jquery form submit empty values to Mysql

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.

Categories