Variables to DB and back codeigniter with jQuery - php

Ok, so I have a table that looks like this:
echo "<table id='tbl'>";
foreach ($questions as $q1)
{
if($q1->parinte==0)
{
echo "<tr class=".clickable">";
echo "<td class='parrent".$q1->parinte."' id='".$q1->id."'>".$q1->text."</td>";
echo "</tr>";
}
}
The questions variable is passed from my controller and used here.
What I want is when i click a row in that table, I want to check the id of that row with something from my database and then rewrite the table with other rows from my database.
I think it's simplier in jQuery but I kinda new to jQuery and Codeigniter.
Can someone give me an example on how to send the ID when I click a row and compare to something in my database?
Thanks.
LE:
My model:
class Support_help_model extends CI_Model
{
public function get_questions()
{
//Intrebari principale
$query = $this -> db -> query("SELECT * FROM decision_tree");
return $query->result();
}
}
My controller:
class Support_help_controller extends CI_Controller
{
public function index()
{
$this->load->model("support_help_model");
$data['questions'] = $this->support_help_model->get_questions();
$this->load->view('welcome_message', $data);
}
}

onClick of the row, send the variable to your php script (save.php) using ajax. Just like this-
$(".parrent0").click(function() {
$.post( "save.php", { param: this.id }, function( data ) {
alert(data); // here you'll get the db rows returned
});
});
Receiving the variable and returning the result back; save.php-
$param = $_POST['param'];
//
// db queries
//
$db_data; // data/rows to be returned back
echo json_encode($db_data);

Related

How to display data from MYSQL in codeignitor?

I want to create a dynaic page, I have created model and controller and also data subitted in database successfully. Now, i'm having problem while displaying that data on front end.
Here is my Modal:
function getcorporate(){
$q="SELECT * from corporate";
$query=$this->db->query($q);
return $query->result_array();
}
Here is my Controller:
function corporate()
{
$popular['popular'] = $this->auth_model->getPopularcourses();
$data1['corporate'] = $this->auth_model->getcorporate();
$data["institute_details"] = $this->auth_model->getInstitutedetails();
$data1['course'] = $this->auth_model->getcoursesdetailes();
$this->load->view('nulearnFront/header', $data);
$this->load->view('nulearnFront/corporate', $data1);
$this->load->view('nulearnFront/footer', $popular);
}
Try this
First you can print_r() the data you receive.
print_r($corporate);
After that you can use foreach to display all the data
foreach($corporate as $value)
{
////do code according to your requirement
}
I hope this may be help out to solve your problem
Add View file this code
<?php
if (isset($corporate) && !empty($corporate)) {
foreach ($corporate as $cdata) {
echo $cdata->YourValue(db column name);
}
}
?>
You are so close to the answer. You are passing the data from your Controller class. So what you have to do is just get that data as the follows,
I get the corporate values as it is returning an array data. So here you go,
In your view.php file,
<?php
if (isset($corporate)) { // Check if the data is set or not
foreach ($corporate as $corporateData) {
?>
// Your HTML goes here, table or etc.
<?php echo $corporateData->databaseColumnName // Value that need to print from the database ?>
<?php
}
}
?>
Hope this helps you.
print the query and run it to check
function getcorporate(){
$q="SELECT * from corporate";
$query=$this->db->query($q);
print_r($this->db->last_query());die();
return $query->result_array();
}
if query works fine then you can foreah the query
foreach($corporate as $corporate)
{
echo corporate;
}
if it does not return result then change result_array() to result() in model

how to display data from database using $.post

