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);
Related
I tried creating a universal delete function in 3 ways.
function DeleteByID($table, $id){
1. DB::table("$table")->delete("$id");
2. DB::table("$table")->find("$id")->delete();
3. DB::table("$table")->where('id', '=', "$id")->delete();
}
I'm using ajax to send the request to an Ajax Controller class, which sends it to the according controller class of the specific subject. Everything goes fine with the ajax request, it does what it should do. But deleting something from the table doesn't work.
And yes, I am putting the right table names into the $table parameter when I'm calling the DeleteByID($table, $id) function.
Update 1
removed every double "" from the ajax request to the call of the delete function.
DB::table($table)->where('id', '=', $value)->delete();
Is what it is now. Still doesn't work.
Update 2
This triggers the DeleteRole function. This will open a modal, asking if you are sure you want to delete the record. there will be another button with onclick="DeleteRole(this.id, true)" with ofcourse the id send with it.
<a id="{{$role->id}}" onclick="DeleteRole(this.id, false)">
<button class="btn btn-neutral btn-icon btn-round" data-toggle="modal"
id="{{$role->id}}" data-target="#rolesModalDelete">
<i class="material-icons" style="color:rgba(185,14,22,0.81)">clear</i>
</button>
</a>
AJAX Request:
function DeleteRole(id, bool){
let contentModal = $('#DeleteRoleContent');
if(bool === false){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/DeleteRole',
type: 'POST',
dataType: "json",
beforeSend: function (xhr) {
const token = jQuery('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {
roleID: id,
popup: bool,
},
success: function (data) {
contentModal.empty();
contentModal.append(data);
}
});
}else if (bool === true){
let row = $('#' + id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/DeleteRole',
type: 'POST',
dataType: "json",
beforeSend: function (xhr) {
const token = jQuery('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {
roleID: id,
popup: bool,
},
success: function (data) {
row.empty();
}
});
}
}
Update 3
The if statement where it checks if the $_POST['popup'] is true or not, was ignored. Changed it, so the deletion works now. But now the succes handler won't be called. the ajaxrequest returns 200 OK.
public function RoleDelete()
{
if($_POST['roleID']){
if($_POST['popup'] == 0){
$htmlObject = $this->roleController->GetData($_POST['roleID']);
echo json_encode($htmlObject);
} else {
if($_POST['roleID'] !== null) {
$this->db->DeleteByID('rollen', $_POST['roleID']);
} else {
echo json_encode('ID is null');
}
}
} else {
echo json_encode('Geen gegevens gevonden, is het record al verwijderd? AC 256;');
}
}
You should try this
Do not use "" for variable
1. DB::table($table)->delete($id);
2. DB::table($table)->find($id)->delete();
3. DB::table($table)->where('id', '=', $id)->delete();
I apologize if this comes off as a "make sure it's plugged in" kind of answer, but sometimes the simple stuff is the easiest to overlook, especially when you're tunnel-visioned on the code. That said, are you sure your DB credentials actually have delete-permissions?
The if statement where it checks if the $_POST['popup'] is true or not, was ignored. Changed it, so the deletion works now. But now the succes handler won't be called. the ajaxrequest returns 200 OK.
public function RoleDelete(){
if($_POST['roleID']){
if($_POST['popup'] == 0){
$htmlObject = $this->roleController->GetData($_POST['roleID']);
echo json_encode($htmlObject);
} else {
if($_POST['roleID'] !== null) {
$this->db->DeleteByID('rollen', $_POST['roleID']);
} else {
echo json_encode('ID is null');
}
}
} else {
echo json_encode('Geen gegevens gevonden, is het record al verwijderd? AC 256;');
}
}
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()`
}
});
This is my AJAX call:
function ck_loader() {
row_count = $('.grid-item').length || 0;
$.ajax({
type: "POST",
url: baseURL + "welcome/load_more",
data: {offset: row_count, numbdata: permaData},
datatype: 'json',
success: function (response) {
if (response === "") {
$grid.packery();
}
} else {
var $response = $(response);
$(".grid").append($response);
$grid.packery( 'addItems', $response);
$grid.packery();
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
//alert("ERROR");
}
});
so offset counts number of elements (rows) that are visable at the moment, and it helps control the offset of database (loading 15 elements per call)
numbdata: permaData is a variable where I'm saving the filter selection, so my menu has a filter selection, and data from there is saved in a variable (when someone press "video" filter, it saves "video" inside of permaData)
It connects to:
public function load_more()
{
$offset = $this->input->post('offset');
if($offset)
{
$new_rows = $this->postovi_model->get_next_10($offset);
if(isset($new_rows))
{
$data['users'] = $new_rows;
//this will return (echo) html to the ajax success function
//CI takes care of making the correct response headers - sweet
$this->load->view('user_rows_view', $data);
}
else
{
echo ""; //return an empty string
}
}
}
There is a model included in this PHP script:
public function get_next_10($offset = 0)
{
$this->db->limit(15, $offset);
$this->db->order_by('date', 'asc');
$query = $this->db->get("postovi");
return $query->num_rows() > 0 ? $query->result_array() : NULL;
}
}
In this model I am missing WHERE and the WHERE filter is the same as $permaData.
Every filter should reset $Offset back to 0 and run Database for that content.
permaData starts with "*" before any filter is selected.
Change your model function to take two parameters instead of one:
public function get_next_10($offset = 0, $numbdata = false)
and then just call it like:
$new_rows = $this->postovi_model->get_next_10($offset, $numbdata);
while numbdata would be (you're passing that via the AJAX call anyway):
$numbdata = $this->input->post('numbdata');
and finally, just add the WHERE clause in the model.
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');
}
}
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;
}
...
}