ajax returning true while FALSE - php

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;
}
...
}

Related

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);

Send custom error message in Ajax error in codeigniter

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()`
}
});

PHP Return Value from Controller to Ajax

I am using a MVC and I have a button that is using an AJAX call to remove an uploaded image on the site.
This is my Model:
public function remove_document($documentID, $documentName)
{
$objData = $this->objDB
-> setStoredProc('attritionRemoveDocument')
-> setParam('documentID', $documentID)
-> setParam('documentName', $documentName)
-> execStoredProc()
-> parseXML();
return $objData->data->response;
}
The response back from this is either true or false.
Here is my controller:
public function deleteFile()
{
// Get the documentID we are removing
$documentID = $this->input->post('documentID');
$documentName = $this->input->post('documentName');
// Check if the file is even there
if (file_exists('./uploads/'.$documentName)){
// Remove file
unlink('./uploads/'.$documentName);
$removeFile = $this->submit_model->remove_document($documentID, $documentName);
return $removeFile;
}
}
And finally, my AJAX Call:
$('[name=deleteDocument]').click(function() {
var documentID = $(this).attr('documentID'),
documentName = $(this).attr('documentName');
//Delete the image
$.ajax({
type: 'POST',
url: '../deleteFile',
dataType: 'xml',
data: {
'documentID': documentID,
'documentName': documentName
},
success: function(msg) {
// On Success, remove the current file section
console.log(msg);
}
});
});
When i echo the $removeFile value in the controller, I see the true/false value however it never makes it to the success function of the AJAX call.
Any ideas?
in Controller
if the result is true
echo "OK"
if the result is false
echo "NO"
in your View and in success part
success: function(msg) {
if(msg=="OK"){
alert("DELETED");
}else{
alert("NOT deleted");
}
Your controller should not return BOOL if you are using it with ajax , Your AJAX call , should control the result by success method .

Getting Foreach Data

I am trying to get foreach data I am using jquery to submit the page without a refresh being required for some reason jQuery is not retrieving the foreach data, It needs to loop through each admin input field to see each data seperatly.
If it's not possible I won't use JQuery for this but thought I ask
PHP:
if(isset($_POST['admin_add']) AND is_array($_POST['admin_add'])) {
foreach($_POST['admin_add'] as $admin_add) {
if(strlen($admin_add) > 0) {
// $sql=mysql_query("insert into hobbies(hobby)values('$hobby')");
}
}
}
die('<h3>'.$admin_add.'<h3/>');
jQuery:
$(document).ready(function () {
var clan_url_string = window.location.search.substring(1);
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
clan_title_edit: $('#clan_title_edit').val(),
clan_des: $('#clan_des').val(),
admin_add: $('#admin_add').val(),
//remember_me: ($('#remember_me').is(':checked')) ? 1 : 0
}
}
$(window).load(function(){
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
setInterval('cycleImages()', 4000); // run every 4s
});
function loading(e) {
$('#loading_status').show();
}
function hide_loading(e) {
$('#loading_status').hide();
}
function success_message(e) {
$('#success_login').html("We're Just Signing You In");
}
function clearfields() {
$('#login-username').val(''); //Clear the user login id field
$('#login_password').val(''); //Clear the user login password field
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/save_settings.php?'+clan_url_string,
type: 'post',
error: function () {
//If your response from the server is a statuscode error. do this!!!'
hide_loading(e);
$('#status_message').html('<b>Something Has Gone Wrong</b><br> Please Try Again Later');
},
beforeSend: function () {
loading(e);
},
data: {
clan_title_edit: $('#clan_title_edit').val(),
clan_des: $('#clan_des').val(),
admin_add: $('#admin_add').val(),
remember_me: ($('#remember_me').is(':checked'))
}, // get current values
success: function (data) {
//if your response is a plain text. (e.g incorrect username or password)
hide_loading(e);
$('#status_message').hide();
$('#status_message').fadeIn(1000).html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#login_content').keyup(function (e) {
if (e.keyCode == 13) {
var username = $('#login-username').val();
check(e);
}
});
$('#submit_clan_settings').click(function (e) {
if (e.keyCode != 13) {
check(e);
}
});
There's the php and jquery
Thanks
Yes its SQL injection prone, havent fix this yet and I should be using mysqli or $db->);

How to get the response and return result from controller action to view

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');
}
}

Categories