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();
}
Related
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.
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);
Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.
Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
I am using codeigniter to develop my app. And I am using jquery to send some json data.
This is my code :
Model :
public function updateRequest($id_request, $jenis_request, $keluhan ){
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
return $query->row();
controller :
public function updateRequest(){
$id = $_POST['id'];
$jenis_request = $_POST['jenis_request'];
$keluhan = $_POST['keluhan'];
$row = $this->model_request->updateRequest($id, $jenis_request, $keluhan );
echo json_encode($row);
}
This is the view using ajax
$('#btn-footer').click(function(e) {
e.preventDefault();
var id = $("#mainTitle strong").text().split("/").pop();
/*get value checkbox*/
var jenis_request = [];//console.log($("input[name='request[]']"));
$("input[name='request[]']:checked").each(function() {
//console.log($(this).val());
jenis_request .push($(this).val());
});
jenis_request = jenis_request.join(',');
alert(jenis_request); //for check
/*ambil keluhan*/
var keluhan = $('#modalkeluhan').val();
$.ajax({
url: '<?php echo base_url() . 'control_closing/updateRequest/' ?>',
type : 'POST',
data : {id : id ,
jenis_request : jenis_request,
keluhan : keluhan
},
dataType: 'json',
success: function (obj) {
console.log(obj);
}
});
});
I got this error, Call to a member function row() on a non-object ,
I know that row() is an object, is that a problem ?
This may help you
public function updateRequest($id_request, $jenis_request, $keluhan )
{
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
$affected_rows=$this->db->affected_rows();
if($affected_rows >0)
{
return $affected_rows." rows updated";//return here the way you want
}
else
{
return "No updates";
}
}
i have written this script in View. In onblur event i have check whether the mail id is already exits r not.for that i have to pass mailId id to the controller action and i want to get the return result.
$.ajax({
type: "POST",
url: "<?php Yii::app()->createAbsoluteUrl("Approval/checkMailid"); ?>",
data: mailId,
success: function() {
return data;
},
error: function() {
alert('Error occured');
}
});
public function actionCheckMailid($mailId)
{
$model = YourModel::model()->findAll('id = :mid', array(':mid'=>$mailId));
echo json_encdoe($model);
}
Just need to throw a 404 page and ajax error handle can catch it.
public function actionCheckMailid($mailId){
$exist = Yii::app()->db->createCommand('select count(*) from your_email_table where id_email = :id_email')
->queryScalar(array(
'id_email' => $mailId
));
if($exist > 0){
echo json_encode(array(
'success'=>true
));
}else{
throw new CHttpException('Email can not be found');
}
}