Trying to add some ajax functionality within a voting system and it's not working. I'm wanting to send a post request to the database and update the count value. Problem I'm running into is that I can't seem to get the ajax request tow work within the MVC.
I do want to retain the MVC structure.
The jquery code is:
<script>
$( document ).ready(function() {
$( "#vote li a" ).each(function( index ) {
$(this).click(function(){
$.ajax = ajax();
var id = $(this).attr('data-scenario-id');
var value = $(this).attr('data-value');
$.ajax({
url: "ajax-vote.php",
cache: false,
data: { id: id, value: value }
})
.done(function( html ) {
$(this).html( html );
});
return false;
});
});
});
and the php code currently residing in ajax-vote.php is:
$id = isset($_GET['id']) ? $_GET['id'] : null;
$value = isset($_GET['value']) ? $_GET['value'] : null;
$query = $this->db->query('SELECT count FROM total_counts WHERE scenario_id = ' . $id . ' AND interaction_id = ' . $value);
$row = $query->row();
$count = $row->name;
$count++;
$query = $this->db->query('UPDATE total_counts SET count = ' . $count);
$query = $this->db->query('SELECT count FROM total_counts WHERE scenario_id = ' . $id . ' AND interaction_id = ' . $value);
$row = $query->row();
$count = $row->name;
switch ($value) {
case 1:
$text = 'OK '. $count;
break;
case 2:
$text = 'NOT OK'. $count;
break;
case 3:
$text = 'ABUSE'. $count;
break;
}
echo ''. $text .'';
Thanks in advance.
If you are working with codeigniter than you than you have to give controller path in the url. I am assuming your controller name is ajax-vote.php than your ajax code would be
$( document ).ready(function() {
$( "#vote li a" ).each(function( index ) {
$(this).click(function(){
$.ajax = ajax();
var id = $(this).attr('data-scenario-id');
var value = $(this).attr('data-value');
$.ajax({
url: "<?php echo base_url(); ?>ajax-vote",
cache: false,
data: { id: id, value: value }
})
.done(function( html ) {
$(this).html( html );
});
return false;
});
});
});
You must put your code into a controller, not in a simple php file! Then you can pass to javascript the codeigniters site_url path like this:
<script> var site_url = '<?php echo site_url()?>';</script>
You must do this in your header view.
then later in your ajax call you can use this variable to build the path:
$.ajax({
url: site_url + "ajaxcontroller/vote",
cache: false,
data: { id: id, value: value }
})
.done(function( html ) {
$(this).html( html );
});
now you have php and javascript separated.
Of course you have to do an AjaxController extending CI_Controller, and put your code inside a function called "ajax" (or whatever you want, just make sure to use the same name what you used in the js call)
Related
I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this
I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)
this is my javascript code ...i have written a function in my controller in which if false is return then i am echoing the 'userNo' other wise echo the json .. here is my javascript in which only else part is working not if part ... i have checked in firebug also .. i am getting a response "userNo" but dont know why it is not running the first part
<script type="text/javascript">
$(document).ready(function(){
$('#hide').hide();
$('#bill_no').blur(function(){
if( $('#bill_no').val().length >= 3 )
{
var bill_no = $('#bill_no').val();
getResult(bill_no);
}
return false;
})
function getResult(billno){
var baseurl = $('.hiddenUrl').val();
$('.check').addClass('preloader');
$.ajax({
url : baseurl + 'returnFromCustomer_Controller/checkBillNo/' + billno,
cache : false,
dataType: 'json',
success : function(response){
$('.check').removeClass('preloader');
if (response == "userNo") //this part is not working
alert("true");
else
$('.check').removeClass('userNo').addClass('userOk');
// $(".text").html(response.result);
$('#hide').show();
$(".text1").html(response.result1);
$(".text2").html(response.result2);
$(".text3").html(response.result3);
}
})
}
})
</script>
my Controller
function checkBillNo($billno)
{
$this->load->model('returnModel');
$query = $this->returnModel->checkBillNo($billno);
//$billno = $this->uri->segment(3);
$billno_results = $this->returnModel->sale($billno);
if (!$billno_results){
echo "userNo";
}else{
echo json_encode($billno_results);
}
}
Instead of echo "userNO", try to use it:
echo json_encode(array('return' => 'userNo'));
... and in your JS, use this:
if (response.return == "userNo") { // ...
I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";
How can I see if the update, after JQuery post, is succesfull?
JQuery code:
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(){
});
}
});
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
$this->mgl->mgl_check_paid($code, $id);
}
CI model:
function mgl_check_paid($code, $id){
$q = $this->db->select('*')->from('ad')->where('id_ad', $id)->where('code', $code)->get();
$q_r = $q->row();
if ($q->num_rows() != 0 && $q_r->paid == 0) :
$data['paid'] = 1;
$this->db->where('id_ad', $id);
$this->db->update('ad', $data);
return TRUE;
else :
return FALSE;
endif;
}
I need to check if update is successful and show appropriate message.
CI controller:
function mgl_check_paid()
{
$code = $this->input->post('code');
$id = $this->input->post('id');
// could also return a json or whatever info you want to send back to jquery
echo ($this->mgl->mgl_check_paid($code, $id)) ? 'yes' : 'no';
}
Jquery
var code = $('#code'),
id = $('input[name=id]').val(),
url = '<?php echo base_url() ?>mali_oglasi/mgl_check_paid';
code.on('focusout', function(){
var code_value = $(this).val();
if(code_value.length < 16 ) {
code.after('<p>Code is short</p>');
} else {
$.post(url, {id : id, code : code_value}, function(data){
// display the data return here ... simple alert
//$('.result').html(data); // display result in a div with class='result'
alert(data)
});
}
});
You may also want to read more # http://api.jquery.com/jQuery.ajax/ (if you want to do better error checking like failure)
First of all, mad props, I <3 CI and jQuery. Secondly, you need to echo in order to return data to your jQuery post.
Gimmie 5 to fix something at work and i'll edit this answer with more detail.