Send custom error message in Ajax error in codeigniter - php

I am currently using Codeigniter and working on CRUD operation in one HTML form.
I am using Ajax for this create/read/update.
I have also used Transaction Management as best practices in a database query.
The Problem:
(1) I want separate Error message for Update and Insert Error. Which I did not get in the ajax error section.
(2) I have used the debugger to debug this problem but I do not get it proper.
Here is the Code of my controller.
Controller:
public function save_candidate_experience() {
$this->db->trans_start();
if(empty($postId))){
$query_staus = $this->test_model->insert_function( $data );
if($query_staus != TRUE) {
$msg = array('message'=>'Failed To Save! Erroe Wile Inserting.');
} else{
$msg = array('message'=>'Successfully Insert');
}
} else {
$query_staus2 = $this->test_model->update_function( $data );
if($query_staus2 != TRUE) {
$msg = array('message'=>'Failed To Save! Erroe Wile Updateing.');
}else{
$msg = array('message'=>'Successfully Updated');
}
}
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
echo json_encode ($msg);
}
else
{
$this->db->trans_commit();
echo json_encode ($msg);
}
}
This is the Model Code:
public function insert_function() {
$this->db->insert('table_name', $data);
if($this->db->affected_rows() > 0){
return TRUE;
} else{
return FALSE;
}
}
public function update_function() {
$this->db->where('id', $id);
$this->db->update('test_table', $data);
if($this->db->affected_rows() > 0){
return TRUE;
} else{
return FALSE;
}
}
Ajax Code in my view.
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: save_experience,
data: $('#candidata_exp_form').serialize(),
success: function (response) {
//doing something with ajax success
},error: function (msg)
{
alert(msg.message);
// I know I can give alert message here but.
//I don't want to give alert message here.
//I want to indicate user that the error occure whilt insert or update seperately.
}
});

You have to understand 2 things.
Form validation error and ajax error is different.
Ajax error - Is not validation error.
It means, suppose you call a function and there is php error in that function, or 404 error. At that time .error() will be called.
Ajax Success - No error(No syntax error).
So now you should write the logic in ajax success().
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: save_experience,
data: $('#candidata_exp_form').serialize(),
success: function (response) {
alert(response.message);// this will alert you the message which you have put in `json_encode()`
}
});

Related

Confirming A Database Row was deleted via PHP in aJax/jQuery

I'm trying to figure out the best way to relay back to ajax if the POST data sent to the .php file successfully deleted the data from the database. I'm not sure what to phrase what I'm looking for, but essentially I thought about a 'if() { } else { }' statement perhaps, but I'm not sure how to send the data back correctly into the success:function. Here is the basic code below that ajax is using. The PHP file is just standard code for running a deletion via php/mysqli.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
//IF() {
//EXECUTE SUCCESS & REMOVE DIV
//} ELSE {
//GIVE NOTICE OF DELETION FAILURE
//}
}
});
So anyone have any ideas how I could accomplish this?
On your php. depends on what you are using, you can check if the query was successful or not. then you can add anything on your return statement that you could use on your ajax success funtion.
Example:
on the php side using PDO
$success = true;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "DELETE FROM MyGuests WHERE id=3";
$conn->exec($sql);
} catch (PDOException $e) {
$success = false;
}
return json_encode([
'success' => $success
])
Then on ajax. you can use this
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
IF(data.success) {
//EXECUTE SUCCESS & REMOVE DIV
} ELSE {
//GIVE NOTICE OF DELETION FAILURE
}
}});
Some changes in your php file. if delete query return success then return true or 1 otherwise false or 0.
$.ajax({
url: "../ajax/modules/delete-from-db.php",
data:{},
type:'POST',
success:function(data){
if(data == 1){
alert("success");
} else {
alert("error");
}
}
});
it depends on what you send back from your php script, i recommend JSON which you could format as such
{
status:"success",//or error if failed
message:"record was successfully deleted"
}
in the php script you could have a Boolean flag to check if the record was deleted eg:
if($deleteFlag){
$response = array('status'=>'success', 'message'=>'record was successfully deleted');
} else {
$response = array('status'=>'error', 'message'=>'could not delete record!');
}
header('Content-type: application/json');
echo json_encode($response);

Laravel Ajax - success executed even when db row is not present

I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);

what is the correct way to process database?

The code below only deletes the data when I add the extra statement in the controller. why is that?
I've only been using codeigniter for a few months now and I keep getting stuck with weird bugs like this.
this is the models file:
My_model.php
function delete_data($where=array())
{
return $this->db->delete('table1', $where);
}
and the code in controller:
tasks.php
function do_delete_data()
{
$this->load->model('My_model');
$result = array('status' => '', 'message' => '');
try
{
$this->db->trans_begin();
$id = $this->input->post('post_id', TRUE);
if ( ! $this->My_model->delete_data(array('id' => $id)))
{
throw new Exception('Database process failed.');
}
$result['message'] = $this->db->last_query(); // extra statement
$this->db->trans_commit();
$result['status'] = 1;
}
catch(Exception $e)
{
$this->db->trans_rollback();
$result['message'] = $e->getMessage();
}
if ($this->input->is_ajax_request())
{
echo json_encode($result);
}
}
it works fine until recently I tried to call this function via ajax like this:
display.php
$.ajax({
url: '/tasks/do_delete_data',
type: 'post',
data: {
'post_id' : $('#post_id').val(), // e.g. 12
},
dataType: 'json',
success: function(response) {
alert('File deleted successfully.');
console.log(response);
},
error: function(e) {
alert('an error occurred.');
}
});
You are using id in ajax param but using post_id as in your controller, which is undefined index.
You need to correct your index name as:
$id = $this->input->post('id', TRUE); // use id
It's better to check what are you getting in controller by using print_r($_POST) this will you to understand, what kind of array are you getting from ajax data.

