Showing success message in php using ajax - php

Iam Working on a project using OO php and i want to display success message when submit is clicked
I've searched all on the web but the solutions am getting are not working for me!!
I tried using both jquery and ajax but i keep on getting the same error
Here is my html
<form method="post" id="postForm" class="form-horizontal" action = "index.php">
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post"/>
</div>
</div>
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<Textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
</div>
<button type="submit" class="btn btn-default" name="submit">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="wanings" class="text-danger"></span>
</div>
</form>
This is my jquery script file inserted into the same page index.php
<script>
$(document).ready(function(){
$('#postForm').submit(function(event){
event.preventDefault();
var $form = $(this),
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if(title == '' || body == ''){
$('#warnings').html('All Fields are Required');
}else{
$('#warnings').html('');
$.ajax({
url: url,
method:method,
data:{title: title, body:body},
success:function(data){
$('#postForm').trigger('reset');
$('#success').fadeIn().html(data);
setTimeout(function function_name() {
$('#success').fadeOut('slow');
}, 3000);
}
});
}
});
});
</script>
And the Php is just above the Html also in the same page. Its supposed to get the post title and insert it into the database but echo the message that data has been successfully added if submit is clicked.
Here is the Snippet
<?php
require 'classes/Database.php';
$database = new Database;
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($post['submit']){
$title = $post['title'];
$body = $post['body'];
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $title);
$database->bind(':body', $body);
$database->execute();
if($database->lastInsertId()){
echo "<h1>Post added Successfully To the Database</h1>";
}
}
?>
When i run the page in the browser, it displays the whole html in the div.
instead of a message set and then it throws the following error in the console.
Could any of you be knowing why it can't show the message? thanks

As you notice by the image, all the text is green, this is because you are rendering the response within that text-success span. Not ideal.
Instead of responding with HTML respond with JSON, and do your checks within the javascript to determine whether it was successful or a warning.
Some other issues:
You're not sending up submit so it will always skip passed the if statement.
So try something like:
$(document).ready(function() {
$('#postForm').submit(function(event) {
event.preventDefault();
var $form = $(this);
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if (title == '' || body == '') {
$('#warnings').html('All Fields are Required');
if (title == '') {
$('#title').closest('.form-group').find('.help-block').html('Title is a required field')
}
if (body == '') {
$('#body').closest('.form-group').find('.help-block').html('Body is a required field')
}
} else {
$('#warnings').html('');
$form.find('.help-block').html('')
$.ajax({
url: url,
method: method,
data: {
title: title,
body: body
},
success: function(response) {
// got errors from server
if (response.status === 'error') {
if (response.errors.title) {
$('#title').closest('.form-group').find('.help-block').html(response.errors.title)
}
if (response.errors.body) {
$('#body').closest('.form-group').find('.help-block').html(response.errors.body)
}
if (response.errors.global) {
$('#warnings').html(response.errors.global)
}
}
// all good, assign message to success
else {
$('#success').fadeIn().html(response.msg);
setTimeout(function() {
$('#success').fadeOut('slow');
}, 3000);
$('#postForm').trigger('reset');
}
}
});
}
});
});
<form method="post" id="postForm" class="form-horizontal" action="index.php">
<div class="form-group">
<label for="title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="body" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
<span class="help-block"></span>
</div>
<button type="submit" class="btn btn-default">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="warnings" class="text-danger"></span>
</div>
</form>
PHP code, basically validate and return as JSON.
<?php
require 'classes/Database.php';
$database = new Database;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$response = [];
$errors = [];
// validate inputs
if (empty($post['title'])) {
$errors['title'] = 'Title is a required field';
}
if (empty($post['body'])) {
$errors['body'] = 'Body is a required field';
}
// errors is empty so its all good
if (empty($errors)) {
//
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $post['title']);
$database->bind(':body', $post['body']);
$database->execute();
if ($database->lastInsertId()) {
$response = [
'status' => 'success',
'msg' => 'Post added successfully added'
];
} else {
$response = [
'status' => 'error',
'errors' => [
'global' => 'Failed to insert post, contact support'
]
];
}
} else {
$response = [
'status' => 'error',
'errors' => $errors
];
}
exit(json_encode($response));
}
// guessing after this is your rendering of that form

