why is this failing.
my view code
function Dispose(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url:"<?php echo site_url('Login/ajax_delete')?>" ,
type: 'post',
data: {'id' : id},
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
}
}
controller code:
public function ajax_delete()
{
$id = $this->input->post('id');
$this->mod->delete_by_id($id);
}
model code:
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete('chemicalBottleInfo');
}
what i want to happen is to delete the item from chemicalbottleinfo
Your are passing id was wrong should not be quotes
function Dispose(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url:"<?php echo site_url('Login/ajax_delete')?>" ,
type: 'post',
data: {id : id},
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
}
}
Another way:
Adding a check before deleting the id in the table.
Javascript:
function Dispose(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url:"<?php echo site_url('Login/ajax_delete/'+id)?>" ,
success: function () {
alert('ajax success');
},
error: function () {
alert('ajax failure');
}
});
}
}
Controller:
public function ajax_delete($id= '')
{
$id = $this->input->post('id');
if($id != ''){
$response = $this->usrExist($id, 'chemicalBottleInfo');
}
if($response == 1){
$this->mod->delete_by_id($id);
}
}
public function usrchk($id,$tableName) {
$qry = "SELECT count(*) as cnt from ".tableName." where id= ?";
$res = $this->db->query($qry,array($id))->result();
if ($res[0]->cnt > 0) {
return 1;
} else {
return 0;
}
}
Related
I'm using CodeIgniter to access the database, but everytime I run the code it gets an internal error. This is my jQuery code:
function showCadeiras() {
$.ajax({
type: "POST",
url: base_url + "api/teacher/getCadeiras",
data: {id: localStorage.user_id},
success: function(data) {
for(var i = 0; i < data.cadeiras_id.length; i++) {
var cadeira_id = data.cadeiras_id[i].cadeira_id;
$.ajax({
type: "POST",
url: base_url + "api/teacher/getCadeiraInfo",
data: {id: cadeira_id},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
}
})
}
},
error: function(data) {
console.log(data);
}
});
}
Here is the code inside the Controller:
public function getCadeiras() {
$user_id = $this->post('id');
$this->load->model('UserModel');
$data["cadeiras_id"] = $this->UserModel->getCadeiras($user_id);
$this->response($data, parent::HTTP_OK);
}
public function getCadeiraInfo(){
$cadeira_id = $this->post('cadeira_id');
$this->load->model('UserModel');
$data["info"] = $this->UserModel->getCadeiraInfo($cadeira_id);
$this->response($data, parent::HTTP_OK)
}
Lastly, the Model code:
public function getCadeiras($id) {
$this->db->select("cadeira_id");
$this->db->where(array('user_id =' => $id));
$query = $this->db->get('professor_cadeira');
return $query->result_array();
}
public function getCadeiraInfo($id) {
$query = $this->db->get_where('cadeira', array('id =' => $id));
return $query->result_array();
}
Everytime I comment the second function (getCadeiraInfo) the code works without a problem, however it doesn't work with the second function. They are written in a similar way, I don't understand the error.
I tried to update the data with ajax on php but it went wrong while ajax information has been successful but the data is not updated, I think the script is correct but do not want to update the data, what is wrong with my script ??
<input type="hidden" id="select_id" name="select_id" value="<?php echo $read_inbox['id_data']; ?>" />
$('[id^=delete_read_inbox]').click(function() {
if (confirm('You are sure to delete this message?')) {
var id = $("#select_id").val();
var url = base_url+'message/delete_inbox_read';
$.ajax({
url : url,
type: 'POST',
data: 'select_id='+id,
success: function(response) {
console.log('success');
},
error: function (request, jqXHR, textStatus, errorThrown) {
console.log(request.responseText);
}
});
} else {
}
});
Controllers
function delete_inbox_read() {
$this->Message->delete_ReadInbox();
redirect('user/message/inbox');
}
Models
function delete_ReadInbox() {
$update = $this->input->post('select_id');
$data = array(
'delete_pa_inbox' => 0
);
$this->db->where('id_Message', $update);
$this->db->update('tb_message', $data);
}
you are trying to POST 'id' from js and fetching 'select_id' on PHP side, hence its not working, change to:
...
var id = $("#select_id").val();
var url = base_url+'message/delete_inbox_read';
$.ajax({
url : url,
type: 'POST',
data: { 'id' : id },
success: function(response) {
console.log('success');
},
....
Controller:
function delete_inbox_read() {
//get the POST data
$select_id = $this->input->post('id'); //id not select_id
$this->Message->delete_ReadInbox($select_id);
//redirect('user/message/inbox'); //remove redirect
echo "done";
}
Model:
function delete_ReadInbox($select_id) {
$data = array(
'delete_pa_inbox' => 0
);
$this->db->where('id_Message', $select_id);
$this->db->update('tb_message', $data);
}
I am working on a project with CI and Ajax. Since, I'm working with ajax after a long time, I am having some issues in debugging. I have written this code. In which i am sending data to to controller function login. Please guide me regarding how to check whether the data is reaching controller, and model. And also on how to return data from model to controller and from controller to view.
My Ajax code is as follows:
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert('Ajax Success');
}, error: function () {
alert('Ajax Error');
}
});
}
});
Controller home.php Code is as follows:
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
return $data;
}
and Model Dis_model.php code is as follows:
function check_user($uname, $pwd) {
$this->db->select('*');
$this->db->where('uname', $uname);
$this->db->where('pwd', $pwd);
$query = $this->db->get('users');
return $query->result();
}
All positive suggestions are welcomed.
Thanks in advance.
Change In Controller:
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
echo $uname;
exit;
}
Change in ajax:
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert(response);
}, error: function () {
alert('Ajax Error');
}
});
}
});
Same in modal
Change in Controller
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
echo json_encode($data['userinfo']);
die;
}
Change in ajax
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert(response);
}, error: function () {
alert('Ajax Error');
}
});
}
});
I am using an AJAX call to insert some data into MYSQL
JS code:
$("input.addtruck").click(function (event) {
event.preventDefault();
var user_id = $("input#user_id").val();
var numar = $("input#numar").val();
var serie = $("input#serie").val();
var marca = $("select#marca").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
});
success: function (res) {
if (res)
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
});
Method used from controller:
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$this->trucks_model->insert_truck($data);
$data['confirmare'] = 'Data Inserted Successfully';
}
And method from models file
function insert_truck($data){
$this->db->insert('trucks', $data);
}
Basicly i need to hide the #truck_form and show #success if the data was inserted, or show #error .
You need to check data is inserted or not in database using affected_rows in model
Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$afftectedRows=$this->db->affected_rows();
if($afftectedRows>0)
{
return TRUE;
}
else{
return FALSE;
}
}
YOu need to echo your result in Controller
Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$res=$this->trucks_model->insert_truck($data);
if($res){
$data['msg'] = 'true';
}else{
$data['msg'] = 'false';
}
echo json_encode($data);
}
Ajax
success: function (res) {
if (res.msg=='true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
You can create an array of response like this. As you ajax dataType is json so you will send response in json.
function add_truck() {
$response = array();
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$check_insert = $this->trucks_model->insert_truck($data);
if(check_insert){
$response['status'] = 'true';
$response['msg'] = 'Data Inserted Successfully';
}else{
$response['status'] = 'false';
$response['msg'] = 'Problem in data insertion';
}
echo json_encode($response);
die;
}
and then in ajax :
success: function (res) {
if (res.status == 'true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
error: function (result) {
console.log('Problem with ajax call insert');
}
And method from models file
Just to ensure row inserted return insert_id
function insert_truck($data){
$this->db->insert('trucks', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
In AJAX
<script type="text/javascript">
$("#addtruck").click(function (event) { // change
event.preventDefault();
var user_id = $("#user_id").val(); // remove input(input#user_id)
var numar = $("#numar").val();
var serie = $("#serie").val();
var marca = $("#marca").val();
$.ajax(
{
type: "post",
dataType: 'json',
url: "<?php echo base_url(); ?>aplicatie/add_truck",
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
}
);
success: function (res) {
if (res == TRUE)
{
jQuery("truck_form").hide(); // remove div on here
jQuery("success").show(); // remove div on here
} else {
jQuery("error").show(); // remove div on here
}
}
});
</script>
In HTML
Button should be
<input type="button" id="addtruck" value="Add New Truck">
and form action="" should be removed
In Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
# passing to model
$res = $this->trucks_model->insert_truck($data);
# Check return value on $res
if($res == TRUE)
{
$data['msg'] = 'true';
}
else
{
$data['msg'] = 'false';
}
echo json_encode($data);
}
In Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$row_affect = $this->db->affected_rows();
if($row_affect > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
You can add error after success to know ajax called successfully or not.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
success: function (res) {
if (res)
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
},
error: function (xhr,err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
Just remove event.preventDefault() from the code and use success like below
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
success : functionName
});
function functionName(){
//your code for success
}
i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}