Displaying data from AJAX call to database with jquery and CI - php

The model seems to be working as well as the controller. The AJAX displays the results as "null" so I think it is because we need to send the data as json. Any ideas on how to get the data into the correct format and to display in the view
View
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table' style="color:white;">
hola amigo
</div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url().'index.php/trial/getValues';?>',
type:'POST',
dataType: 'json',
error: function(){
$('#result_table').append('<p>goodbye world</p>');
},
success: function(results){
$('#result_table').append('<p>hello world</p>');
} // End of success function of ajax form
}); // End of ajax call
});
</script>
Controller
function getValues(){
$this->load->model('get_db');
$data['results'] = $this->get_db->getAll();
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}

in your view, you set your data type to json so you need a controller that it's generate a json output. codeIgniter has a system to generate this type. you can use this code in your controller to do that:
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $data ));
and in ajax success get your response and use it:
success: function(response){
server_res = JSON.parse(response);
console.log(server_res);
$('#result_table').append('<p>hello world</p>');
}

just print/echo the $data in controller if you want html form(dont return). If you want json then print/echo json_encode($array)
and in success ajax write
success: function(results){
$('#result_table').append(results.arraykey);//arraykey=array key from controller
} // End

In the controller just use this
function getValues(){
$this->load->model('get_db');
echo json_encode($this->get_db->getAll());
}
And in the view
success: function(results){
results = JSON.parse(results);
$('#result_table').append('<p>hello world</p>');
}

Related

How to fix ajax when fetching the data without load or refresh? CodeIgniter PHP

My problem is I can already fetch the data but I still need to refresh the page when a data is inserted from the backend. in the front end is there where I uses ajax.
So I need a solution where when the data is inserted then the page should stay as it is and the data must be fetched without load or refresh
So here is my view
I have a div, so everytime a data is inserted the number must be incremented without refresh
<div id="count"></div>
My script
<script>
$(function(){
showAllPosts();
//function
function showAllPosts(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>students/showAllPosts',
async: false,
dataType: 'json',
success: function(data){
var count = '';
count += '<p>'+data.length+'</p>';
$('#showdata').html(count);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
});
</script>
In my Controller
public function showAllPosts(){
$result = $this->student_model->showAllPosts();
echo json_encode($result);
}
And my Model
public function showAllPosts(){
$this->db->select('*');
$this->db->from('classes');
$this->db->join('posts', 'classes.group_id = posts.activity_id');
$this->db->where('classes.student_id', $this->session->userdata('user_id'));
$query = $this->db->get();
return $result = $query->result_array();
}

Passing ajax data to blade to use in php query

I have a modal which opens on click:
jQuery('.calendar-day-update-edit-trigger').click(function(event){
var targetDate = jQuery(this).attr('data-day');
jQuery('.updater-date-edit').html(targetDate);
jQuery('.hidden-date-input-edit').val(targetDate);
$.ajax({
method: "get",
url: "/admin/days/getdata/"+targetDate,
data: { 'EID': targetDate,},
})
});
I want to send the data to a blade file so I can query my database.
public function getData($getData){
$data = Day::where('sale_at', $getData)->first();
return $data;
}
Hello,
If you want to return data from your controller to your template, you must return your data in json.
After this, you can use the success method in your ajax call to get the data from your controller and affect these data to an or more HTML elements in your blade template.
In your JS:
$.ajax({
method: "get",
url: "/admin/days/getdata/"+targetDate,
data: { 'EID': targetDate,},
success: function(data) {
$('#your_html_element').val(data);
}
})
In your PHP:
header('Content-Type: application/json');
echo json_encode($data);
In your blade template:
<div id="your_html_element"></div>

to print a session using ajax codeigniter

In my page
$(document).ready(function(){
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>total',
data:'id=1',
beforeSend:function(){
$('.searc_res').show();
},
success:function(html){
$('.searc_res').remove();
$('.searc_res').append(html);
}
});
});
This is just to return in the div the value of a session
Session is: $this->session->userdata('searchItems_Total')
How to do this in the total.php file?
Do I need to create something in the model?
Just print it?
public function total()
{
header('Content-type: application/json');
/.../
echo json_encode($this->session->userdata('searchItems_Total'));
}
In your client side call (to view the returned data's structure):
$.ajax({
...
success: function(resp){
console.log(resp);
});
You can just return $this->session->userdata('item'); in your php function or you can just echo the values in your html since you are trying send an ajax request in document ready state which is not necessary.

codeigniter update database using ajax then show

I would like this function:
After I select an option I want to update right away the database and then show it right away also inside a certain div. How can I achieve this?
Here's my HTML:
<select id="category1" name="cat1">
<option>Hardware</option>
<option>Software</option>
<option>Network</option>
</select>
AJAX code:
$('#category1').on('change',function(){
var data = $("cat1").val();
var ticket = '<?php echo $ticket_details[0]["cTicketNo"];?>';
if(data){
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo base_url();?>User/TicketView/update_cate",
data: {data: data,ticket: ticket},
success:function(response){
alert('successful');
},
error: function(response){
alert('tangina!');
}
});
}
});
Controller:
function update_cate(){
$this->TicketView_m->update_cat1();
redirect($_SERVER['HTTP_REFERER']);
}
Model:
function update_cat1(){
$ticket_id = $_POST['ticket'];
var_dump($cat = $_POST['data']);
$this->db->set('vCategory',$cat);
$this->db->where('cTicketNo',$ticket_id);
$this->db->update('tconcerns');
}
THanks for all the help!
Drop that redirect($_SERVER['HTTP_REFERER']);, You don't need that.
First of all, AJAX will allow you to send data to server without redirecting to another page.
Based on your AJAX dataType. It is JSON. So for you to get the result, You have to encode it to JSON like json_encode(['result' => 'things you want to show']).
Then you can access it in your response like this:
success:function(response){
alert('successful');
var res = response.result; //Access the JSON
$("#certainDiv").html( res ); //Print to the div you want
}
And it is also better to get the post request in your controller then pass it to your model:
function update_cate(){
$ticket_id = $this->input->post('ticket');
$cat1 = $this->input->post('cat1');
$this->TicketView_m->update_cat1($ticket_id, $cat1);
echo json_encode(['result' => 'things you want to show']);
}

How to pass JS object to PHP function

$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
on callback function success return the data and pass it to add_attribute_form(data) php function but nothing response.
what is the correct way to pass js object to php function
What you will need to do here is, use Ajax to send data to a separate php page passing it some information, then, based on that information, the php page should return data to the Ajax callback function which will add the returned data to the original page.
Here's a simple example (and a working demo here):
In index.html do this:
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
Then in somepage.php do the following:
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>

Categories