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

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

Related

looking for a help(in wordpress) on how to parse JSON encoded object at server side (PHP code)?

Though I have searched a lot, I was not able to get a concrete answer
client side code
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
dataType : "json",
url: myAjax.ajaxurl,
data: { action : "my_action",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " );
//console.log("success " + JSON.parse(response));
jQuery("#d_amount").val(donor_data[0]);
jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
server side code
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode($_REQUEST['donors']);
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
Info needed
I'm not able to see my data base being updated, when I click the button,How to parse the Json data (array) at server side ?
Is there any way to know what I have received at server side, If I use "echo" to print a variable it is sent to ajax client ?
If answer to #2 is "NO" , how to parse the JSON data at client side ?
try this
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
//dataType : "json",
url: myAjax.ajaxurl,
data: { action : "ajx_add_donations",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " ,response);
//console.log("success " + JSON.parse(response));
//jQuery("#d_amount").val(donor_data[0]);
//jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode(stripslashes($_REQUEST['donors']));
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
add_action( 'wp_ajax_ajx_add_donations','ajx_add_donations' );
add_action( 'wp_ajax_nopriv_ajx_add_donations', 'ajx_add_donations');

Passing a value from Controller to jQuery CodeIgniter

Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.
Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}

Call to a member function row() on a non-object when updating a table

I am using codeigniter to develop my app. And I am using jquery to send some json data.
This is my code :
Model :
public function updateRequest($id_request, $jenis_request, $keluhan ){
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
return $query->row();
controller :
public function updateRequest(){
$id = $_POST['id'];
$jenis_request = $_POST['jenis_request'];
$keluhan = $_POST['keluhan'];
$row = $this->model_request->updateRequest($id, $jenis_request, $keluhan );
echo json_encode($row);
}
This is the view using ajax
$('#btn-footer').click(function(e) {
e.preventDefault();
var id = $("#mainTitle strong").text().split("/").pop();
/*get value checkbox*/
var jenis_request = [];//console.log($("input[name='request[]']"));
$("input[name='request[]']:checked").each(function() {
//console.log($(this).val());
jenis_request .push($(this).val());
});
jenis_request = jenis_request.join(',');
alert(jenis_request); //for check
/*ambil keluhan*/
var keluhan = $('#modalkeluhan').val();
$.ajax({
url: '<?php echo base_url() . 'control_closing/updateRequest/' ?>',
type : 'POST',
data : {id : id ,
jenis_request : jenis_request,
keluhan : keluhan
},
dataType: 'json',
success: function (obj) {
console.log(obj);
}
});
});
I got this error, Call to a member function row() on a non-object ,
I know that row() is an object, is that a problem ?
This may help you
public function updateRequest($id_request, $jenis_request, $keluhan )
{
$data= array(
'jenis_request' => $jenis_request,
'keluhan' => $keluhan
);
$this->db->where('id_request', $id_request);
$query = $this->db->update('tbl_requestfix', $data);
$affected_rows=$this->db->affected_rows();
if($affected_rows >0)
{
return $affected_rows." rows updated";//return here the way you want
}
else
{
return "No updates";
}
}

Posting to controller with jquery ajax in CakePHP

I want to post data to a controller in CakePHP, but posting with JQuery always results in an error and I can't figure out why.
In my view I have the following method, that posts the data to the controller page
function RenameNode(name, id)
{
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'categories', 'action' => 'rename')); ?>',
data: {
id: id,
name: name
},
success: function(){
}
});
}
My controller method looks like this:
public function rename($id = null, $name = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if(!$id)
{
$id = #$this->request->query('id');
}
if(!$name)
{
$name = #$this->request->query('name');
}
if (!$id) {
throw new NotFoundException(__('No id'));
}
$category = $this->Category->findById($id);
if (!$category) {
throw new NotFoundException(__('Invalid category'));
}
$this->autoRender = false;
$this->layout = 'ajax';
if ($this->request->is('post') || $this->request->is('put')) {
$this->Category->id = $id;
$this->request->data['Category']['name'] = $name;
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('The category has been updated.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to update the category.'));
}
}
}
When I do a post with the jquery method, I keep getting the following error message in my log:
2013-05-20 11:34:25 Error: [NotFoundException] No id
Request URL: /cakephp/categories/rename
Stack Trace:
#0 [internal function]: CategoriesController->rename()
When I comment the request checks for get and post, the controller itself works perfectly when I call it with /categories/rename?id=1&name=test. For some reason the ajax way doesn't work, but I can't figure out why. Any ideas?
Update
I fixed it by changing the following code, now it works perfectly
if(!$id)
{
$id = #$this->request->query('id');
}
if(!$name)
{
$name = #$this->request->query('name');
}
to
if(!$id)
{
$id = #$this->request->data('id');
}
if(!$name)
{
$name = #$this->request->data('name');
}
You are not including the id and/or name in the URL you're posting to;
echo Router::url(array('controller' => 'categories', 'action' => 'rename'));
Will output;
/categories/rename
But you're expecting
/categories/rename/1/test
Or
/categories/rename?id=1&name=test
Change the URL in your AJAX code to something like;
echo Router::url(array(
'controller' => 'categories',
'action' => 'rename',
0 => $this->request->params['pass'][0],
1 => $this->request->params['pass'][1]
));
Which should output the right url, containing the original id and name of the current request (e.g. /categories/rename/123/oldname)
use somthing like that
data = 'name='+name+'&id='id'';
$.ajax({
type:'post',
url: '/categories/rename',
data: data
});
and in controller function
$name=$_POST[name];
$id=$_POST[id];
$('a.ajax-delete-pdf').on('click', function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax(
{
url: webroot + 'productos/ajax_eliminar_pdf/' + id ,
async : false,
success: function(respuesta)
{
if(respuesta == 'Borrado')
{
$(this).parent().toggle();
}
}
});
});

jQuery JSON not passing data to Ci properly

The script below works as far as i can tell:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#add').bind('keypress', function(e) {
if(e.keyCode == 13){
var add = $("#add").val();
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url("home/jsonAddData"); ?>",
data: add,
json: {title_posted: true},
success: function(data){
if(data.title_posted == true) { // true means data was successfully posted.
$("#success").append("Success").fadeIn(400);
} else if(data.title_posted == false) { // false means data failed to post.
$("#success").append('Failure').fadeIn(400);
}
}
});
}
});
});
</script>
The problem I'm experiencing with the code below is that the mysql insetion query just wont work. It creates the row in the table and auto-increments but for some odd reason it wont pass the 'var add' in the Javascript above to the Ci script below and perform an insertion in the db. Any thoughts or ideas?
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home', $data);
}
function displayList() {
$str = '';
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$b = '<input name="completed" type="checkbox" />';
$a = $row->title . "<br>";
$str .= $b.$a;
}
return $str;
}
function jsonAddData() {
if($this->input->is_ajax_request()) {
$title = $this->input->post('title');
$query = $this->db->query("INSERT INTO data (title) VALUES ('$title')");
header('Content-type:application/json');
if($query) echo json_encode(array('title_posted' => true));
else echo json_encode(array('title_posted' => false));
}
}
}
?>
In
$.ajax({
...
data: {title: add}
Not just a string

Categories