You need to check if($_POST) instead of if($post['submit']) because in your case its not going into if condition and echo out your result. Also after echo add "exit" statement so that form will not be printed in division.

Related

Codeigniter form validation return false on ajax request

Before I start, sorry for my English. i am developing a website using CI on Backend. And i want to make a registration system without refreshing the page. If i try with post form submit i got no error and everything went good. but when I try using with ajax request, I can't use form validation because form validation return false and validation_errors is empty. if I disable form validation, ajax request works well. here is my controller and ajax request. Please help me.
User.php (My Controller)
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
$data = json_encode(array('status'=> false,'info'=>validation_errors()));
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
$data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
} else {
$data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
}
}else{
$data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
}
}
echo $data;
}
}
And here is my ajax request in js
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: url + 'User/register', //url is correct i tested without form validation
data: $('#register-form').serialize(),
dataType: "json",
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
edit: and here is my form:
<!-- Register Form -->
<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
<div class="md-form">
<input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="name_kyt" >Name</label>
</div>
<div class="md-form">
<input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="surname_kyt" >Surname</label>
</div>
<div class="md-form">
<input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="username_kyt" > Username </label>
</div>
<div class="md-form">
<input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="email_kyt" >Email</label>
</div>
<div class="md-form">
<input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="password_kyt" >Password</label>
</div>
<div class="md-form">
<input type="password" id="password_confirm" name="password_onay" class="form-control">
<label for="password_confirm" >Password Confirm</label>
</div>
<div class="form-group text-center">
<div class="row">
<div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
<input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
<p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>
</div>
</div>
</div>
<!-- End of Register Form -->
<?php echo form_close(); ?>
Please refer below example to validate a form in CodeIgniter using ajax call.
1. ajax code.
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
var formData = $("#register-form").serialize();
$.ajax({
type: 'get',
url: url + 'User/register',
data: formData,
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
2. Controller code :
Load form_validation library and form helper
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
public function register(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
} else {
echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
}
}else{
echo $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
}
}
}
}
I have solved this problem. Form validation only works with post method. If you use get method it won't work.

Taking post parameters in ajax comment form

I'm trying to customize one comment form from template which I purchased. In short I have 3 files - post.php, comment_post.php and main.js. In post.php is simple html comment form. I'm not that good in ajax part and still trying to learn php so I'll need some help with this.
<form class="row" role="form" id="comments-form" name="comments-form" action="comments-send.php" method="POST">
<input type="text" class="form-control form-name-error" name="comments[form-name]" id="form-name" placeholder="Name">
<input type="email" class="form-control form-email-error" id="form-email" name="comments[form-email]" placeholder="Email">
<input type="hidden" name="comments[post_id]" value="<?php echo $row['post_id'];?>" >
<textarea class="form-control input-row-2 form-review-error" rows="3" id="form-comments" name="comments[form-review]" placeholder="Comment"></textarea>
<div class="form-group text-right btn-submit">
<button type="submit" class="btn btn-dark button-submit">Send</button>
<div class="message-success alert-success alert hidden" style="position: absolute"><i class="fa fa-check"></i></div>
</div>
</form>
I have one hidden field to get post_id..
Here is comment_post.php which is the problem ( I think ). The errors are Undefined variable: comment_author_name, comment_author_image .. etc
if(isset($_POST['comments'])) {
$response = array('status' => '', 'errors'=>array());
foreach($_POST['comments'] as $key => $value) {
if($value == '') {
$response['errors'][$key.'-error'] = 'error';
}
}
if(empty($response['errors'])) {
$_POST['comments']['form-name'] = $comment_author_name;
$_POST['comments']['form-email'] = $comment_author_email;
$_POST['comments']['post_id'] = $post_id;
$_POST['comments']['form-review'] = $comment_text;
$sql = "INSERT INTO comments (comment_author_name, comment_author_email, comment_date, comment_text, post_id)
VALUES (:comment_author_name, :comment_author_email, NOW(), :comment_text, :post_id)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(":comment_author_name", $comment_author_name);
$stmt->bindValue(":comment_author_email", $comment_author_email);
$stmt->bindValue(":post_id", $post_id);
$stmt->bindValue(":comment_text", $comment_text);
$stmt->execute();
$response['status'] = 'ok';
} else {
$response['status'] = 'error';
}
echo json_encode($response);
}
In original file (comment_post.php) there is nothing for database insertion and this is my code. I'm not sure how to get values from the form when is send to the php part. This is from main.js file for the comment_form.
$("#comments-form").submit(function(e) {
$('#comments-form .form-control').removeClass('#comments-form message-error');
$.post("comments-send.php", $('#comments-form').serialize(), function(data) {
if (data.status === 'ok') {
$("#comments-form .message-success").removeClass('hidden').velocity({ opacity : 1 });
$("#comments-form .button-submit").addClass('button-transparent');
$('#comments-form .form-control').val('');
setTimeout(function() {
$("#comments-form .message-success").velocity({ opacity : 0 }, function() {
$(this).addClass('hidden');
});
$("#comments-form .button-submit").removeClass('button-transparent');
}, 3000);
} else {
$.each(data.errors, function(i, e) {
$('.' + i).addClass('#comments-form message-error');
});
}
}, 'json');
e.preventDefault();
});
$("#comments-form").on('keyup', '.contact-form', function() {
var that = this;
if ($(this).val() !== '') {
$(this).removeClass('message-error');
} else {
$(that).addClass('message-error');
}
});
It looks like you are not setting your variables correctly
update to this
$comment_author_name = $_POST['comments']['form-name'];
$comment_author_email = $_POST['comments']['form-email'];
$post_id = $_POST['comments']['post_id'];
$comment_text = $_POST['comments']['form-review'];
What you want to do is actually get the values from the $_POST and save them to the variables you have created.
Previously you were doing the oposite, therefore the variables did not exist and you were also reseting the values in your $_POST

