Display rows from database in html table using jQuery, Ajax, json - php

I need some help with the following code. I am trying to query my database using ajax and return the results within a table. The code is executing and I am not getting any errors - I'm just not getting a response. Any ideas? I have a feeling something is messed up with my jQuery function.
Thanks for any help you can give.
My function in my view:
$("#test").click(function() {
var form_data = {
Opportunity_Id: $('#Opportunity_Id').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('schedule/get_classes'); ?>",
type: 'POST',
data: form_data,
cache: false,
success: function(server_response) {
var data = $.parseJSON(server_response);
for(var i = 0; i < data.length; i++){
week = data[i];
$("table.table").append("<tr><td>" + week.Class_Number + "</td><td>" + week.Class_Date + "</td></tr>");
};
},
error: function(thrownError) {
alert(thrownError);
}
});
return false;
})
My controller:
function get_classes() {
$Opportunity_Id = $this->input->post('Opportunity_Id');
$this->ion_auth_model->get_classes($Opportunity_Id);
foreach ($classes as $class):
$results[] = array(
"Class_Number" => $class->Class_Number,
"Class_Date" => $class->Class_Date,
"Start_Time" => $class->Start_Time,
"End_Time" => $class->End_Time
);
endforeach;
echo json_encode($results);
}
My model:
function get_classes($Opportunity_Id) {
$this->db->select('*')->from('Classes')->where('Opportunity_Id', $Opportunity_Id);
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $classes) {
$data[] = $classes;
}
return $data;
}
}

I think this maybe your problem, you are returning an array from get_classes($Opportunity_Id) but you have not captured that array when you call it :-
function get_classes() {
$Opportunity_Id = $this->input->post('Opportunity_Id');
$classes = $this->ion_auth_model->get_classes($Opportunity_Id); <--- changed here
foreach ($classes as $class):
$results[] = array(
"Class_Number" => $class->Class_Number,
"Class_Date" => $class->Class_Date,
"Start_Time" => $class->Start_Time,
"End_Time" => $class->End_Time
);
endforeach;
echo json_encode($results);
}

Related

Unable to pass array data from view to controller using AJAX