hey iam trying to take data from data base using $.post. Here iam taking db data as json ecoded. But i couldn't display or alert the data. If possible how can i display the json array? how can i check the database values in json format? pls help me. iam using codeigniter
function profile_view(id3)
{
$.post("<? echo base_url();?>Attendance/Prev_leave_record", {id:id3},function(data){
//do something
});
}
controller
function Prev_leave_record()
{
$teacher_id=$this->input->post('id');
$teacher_details=$this->AM->prev_record($teacher_id);
$out=array(
'teacher_details'=>$teacher_details);
// echo '{"teacher_details":'.json_encode($teacher_details).'}';
echo json_encode($out);
}
model
function prev_record($teacher_id)
{
$this->db->select('leave_from_date,leave_to_date');
$this->db->from('leave_data');
$this->db->where('applied_user_id',$teacher_id);
$teacher_details=$this->db->get();
return $teacher_details;
}
Try this
Model:
Your model made a query but didn't return the result of the query.
See Returning Query Results.
function prev_record($teacher_id)
{
//This is opinion, but it will be much more efficient
//not using Query Builder for such a simple query
$sql = "SELECT leave_from_date, leave_to_date FROM leave_data WHERE applied_user_id = ?";
$query = $this->db->query($sql, [$teacher_id]);
//always check that the query produced results
//the next statement returns one row as an array or
//returns NULL if the query produced no results
return $query->num_rows() > 0 ? $query->row_array(): NULL;
}
Controller:
function Prev_leave_record()
{
$teacher_id = $this->input->post('id');
$teacher_details = $this->AM->prev_record($teacher_id);
if(isset($teacher_details))
{
$out['results'] = "Success";
$out['teacher_details'] = $teacher_details;
}
else
{
$out['results'] = "Failed";
}
echo json_encode($out);
}
javascript:
function profile_view(id3)
{
$.post("<? echo base_url();?>attendance/prev_leave_record", {id:id3},
function(data)
{
console.log(data); //so you can see the structure returned
if(data.results === "Success){
alert("Cool, it worked: " + data.teacher_details);
} else {
alert("Opps, we didn't get anything.");
}
}
);
}
Try this,
function profile_view(id3)
{
$.post("<? echo base_url();?>Attendance/Prev_leave_record", {id:id3},function(data){
console.log(data); // or alert(data);
});
}
Then check the console from Inspect element from browser (F12 or ctrl+shift+i)

Passing Json array value from codeigniter to Jquery calendar Error

