Can not update data with ajax on codeigniter - php

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

Related

Trying to remove value from a JSON file

I'm trying to remove value from a json file with AJAX request, it don't show any error but it don't delete the value, someone can check it? Thanks you!
Before the AJAX function (for insert the ID on the "erase"). (the function deletee(item) click the button that activate the dlt function)
JS:
function deletee(item) {
var el = document.getElementById('erase');
el.value = Checker[item].id;
var r= confirm("Do you want delete it?")
if (r==true) {
document.getElementById('rmv').click()
}
}
JS AJAX:
function dlt(item) {
var iddlt = document.getElementById('erase').value;
$.ajax({
type: 'GET',
url: 'api/delete/'+ iddlt,
dataType: 'json'
});
}
php:
$app->get('/delete/{id}', function (array $args) {
$jsonContents = file_get_contents('data/data.json');
$id = $args['id'];
$data_array = json_decode($jsonContents, true);
foreach ($data_array as $key => $value) {
if ($value['id'] == $id) {
unset($data_array[$key]);
}
}
$data_array = array_values($data_array);
file_put_contents('data/data.json', json_encode($data_array));
});
Pass ID to your function and Ajax URL :
function dlt(item_id) {
$.ajax({
type: 'GET',
url: 'api/delete' + item_id,
dataType: 'json'
});
}
Add id in your URL to make your API work.
function dlt() {
var id= "it should be a valid id";
$.ajax({
type: 'GET',
url: 'api/delete/'+ id,
dataType: 'json'
});
}

Ajax request shows complete but data not submitted

I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()

Check if AJAX call is success or not in codeigniter

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
}

sending data via ajax in Cakephp

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

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

Categories