The data (array of array) is not getting passed from view to controller while using AJAX in CodeIgniter (PHP)
url is working in $.ajax. It is redirecting to the method in controller
view.php (view)
$('#save').click(function(){
var table_data = [];
// use .each to get all data
$('#data_table tr').each(function(row,tr){
// create array again to store data by row
// get only data with value
if ($(tr).find('td:eq(0)').text() == "") {
} else {
var sub = {
'no' : $(tr).find('td:eq(0)').text(),
'firstname' : $(tr).find('td:eq(1)').text(),
'middle' : $(tr).find('td:eq(2)').text(),
'last' : $(tr).find('td:eq(3)').text(),
};
table_data.push(sub);
}
});
//use ajax to insert the data
console.log(table_data);
var data = {'data_table':table_data};
console.log(data);
$.ajax({
data : data,
type : 'POST',
url : 'save',
crossOrigin : false,
dataType : 'array',
success: function(msg){
$('.answer').html(msg);
}
});
Welcome.php (controller)
public function save() {
$relatives_list = $this->input->post('data');
echo 'as';
echo $relatives_list;
// the list is not shown here
$this->load->model('Batch');
$status = $this->Batch->save($relatives_list);
$this->output->set_content_type('application/json');
echo json_encode(array('status' => $status));
}
Batch.php (model)
public function save($relative_list){
$length = count($relative_list);
for($x = 0; $x < count($relative_list); $x++){
$data[] = array(
'no' => $relative_list[$x]['no'],
'firstname' => $relative_list[$x]['firstname'],
'middle' => $relative_list[$x]['middle'],
'last' => $relative_list[$x]['last'],
);
}
try {
for($x = 0; $x<count($relative_list); $x++){
$this->db->insert('hhh',$data[$x]);
}
return 'success';
}catch(Exception $e) {
return 'failed';
}
}
Error:
parameter-must-be-an-array-or-an-object-that-implements-countable
According to your script it wouldn't be data it would be data_table
var data = {'data_table':table_data};
Thus:
var_dump($this->input->post('data_table')
If that doesn't work please post the console.log of your data var.
Please note: you will have to remove the echos before json_encode after you are done troubleshooting or jquery will fail to parse the response.

Display name one by one using JSON and AJAX

How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);

Undefined Variable in Ajax from PHP

I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}

Codeigniter : How to insert last uri segment into database using ajax

I am creating a rating system in which when user rate any company then rate stored into rate along with the v_id table. (v_id is company id),
This is my url in which i want to rate...
www.ABC.com/controller/function/company_id
Here company_id is getting from database. I want to store the company rating into rate table. when user click on the star.
Controller
function visa_company_profile($v_id) {
$data['total_ratings'] = $this->Visa_mdl->total_ratings($v_id);
$data['total_average'] = $this->Visa_mdl->total_average($v_id);
$result = $this->Visa_mdl->get_company_profile($v_id);
$data['items_company_profile'] = $result;
$this->load->view('include/header');
$this->load->view('hotels/company_profile',$data);
$this->load->view('include/footer');
}
Views
This is ajax part in which i am sending the star values to the controller
$(document).ready(function(){
var click_val = 0;
$("#1_star").hover(function(){
$("#1_star").attr("src","<?php echo base_url('assets/rating/star.png'); ?>");
$("#2_star").attr("src","<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#3_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#4_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#5_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
});
$("#1_star").click(function(){
click_val = 1;
$.ajax({
url: '<?php echo base_url('Account/loggedin');?>',
success: function(logged_in) {
if (logged_in === "1") {
ajaxCall();
}else {
$("#l_modal").modal('show');
}
}
});
});
function ajaxCall() {
$.ajax({
method : 'POST',
data: {'click_val':click_val},
url: '<?php echo base_url('Hotels/ratings/');?>',
success: function() {
location.reload();
}
});
}
Star Controller To store Rate into data
Here i am trying to get the company id from url and store into column(v_id) rate table.
function ratings() {
date_default_timezone_set('Asia/Kolkata');
$last = $this->uri->total_segments();
$record_num = $this->uri->segment($last);
$value = array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $record_num
);
$this->Visa_mdl->ratings($value);
}
Model
function ratings($value) {
$this->db->insert('user_ratings',$value);
}
You can do it simply modifying you ajax function input value
function ajaxCall() {
$.ajax({
method : 'POST',
data: {'click_val':click_val,'company_id':<?php echo $this->uri->segment(3)},
url: '<?php echo base_url('Hotels/ratings/');?>',
success: function() {
location.reload();
}
});
}
Again you can catch the company ID in your controller Function Hotels/ratings.
function visa_company_profile($v_id) {
$data['v_id'] = $v_id;
$data['total_ratings'] = $this->Visa_mdl->total_ratings($v_id);
$data['total_average'] = $this->Visa_mdl->total_average($v_id);
$result = $this->Visa_mdl->get_company_profile($v_id);
$data['items_company_profile'] = $result;
$this->load->view('include/header');
$this->load->view('hotels/company_profile',$data);
$this->load->view('include/footer');
}
If you pass click value in url then ajax script should be like this:
function ajaxCall() {
var company_id = '<?php echo $v_id; ?>';
$.ajax({
method : 'POST',
data: {'click_val':click_val, 'company_id':company_id},
url: '<?php echo base_url('Hotels/ratings/');?>'+click_val+'/'+company_id,
success: function() {
location.reload();
}
});
}
Because you are not passing click value in url so controller should be like that:
function ratings() {
date_default_timezone_set('Asia/Kolkata');
$record_num = $this->input->post('company_id', true);
$value = array (
'rate' => $this->input->post('click_val', true),
'date' => date('Y-m-d H:i:s'),
'v_id' => $record_num
);
$this->Visa_mdl->ratings($value);
}
And controller:
function ratings($record_num = 0, $company_id = 0) {
date_default_timezone_set('Asia/Kolkata');
$value = array (
'rate' => $record_num,
'date' => date('Y-m-d H:i:s'),
'v_id' => $company_id
);
$this->Visa_mdl->ratings($value);
}

How to test returned json result?

I have an Ajax Request that is getting data from my database, specifically two columns from it, company_id and people_id,
I need to test the result that comes from the json result, I need to check if a specific people_id exists in the result,
Here is my Ajax Request
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'CompanyPeople',
method: 'secget',
data: Ext.encode({
people_id: Ext.getCmp('peopleGrid').selectedRecord.data.people_id
})
},
success: function (response) {
},
failure: function () {
}
});
I thought I could do this following code in the success function but it didnt work
if (data == 0) {
Ext.MessageBox.alert('Status', 'Person is not attached to anything bud!.');
}
else {
Ext.MessageBox.alert('Status', 'Person already attached to another company.');
}
Also here is my php
class CompanyPeople extends Connect {
function __construct() {
parent::__construct();
}
public function secget($vars) {
$sql = "SELECT * FROM CompanyPeople where people_id={$vars->data->people_id}";
$data = array();
$total = 0;
if ($result = $vars->db->query($sql)) {
while ($row = $result->fetch_assoc()) {
$data[] = array("people_id" => intval($row["people_id"]));
$total++;
}
$result->free();
}
echo json_encode(array("success" => true, "total" => $total, "topics" => $data));
}
}
I think something like this should work:
success: function( response ){
if(response.success === true) {
var personExist = false;
for(var i = 0; i < response.topics.lenght; ++i) {
// Your specific people_id in myValue
if(response.topics[i]['people_id'] === myValue) {
personExist = true;
break;
}
}
}
},

Categories