Data check in database if already exist in codeigniter through ajax - php

I want to check data in database through ajax in codeigniter how can get check name already exist through ajax
controller
public function insert(){
$user = array('Name' => $this->input->post('name'),
'Cnic' => $this->input->post('cnic'),
'Phone' => $this->input->post('phone'),
'Address' => $this->input->post('address'),
);
$this->load->model('suppliermodel');
if($this->suppliermodel->checkData($user['Name'])){
if ($this->session->userdata('user_id'))
$detail = 'Already exist';
$this->load->view('admin/includes/header');
$this->load->view('admin/includes/sidemenu');
$this->load->view('admin/add_supplier',['exist'=>$detail]);
$this->load->view('admin/includes/footer');
$this->load->view('admin/includes/add_supplier_footer');
}
else{
$this->suppliermodel->add($user);
}
}
model
public function checkData()
{
$name = $this->input->post('name');
$this->db->select('*');
$this->db->where('Name', $name);
$this->db->from('suppliers');
$query = $this->db->get();
if($query->num_rows() >0){
return $query->result();
}
else{
return $query->result();
return false;
}
}
what is ajax code and controller function

How about this?
Controller
public function insert(){
// set a rule that make the Name field is unique by 'set_rules'
$this->form_validation->set_rules('Name', 'Name Field', 'required|is_unique[suppliers.name]');
//$this->form_validation->set_rules('[Other Field]', '[Field Name to Display]', '[Restriction]');
// if the field cannot pass the rule
if ($this->form_validation->run() === FALSE) {
$errors = array();
foreach ($this->input->post() as $key => $value) {
// Add the error message for this field
$errors[$key] = strip_tags(form_error($key));
}
// Clear the empty fields (correct)
$response['errors'] = array_filter($errors);
$response['status'] = false;
}
else {
// otherwise, call the model
$result = $this->suppliermodel->add($user);
if ( $result ) {
$response['status'] = true;
}
}
echo json_encode($response);
}
JavaScript
$.ajax({
url: '//localhost/insert',
data: {
Name: $('input[name=Name]').val(),
Cnic: $('input[name=Cnic]').val(),
Phone: $('input[name=Phone]').val(),
Address: $('input[name=Address]').val()
},
dataType: 'JSON',
type: 'POST',
error: function(xhr) {
alert('request failed!');
},
success: function(response) {
var response = $.parseJSON(JSON.stringify(response));
if (response.status != true) {
$.each(response.errors, function(field, i) {
alert( field+ ' errors with ' + i)
});
}
else {
alert('success!');
}
}
});
Use is_unique[table.fieldToCompare] to make the field is always unique.
Wish it helps.
set_rules restrictions, see the Codeigniter User Guide Form validation
If fails, the controller would return a set of JSON, with field and error message. Then you can handle it in $.ajax's success.

Related

How to validate an empty checkbox and display message via AJAX using CodeIgniter form validation library?

