Codeigniter pass variable to php file using json - php

I want to get data from database but I cannot pass variable from view to controller using json. Could you please help me to find the mistake.
Here is my view:
<?php
echo $message;
foreach($results as $row)
{
$faq_id = $row->faq_id;
$faq_title = $row->faq_title;
?>
<h3><?php echo $faq_title; ?></h3>
<?php
}
?>
Here is my JS file:
$(".faq_title").click(function(){
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title},
dataType: 'json',
type: "post",
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Here is my Controller:
public function get_faq_data() {
header('Content-Type: application/json',true);
$this->load->model("model_faq");
$title = $this->input->post('title');
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title){
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0){
return $query->result();
}
else {
return false;
}
}

var title = $(this).text();
$.post( // you can simply send json from post method of jquery
"<?php echo site_url('faq/get_faq_data') ?>", // try to use full url
{
title : title
},
function( data ) {
console.log( data );
},
"json"
);

Related

Redirect Page With Data

I did some research on this topic but i cant run this id is not send to page.
listdata.php
<td class="text-center" style="min-width:130px;">
<button style="width:100%" class="btn btn-primary detail-customer" data-id="<?php echo $m->id; ?>">Bilgi</button>
</td>
ajax.php
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: "id=" + id
})
.done(function(data) {
window.location = "customers/info";
})
})
controller:
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
print $id;
//$this->template->views('customers/info', $data);
}
Are you naming your ajax file as Ajax.php? is that a PHP file? It definitely should be a js file.
From what I know from Jquery and Ajax, url key takes the location of the PHP file, and the data key should be passed as an object. Take these two files as an example:
Ajax.js
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/absolute_path/to/php_file.php",
data: {my_id:id, my_custom_key: "my_custom_value"},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function(response){
console.log(response);
}
})
.done(function(data) {
window.location = "customers/info";
})
})
Php_file.php
<?php
$id = $POST["my_id"];
$customValue = $POST["my_custom_value"];
$response = ["message"=> "We took your id which is $id and your custom value which is $customValue"];
echo json_encode($response);
?>
This is a very basic example of how to use ajax.
Please try it
$(document).on("click", ".detail-customer", function() {
var id = $(this).data("id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: {"id":id},
Content-Type:"json"
});
.done(function(data) {
window.location = "customers/info";
})
});
"we do not read your complete controller code
if your code is correct total then please
first convert data in json then
return it.
"
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
echo json_encode($id);
//$this->template->views('customers/info', $data);
}

Can not update data with ajax on codeigniter

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

Get a single row from the database using AJAX in CodeIgniter?

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.

Simple ajax function in cakephp 2.x not working

I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}

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

Categories