How to return PHP response to HTML page using AJAX

I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">

How to check if email exist while typing in MYSQL using jQuery, AJAX and CodeIgniter

I want to validate my form's input with database, so when user type on form's input and contain email already in use or exists it will display an alert and cant submit. I use CodeIgniter framework and jQuery.
I've tried using the code below to check if name exists and this could work. But when I apply it to the other case for email, it doesn't work and display message "The URI you submitted has disallowed characters."
How is the correct way to fix this?
View (kasir_halaman.php) :
<div id="addModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Tambah Kasir</h3>
</div>
<div class="modal-body">
<form action="<?php echo site_url('admin/kasir/addpetugas'); ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label>
<input type="text" id="nama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="email" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" maxlength="30">
</div>
<div class="form-group">
<label>Ulangi Password</label>
<input type="password" name="confirmpassword" class="form-control" maxlength="30">
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Tambah</button>
</form>
</div>
</div>
</div>
</div>
Controller (kasir.php) :
public function cekData($table, $field, $data)
{
$match = $this->Crud->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
public function register_email_exists()
{
if (array_key_exists('email',$_POST)) {
if ($this->Crud->email_exists($this->input->post('email')) == TRUE ) {
echo false;
} else {
echo true;
}
}
}
Model (Crud.php) :
function email_exists($email)
{
$this->db->where('email', $email);
$query = $this->db->get('petugas');
if( $query->num_rows() > 0 ){ return TRUE; } else { return FALSE; }
}
jQuery AJAX (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/petugas/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
var check2=0;
$("#email").bind("keyup change", function(){
//var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
data:{send:true},
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
var check4=0;
$("#confirmpassword").bind("keyup change", function(){
var password = $("#password").val();
var confirmpassword = $(this).val();
if (password == confirmpassword){
$("#report4").text("");
check4=1;
}else{
$("#report4").text("*Password tidak sama");
check4=0;
}
});
$("#submit").click(function(event){
if(check1==0){
event.preventDefault();
}
if(check4==0){
event.preventDefault();
}
});
});
Use ajax post method instead and take data at php side from POST request
you can check more about jquery ajax here: http://api.jquery.com/jquery.post/
and about php post here: http://php.net/manual/en/reserved.variables.post.php
//JS
$("#email").bind("keyup change", function(){
var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
type: "POST",// <---- ADD this to mention that your ajax is post
data:{ send:true, email:email },// <-- ADD email here as pram to be submitted
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
// PHP
// At php side take your data from $_POST
$send = $_POST['send'];
$email = $_POST['email'];
...

Codeigniter twitter bootstrap login using Jquery

Am fairly new to using Jquery and am creating a login for a simple site am creating using CodeIgniter and bootstrap. After submitting the Log in button, it won't show any error or success message, meaning that I don't even know if it actually post the data to the controller
here's my code,
Jquery Code
<script>
//Wait until the DOM is fully loaded
$(document).ready(function(){
//Listen for the form submit
$('#loginform').submit(logIn);
});
//The function that handles the process
function logIn(event)
{
//Stop the form from submitting
event.preventDefault();
//Hide our form
// $('#loginform').slideUp();
//Collect our form data.
var form_data = {
email : $("[name='email']").val(),
password : $("[name='password']").val(),
};
//Begin the ajax call
$.ajax({
url: "admin",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
success: function (json) {
if (json.error==1)
{
//Show the user the errors.
$('#message').html(json.message);
} else {
//Hide our form
$('#loginform').slideUp();
//Show the success message
$('#message').html(json.message).show();
}
}
});
}
</script>
login.php
<?php
echo $this->session->flashdata('alert');
?>
<div id="message"></div>
<?php
$attr = array('class' => 'admin-login form-horizontal well form-signin', 'id' => 'loginform');
echo validation_errors('<div class="alert alert-error">', '</div>');
?>
<?php echo form_open(site_url('admin'), $attr) ?>
<!--<form action="<?php echo site_url('track-order'); ?>" method="post" class="form-horizontal form-search" id="trackModalform">-->
<div class="control-group">
<label class="control-label">Track Your Order</label>
</div>
<div class="control-group">
<label class="control-label" >Email:</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-qrcode"></i></span>
<input type="text" name="email" class="input-block-level email" placeholder="Email address">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" >Password:</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-key"></i></span>
<input type="password" name="password" class="input-block-level password" placeholder="Password">
</div>
</div>
</div>
<div class="form-actions" style="margin-bottom: 0px; padding-bottom: 0px;">
<input type="submit" class="btn btn-primary " name="signin" value="Sign In!" id="login">
</div>
</form>
my controller
public function index()
{
if (!file_exists('application/views/admin/index.php'))
{
//sorry that page is not available
show_404();
}
$this->form_validation->set_rules('email', 'Name', 'required|min_length[5]|max_length[50]|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() === TRUE)
{
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
} else {
//Save the data to the database, of course you will need all the data first.
if($this->admin_model->validate_admin_login()):
//Send the success to our javascript file.
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
endif;
}
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
}
model
public function validate_admin_login()
{
$this->str = do_hash($this->input->post('password')); // SHA1
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->str);
$query = $this->db->get('ip_admin');
if($query->num_rows == 1)
{
$data['admin_sess'] = $this->admin_model->admin_details($this->input->post('email'));
$data = array(
'email' => $this->input->post('email'),
'is_admin_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
}
public function admin_details($user)
{
$query = $this->db->select('*')->from('ip_admin')->where('email', $user);
$query = $query->get();
return $data['admin_sess'] = $query->row();
}
I don't really responding or outputting any message to indicate success or failure, maybe I got everything wrong to start with.
I need it to query the db, returns the message for me on the view page using the json parameter on my controller.
Thanks all.
I suggest you add a data in var_data like this:
var form_data = {
email : $("[name='email']").val(),
password : $("[name='password']").val(),
//add a data which is
ajax: '1'
};
And in your controller check if it is POST'ed:
if($this->input->post('ajax'){
//do something
}else{
//do something
}
so from there you could check if it is working or not. and also install firebug for debugging purposes in Firefox. In Chrome try to inspect element and see console
I honestly haven't gone through all your code as it really isn't that complicated, instead I'd like to suggest you install Firebug to debug your jquery if you haven't already installed it. Its essential when developing with javascript. It will print any errors or success as events are called and handled.
How to use: Firebug FAQ
EDIT:
As you asked for code:
if($this->form_validation->run() === TRUE)
{
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
} else {
//Save the data to the database, of course you will need all the data first.
if($this->admin_model->validate_admin_login()):
//Send the success to our javascript file.
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
endif;
}
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
Wtihin this block, you're echo'ing json once and then spitting out the HTML view afterwards. Just try removing the:
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
Or create separate controller functions for your requests, things get really messy when you try to stuff everything into a single function.

Categories