Displaying form error message when checkbox is not checked using CodeIgniter form validation library.
Currently, form error message is displayed only when checkbox is checked.
Here is AJAX call:
$('#add_user').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
method : "post",
data: $(this).serialize(),
dataType: "json",
success: function(result) {
if(result.success == true) {
alert('Success');
} else {
$.each(result.errors, function(key, value) {
var error = $('#' + key);
error.closest('div.form-group')
.find('.error').remove();
error.after(value);
});
}
}
});
});
And here is PHP controller:
$this->form_validation->set_rules('agreement', 'Agreement', 'callback_agreement_checkbox');
if($this->form_validation->run()) {
$data['success'] = true;
$this->load->view('Success');
} else {
foreach($this->input->post() as $key => $value) {
$data['errors'][$key] = form_error($key);
}
echo json_encode($data);
}
public function agreement_checkbox() {
if (empty($this->input->post('agreement'))) {
return FALSE;
} else {
$error = 'Please accept TOS';
$this->form_validation->set_message('agreement_checkbox', $error);
return TRUE;
}
}
When the form is submitted without checkbox checked, error message is not displayed (but it should). It's displayed only when checkbox is checked and it's wrong.
EDIT:
I've done some modifications for support of mixing different input data:
$this->form_validation->set_rules('first_name', 'First name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last name', 'trim|required');
$this->form_validation->set_rules('email', 'E-mail', 'trim|required');
$this->form_validation->set_rules('agreement', 'Agreement', 'required');
if($this->form_validation->run()) {
$data['success'] = true;
$this->load->view('Success');
} else {
foreach($this->input->post() as $key => $value) {
$data['errors'][$key] = form_error($key);
}
if (empty($this->input->post('agreement'))) {
$data['errors']['agreement'] = form_error('agreement', '<div id="agreement_error">', '</div>');
}
echo json_encode($data);
}
Callback function of Codeigniter does not defined $this->input->post() . I suggest you to use required. So it will be like this.
$this->form_validation->set_rules('agreement', 'Agreement', 'required');
it will defined if the check box was checked before it submitted. then change this code too.
if($this->form_validation->run()) {
if(! empty($this->input->post('agreement))){
$data['success'] = "It was checked";
}else{
$data['error'] = validation_errors();
}
echo json_encode($data);
}
Your ajax:
success: function(result) {
if(result.success) {
console.log(result.success);
} else {
console.log(result.error);
}
}
Let me know the result.

How to validate fields using the functions .each() and ajax()

So. I am trying create a fields validation using ajax. I have created the class "validate-field" on the fields where is a necessary a validation.
One Field is email_addres and another is taxvat. On my controller I just created thea action "validate" and then I am trying get the Field ID and Field Value.
Follow the codes below:
-the jQuery:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".continuar").on("click", function(){
url = "<?php echo Mage::getUrl('awmajax/ajax/validar')?>";
jQuery(".required-entry").each(function(){
if(jQuery(this).val() == ""){
jQuery(this).addClass("validation-failed");
}
else {
jQuery(this).removeClass("validation-failed");
}
});
jQuery(".validate-field").each(function(){
fieldName = jQuery(this).attr('id');
fieldValue = jQuery(this).val();
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
data: ({
field : fieldName,
value : fieldValue
}),
success: function(result){
console.log(result);
}
});
});
});
});
</script>
and the php:
public function validarAction(){
$params = $this->getRequest()->getParams();
if($params['field'] == 'taxvat'){
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if($validacao == false){
$resultTaxvat = array(
"response" => "Taxvat is not valid",
"field" => $params['field']
);
}
$this->getResponse()->setBody(json_encode($resultTaxvat));
}
if($params['field'] = 'email_address'){
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
$resultEmail = array(
"response" => $validacaoEmail, //Type a valid Email
"field" => $params['field']
);
$this->getResponse()->setBody(json_encode($resultEmail));
}
}
What is the problem:
I get always just the email response on the second "If".
Any help is welcome.
Cheers
your second IF statement is passing a value and not comparing... I think you were supposed to write if ($params['field'] === 'email_address')
regarding your issue, try this:
public function validarAction()
{
$params = $this->getRequest()->getParams();
$error = false;
$errors = [];
if ($params['field'] == 'taxvat') {
$taxvat = $params['value'];
$validacao = Mage::helper('awm_awmajax')->validaCPF($taxvat);
if (!$validacao) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Taxvat is not valid',
];
}
}
if ($params['field'] === 'email_address') {
$emailAddress = $params['value'];
$validacaoEmail = Mage::helper('awm_awmajax')->checkEmailExists($emailAddress);
if (!$$validacaoEmail) {
$error = true;
$errors[] = [
'field' => $params['field'],
'message' => 'Type a valid Email',
];
}
}
$this->getResponse()->setBody(json_encode([
'error' => $error,
'errors' => $errors
]));
}
...tyr to use a loop construct to refactor this. as this may result in a lot of IF statements if you are going to validate a lot of fields.
EDIT:
Changed $result to $errors and the JSON index status to error. It would be easier to iterate with the updated code on your JS.

Internal server error 500(codeigniter, ajax)