I am trying to integrate Jquery calendar plugin with the codeigniter database and passing Json array what would be the mistake appreciate your help.
calendar.php in view
<script>
var unavailableDates = '<?php echo base_url() ?>Calr/getevent';
$('#calendar').availabilityCalendar(unavailableDates);
</script>
Controller Calr.php
public function getevent()
{
$this->load->model(user/Calr_model/SelectAll);
}
Model Calr_model.php
function SelectAll()
{
$sql = 'SELECT start_date,end_date,link FROM tbl_events';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
have tried this function also in calr_model.php
function SelectAll()
{
$sql = 'SELECT start_date,end_date,link FROM tbl_events';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
$emparray = array();
while($row =mysqli_fetch_assoc($query))
{
$emparray[] = $row;
}
echo json_encode($emparray);
}
but json array values is not retrived from database,
static input for which is working in view like
calendar.php
<script>
var unavailableDates = [{start: '2015-08-31', end: '2015-09-05', title:'Event 1'} {start: '2015-09-11', end: '2015-09-15', title:'Event 2'},{start: '2015-09-15', end: '2015-09-23', title:'Event 3'},{start: '2015-10-01', end: '2015-10-07', title:'Event 4'}];
$('#calendar').availabilityCalendar(unavailableDates);
</script>
Regards,
Vinoth
You should have a better distinction between the model and the controller. A model should never echo anything. This is the job of the controller.
Your controller:
public function getevent()
{
$this->load->model('Calr_model');
$data = $this->Calr_model->SelectAll();
echo json_encode($data);
}
Your model (be sure to rename the fields to the proper javascript names, saves you the trouble later):
function SelectAll()
{
$sql = 'SELECT `start_date` AS `start`, `end_date` AS `end`, `link AS `title` FROM tbl_events';
$query = $this->db->query($sql);
return $query->result();
}
You could load this model-method on page load of the normal page. So you don't need another controller for this. If you use AJAX to retreive the data with a normal Ajax call and on success add the events to the calendar with
$.ajax({url: "/Calr/getevent/", success: function(result){
$('#calendar').availabilityCalendar(result);
}});
Mind you, usually the calendar has an event when the calendar is done loading. Use that event to retreive the data via the Ajax function above, otherwise it may not work properly.

php class method not showing all rows if reference more than one method

I am trying to move over to OOP and have a User class with the following:
<?php
class User {
public function __construct($sdb)
{
$this->sdb = $sdb;
}
// and some other methods
}
?>
I call the class using:
$Users = new User($sdb);
I can then use
echo $Users->GetAdminName($AdminId);
And it shows me the results just fine.
But then further down the page, I call another method named ShowUsers that returns all users from the table.
$results = $Users->ShowUsers();
foreach($results as $result)
{
echo my results ....
}
The issue I am having is that the ShowUsers() method is only showing 1 record instead of all the records.
BUT, if I comment out the top method call
//echo $Users->GetAdminName($AdminId);
It shows all the records and not just one.
I am not sure what I am doing wrong here. Any help is greatly appreciated.
function GetAdminName($AdminId)
{
$this->sdb->limit_val="0,1";
$results = $this->sdb->dbSelect("administrators",array("AdminId","FirstName","LastName"),array("AdminId"=>$AdminId));
foreach($results as $result)
{
$AdminName = $result["FirstName"]." ".$result["LastName"];
}
return $AdminName;
}
function ShowUsers($Status = '')
{
$this->sdb->order_by_column="LastName";
$tables=array("administrators", "roles");
$joins=array("administrators.RoleId=roles.RoleId");
$join_condition=array("INNER JOIN");
$columns=array("AdminId", "AdminEmail", "FirstName", "LastName", "Status", "RoleName");
if($Status)
{
$whereCondition=array("Status"=>"$Status");
}
return $this->sdb->dbSelectJoin($tables,$joins,$join_condition,$columns,$whereCondition);
}

getting values of second select from db based of first select box selection in codeigniter

I Need help on how can i get values of second select box based on first select box
This is view:
$(document).ready(function() {
$('#state').change(function() {
// Get an instance of the select, and it's value.
var state = $(this),
stateID = state.val();
// Add if statement to check if the new state id
// is different to the last to prevent loading the same
// data again.
// Do the Ajax request.
$.ajax({
url : 'http://localhost/ci_ajax/select/get_cities/'+stateID, // Where to.
dataType : 'json', // Return type.
success : function(data) { // Success :)
// Ensure we have data first.
if(data && data.Cities) {
// Remove all existing options first.
state.find('option').remove();
// Loop through each city in the returned array.
for(var i = 0; i <= data.Cities.length; i++) {
// Add the city option.
state.append($('option').attr({
value : data.Cities[i].value
}).text(data.Cities[i].city));
}
}
},
error : function() {
// Do something when an error happens?
}
});
});
});
<form action="" method="post">
<select name="state" id="state">
<option>Select</option>
<?php foreach($states as $row):?>
<option value="<?php echo $row->id?>"><?php echo $row->states;?></option>
<?php endforeach;?>
</select>
<select id="cities" name="cities">
<option>Select</option>
</select>
This is controller:
class Select extends CI_Controller{
function index(){
$data['states']=$this->load_state();
$this->load->view('form',$data);
}
function load_state(){
$this->load->model('data_model');
$data['states']=$this->data_model->getall_states();
return $data['states'];
}
function get_cities() {
// Load your model.
$this->load->model('data_model');
// Get the data.
$cities = $this->data_model->get_cities();
// Specify that we're returning JSON.
header('content-type: application/json');
// Return a JSON string with the cities in.
return json_encode(array('Cities' => $cities));
}
}
This is model:
class Data_model extends CI_Model{
function getall_states(){
$query=$this->db->get('states');
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
function get_cities(){
$this->db->select('id,cities');
$this->db->from('cities');
$this->db->where('s_id',$this->uri->segment(3));
$query=$this->db->get();
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
}
Please help on this hopefully provide the correct code.
Because you are accessing the get_cities() function directly, rather than from another function in the controller, your return statement will not actually print the json array to the page.
return json_encode(array('Cities' => $cities));
There are 3 ways to print it: the first is to print or echo the json array (bad practice), the second is to use a view that prints the raw text sent to it. I.E.
$this->load->view('raw', array('data' => json_encode(array('Cities' => $cities)));
With raw.php being just:
<?php print $data; ?>
Or finally you can use the set_output() function in the output class like this:
$this->output->set_output(array('data' => json_encode(array('Cities' => $cities)));
You may also want to make your function load_state() private if it is only going to be accessed from the index() function.
You may have other problems with your code but that is the most obvious one.

Categories