ajax returning true while FALSE

I am using codeigniter, i have written a function to check if a user password exists which it does. This is my model
The model: user
public function get_some_password($username,$password) {
$this->db->where('user_password', $password);
$this->db->where('user_username',$username);
$query=$this->db->get('some_users_table');
if($query->num_rows()==1){
return true;
}else{
return false;
}
the controller
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
$this->user->get_some_password($username,$password);
}
The ajax on the view
//done on page load
var success1 = $(".success"); //a div on the view that appears if success
var error1 = $(".error"); //a div on the view that appears if error
success1.hide();
error1.hide();
$('#change_password').click(function() {
var username = $('#username').val();
dataString2 = $('#changpassword').serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>controller_name/check_password/' + username,
data: dataString2,
success: function() {
$('.success').html('password successfully updated!'),
success1.slideDown('slow');
},
error: function() {
$('.error').html('Wrong current password!'),
error1.slideDown('slow');
}
});
The problem: Ajax loads the success div even when the username or password returned is false, where am i missing something
This is a correct behavior as jquery error is executed when response code is not 200:
1) You can parse returned value in success method.
e.g.
success: function(data) {
if (data == 'true') {
// Success
} else {
// Error
}
}
2) You can return error code from server 404, 500, 503 ... To trigger execution of error function.
e.g.
header("Status: 404 Not Found");
note: Header should executed before any output is done.
Try in your controller:
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
if(!$this->user->get_some_password($username,$password)) {
$this->output->set_status_header('500');
return;
}
...
}

CodeIgniter ajax call using jquery when call redirect it prints the whole page i div

no title that fits this bug but this how it goes, i have form with a submit button when pressed jquery ajax calls the controller and the form validation is done if it fails the form is redrawn if it passes the page is redirected to the home page with flash message successes and thats where the bug happens it redraws the whole page in the content(header header footer footer). i hope it makes sense seeing is believing so here is the code
side notes: "autform" is a lib for creating forms "rest" is a lib for templates.
the jquery code:
$("form.user_form").live("submit",function() {
$("#loader").removeClass('hidden');
$.ajax({
async :false,
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
data: $(this).serialize(),
success: function(data) {
$("#center").html(data);
$('div#notification').hide().slideDown('slow').delay(20000).slideUp('slow');
}
})
return false;
});
the controller
function forgot_password()
{
$this->form_validation->set_rules('login',lang('email_or_login'), 'trim|required|xss_clean');
$this->autoform->add(array('name'=>'login', 'type'=>'text', 'label'=> lang('email_or_login')));
$data['errors'] = array();
if ($this->form_validation->run($this)) { // validation ok
if (!is_null($data = $this->auth->forgot_password(
$this->form_validation->set_value('login')))) {
$this-> _show_message(lang('auth_message_new_password_sent'));
} else {
$data['message']=$this-> _message(lang('error_found'), false); // fail
$errors = $this->auth->get_error_message();
foreach ($errors as $k => $v){
$this->autoform->set_error($k, lang($v));
}
}
}
$this->autoform->add(array('name'=>'forgot_button', 'type'=>'submit','value' =>lang('new_password')));
$data['form']= $this->autoform->generate('','class="user_form"');
$this->set_page('forms/default', $data);
if ( !$this->input->is_ajax_request()) { $this->rest->setPage(''); }
else { echo $this->rest->setPage_ajax('content'); }
}
}
function _show_message($message, $state = true)
{
if($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
}else{
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
redirect(base_url(),'refresh');
}
i think it as if the redirect call is caught by ajax and instead of sending me the home page it loads the home page in the place of the form.
thanks for any help
regards
OK found the problem and solution, it seemed you cant call a redirect in the middle of an Ajax call that is trying to return a chunk of HTML to a div, the result will be placing the redirected HTML in the div.
The solution as suggested by PhilTem at http://codeigniter.com/forums/viewthread/210403/
is when you want to redirect and the call is made by Ajax then return a value with the redirect URI back to Ajax and let it redirect instead.
For anyone interested in the code:
The Jquery Ajax code:
$("form.user_form").live("submit", function(event) {
event.preventDefault();
$("#loader").removeClass('hidden');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
dataType:"html",
data: $(this).serialize(),
success: function(data) {
var res = $(data).filter('span.redirect');
if ($(res).html() != null) {
[removed].href=$(res).html();
return false;
}
$("#center").html(data);
},
error: function() {
}
})
return false;
});
The PHP Controller
function _show_message($message, $state = true, $redirect = '')
{
if ($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
} else {
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
if ( !$this->input->is_ajax_request())
{
redirect(base_url() . $redirect, 'location', 302);
}
else
{
echo '<span class="redirect">'.base_url().$redirect.'</span>';
}
}
just use individual errors
json_encode(array(
'fieldname' => form_error('fieldname')
));
AJAX
success: function(cb)
{
if(fieldname)
{
{fieldname}.after(cb.fieldname)
}
}
see this

Categories