I want to check if the user email already exists in the database. For which I have build the following code.
AJAX code:
function emailCheck(){
console.log("hello");
var email = $("#email").val();;
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>myCon/customerCheck',
data: {email:email},
success:function(response){
$('#test').html(response);
}
});
}
myCon controller's function:
public function customerCheck(){
$this->load->model('CustomerModel');
$res = $this->customerModel->customerMailCheck();
echo json_encode($res);
}
customerModel model's function:
function customerMailCheck(){
$mail = $this->input->post('email');
$result = $this->db->get_where('privilege_customer', array('email' => $mail);
return $result->result();
}
Now whenever I call that function am getting error stating that internal server error 500.
Is there any better way to do this?
You can try this solution for your problem.
Please add below code in your header of page
<script type="text/javascript">
base_url = '<?=base_url()?>';
</script>
Changes your controller function.
public function customerCheck(){
if ($this->input->is_ajax_request()) {
$this->load->model('CustomerModel');
$mail = $this->input->post('email');
$res = $this->customerModel->customerMailCheck($mail);
if(!empty($res)) {
$data['status'] = 'success';
$data['message'] = 'Email Adress is found';
} else {
$data['status'] = 'error';
$data['message'] = 'Data not found';
}
echo json_encode($data);
exit;
} else{
redirect('login/logout');
}
}
Change Ajax Code
function emailCheck(){
var email = $("#email").val();;
jQuery.ajax({
type: 'POST',
url : base_url +'myCon/customerCheck',
data: {email:email},
success:function(response){
if(response.status=="success"){
$('#test').html(response.message);
} else {
console.log(response.message)
}
}
});
}
CustomerModel model's function:
function customerMailCheck($mail){
$result = $this->db->get_where('privilege_customer', array('email' => $mail));
return $result->result();
}
I hope this will helps you.
One bracket ) is missing in your model function:
Try this:
function customerMailCheck(){
$mail = $this->input->post('email');
$result = $this->db->get_where('privilege_customer', array('email' => $mail));
return $result->result();
}
You must receive ajax request in controller and pass it to model
myCon controller
public function customerCheck(){
$this->load->model('CustomerModel');
-----> $mail = $this->input->post('email'); ------v
$res = $this->customerModel->customerMailCheck($mail);
echo json_encode($res);
}
Model :
function customerMailCheck($mail){
$result = $this->db->get_where('privilege_customer', array('email' => $mail);
return $result->result();
}
Try This
Script : Here you missed Bouble Qutes
function emailCheck(){
console.log("hello");
var email = $("#email").val();;
jQuery.ajax({
type: 'POST',
url: '<?=site_url()?>myCon/customerCheck',
data: {"email":email},
success:function(response){
$('#test').html(response);
}
});
}
Model : Here you missed ) in $result= line
function customerMailCheck() {
$mail = $this->input->post('email');
$result = $this->db->get_where('privilege_customer', array('email' => $mail));
return $result->result();
}

Codeigniter: Ajax data is printing in log but not working in function

I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);

Authentication using Cakephp and PhoneGap

I am working on an application using Cakephp on the server side and PhoneGap at the client Side, with JSON as a intermediate to access the server side.
Now, I am working specifically on a login form where the user needs to enter his/her username and password. I put in my controller the following:
public function api_login() {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization");
if ($this->request->data && isset($this->request->data['username']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'username'=> $this->request->data['username'],
'password' => $this->request->data['password']
)
));
if (count($arrUser) > 0 ) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array('loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
}
else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
and in the client side, I am retrieving what JSON encoded as follows:
<script>
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault();
$username = $("#form-username").val();
$password = $("#form-password").val();
$.ajax({
url : "http://localhost/teslaphonegap_cakephp/" + 'login.json',
cache : false,
data : {
'username' : $username,
'password' : $password },
dataType : 'json',
type : 'POST',
success : function(result) {
if(result.status=="SUCCESS"){
alert("success");
console.log(result);
}else{
alert("username or pass are wrong");
console.log(result);
} },
error : function(xhr, status, err) {
alert("ERROR");
}
});
});
});
</script>
and in my Model I used the beforeSave() in order to hash the passwords before they get added at the very beginning in the Database:
public function beforeSave($options = array()) {
$value=$this->data['User']['password'];
$encrypted = Security::encrypt($value, Configure::read('Security.cipherCriptKey'));
$this->data['User']['password'] = $encrypted;
return true;
}
Now, when I try to login it always returns the error message because it compares a value that is unhashed with other values that are already hashed in my Database. How can I solve this issue? I used the afterFind() but it didn't work:
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if(isset($val['User']['password'])){
$results['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
}
return $results;
}
}
-- EDIT
and in my core.php I used the following:
Configure::write('Security.cipherCriptKey','su0HKssPmdbwgK6LdQLqzp0Y7zOmyaTI');
First of all, your afterFind() callback won't work as expected.
The line
$results['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
should be written as
$results[$key]['User']['password'] = Security::decrypt($val['User']['password'], Configure::read('Security.cipherCriptKey'));
However, changing this won't fix your problem. If you search the database for a record with a password matching $this->request->data['password'], it will return no results. Note that the password in the database is hashed.
You have to fetch the record from table users that matches $this->request->data['username'], decrypt the value of field password and compare it against $this->request->data['password'].
Decryption is already taken care by afterFind(), so your code could be written as follows:
if ($this->request->data && isset($this->request->data['username']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('first',array(
'conditions'=>array(
'username'=> $this->request->data['username'],
)
));
if ($this->request->data['password'] == $arrUser['User']['password']) {
$this->Session->write('Auth.User',$arrUser['User']);
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array('loginSuccess' => 1,'user_id' => $arrUser['User']['id'] );
//rest of your code

Categories