Hello guys im trying to create a simple voting for comments like and dislike but i want to do that with jquery Ajax so i don't want to refresh the page when someone like it.
And this is my jquery code
$(document).ready(function(){
$(".vote-btn").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
// alert(upOrDown); = provides --> id,name
// var all = 'voteId:'+upOrDown[0]+ ',upOrDown:' +upOrDown[1];
// alert(all);
$.ajax({
type: "POST",
url: "http://localhost/Dropbox/cipr/index.php/demo",
cache: false,
dataType:'json',
data:{'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
this is my Controller code Demo.php
<?php
class Demo extends CI_Controller {
function Demo(){
parent::Controller();
$this->load->model('sygjerimet');
}
public function index(){
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='voteup' || true){
$updateRecords = $this->sygjerimet->updateUpVote($voteId);
}else{
$updateRecords = $this->sygjerimet->updateDownVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
}
And this is my model code sygjerimet.php
<?php
Class Sygjerimet extends CI_Model
{
function shtoSygjerimin()
{
$permbajtja = $this->input->post('idea');
$data = array(
'permbajtja' => $permbajtja
);
$this->db->insert('pr_sygjerimet', $data);
}
function updateDownVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_down = vote_down+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
function updateUpVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_up = vote_up+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
}
And this is my view Code
<?php
$query = $this->db->query('SELECT * FROM pr_sygjerimet');
foreach ($query->result() as $row)
{
echo "<div class='sygjerimi'>";
echo htmlspecialchars($row->permbajtja);
if(!$log_in):
echo '<br>';
echo ' <button id="'.$row->ID.'_votedown" class="vote-btn"><i class="fa fa-thumbs-down">'.htmlentities($row->vote_down).'</i></button> ';
echo ' <button id="'.$row->ID.'_voteup" class="vote-btn"><i class="fa fa-thumbs-up">'.htmlentities($row->vote_up).'</i></button> ';
endif;
echo "</div>";
}
?>
That's it guys when i cilck vote it executes this code
alert('Error while request..');
If anyone can help that would be Great :) Thanks
Most likely this is the CI CSRF protection; if you use POST, CI automatically checks the CSRF hidden field and since you are building the ajax post yourself, it's not sending the hidden field so it bags on you.
Check the several $config['csrf_*'] lines in your config/config.php file. You can disable (but I don't recommend this). You can also serialize the form in jQuery and send that, and it should work for you, and keep you a bit more protected from CSRF attacks.
Just to rule this in or out, you can disable the 'csrf_protection' and if it works then, you can enable it again and then change your javascript to serialize the form and use that as your data with your ajax post.
try this
$.ajax({
//pull the toke csrf like this
data:{'<?php echo $this->security->get_csrf_token_name();?>':'<?php echo $this->security->get_csrf_hash();?>'},
});
Related
I am submitting data to a controller function via AJAX, doing what I need to do with the data, and trying to echo it back out to the ajax function.
The issue I am having, is the controller is dumping out the error message and trying to redirect me to the actual function. Obviously the function doesn't have a view, which results in a blank white screen with the response echoed out in the top left corner.
Here is the ajax:
$('#submit_new_split_promo').on('click',function(e){
e.preventDefault();
var id = $(this).data('id');
$('#d_overlay').show();
form = {};
$.each($('#promo-mail-split-add-'+id).serializeArray(),function(k,v){
form[this.name] = this.value;
});
$.ajax({
url:$('#promo-mail-split-add-'+id).attr('action'),
type:"POST",
dataType: "json",
data: form
}).done(function(result){
var res = JSON.parse(result);
if (res == 'Duplicate') {
$('#ms-promo').css('border','3px solid red');
$('#ms-promo').effect('shake');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.');
$('#dynamodal-unique-title').text('That code has been used. Please enter a new Promo Code.').css('color','red').delay(2000).queue(function(next){
$('#dynamodal-unique-title').text('Create Mail Split Promo');
next();
});
return false;
}
$('#mail_split_promo_'+id).modal('toggle');
if (res == false) {
alert('Mail Split Promo did not save. Please try again.');
} else {
$('#add-promo-to-split-'+id).prop('disabled',true);
$('#promo-view-abled-'+id).hide();
$('#promo-view-disabled-'+id).show();
$('#promo-view-disabled-'+id).prop('disabled',false);
}
}).fail(function(){
}).always(function(){
$('#d_overlay').hide();
});
});
Here is the Controllers code
public function addpromo() {
$this->Authorization->skipAuthorization();
$this->request->allowMethod(['get','post']);
$this->autoRender = false;
$data = $this->request->getData();
$mail_split_id = $data['mail_split_id'];
$code = $data['code'];
$result = false;
$doesExist = $this->Promos->findByCode($code)->toArray();
if ($doesExist) {
$result = 'Duplicate';
}
if ($result !== 'Duplicate') {
$MailSplits = $this->getTableLocator()->get('MailSplits');
$mailSplit = $MailSplits->get($mail_split_id);
$entity = $this->Promos->newEmptyEntity();
foreach ($data as $key => $val) {
$entity->$key = $val;
}
$entity->record_count = $mailSplit->record_count;
$result = $this->Promos->save($entity);
if ($this->get_property($result,'id')) {
$promo_id = $result->id;
$MailSplits = $this->loadModel('MailSplits');
$mentity = $MailSplits->get($mail_split_id);
$mentity->promo_id = $promo_id;
$updated = $MailSplits->save($mentity);
if ($this->get_property($updated,'id')) {
$result = true;
} else {
$result = false;
}
$output = [];
exec(EXEC_PATH.'AddPromoToRecordSplits '.$promo_id,$output);
} else {
$result = false;
}
}
ob_flush();
echo json_encode($result);
exit(0);
}
The URL it is trying to redirect me to is: /promos/addpromo when I really just need to stay on the same page, which would be /mail-jobs/view
Response dumped to browser
A couple of things to note:
I have tried adding the function to the controllers policy, and actually authorizing an initialized entity. This has no effect and does not change the issue I am facing.
Something that is more frustrating, I have essentially the same code (ajax structure and controller structure) for other forms on the page, and they work just fine. The only difference seems to be any form that utilizes ajax that is on the page on render, works just fine. The ajax functions I am having an issue with, all seem to be from the forms rendered in Modals, which are different elements. Every form in a modal / element, gives me this issue and that's really the only pattern I have noticed.
Any help is greatly appreciated, I know it's an odd and vague issue.
Thank you!
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
Edit:
It was a problem with localhost and I think with the htaccess file. Although I couldn't make it in localhost, the script is running fine on the web host.
I want to store my form data in to the database using ajax in codeigniter. The problem is that everything is fine, except I'm getting a 500 server internal error.
My contoller:
public function order()
{
$order = $this->main_model->order($_POST);
if($order)
{
return true;
}
else
{
return false;
}
}
my model:
function order($options = array())
{
$options = array(
'client_Name' => $this->input->post('oName'),
'client_Phone' => $this->input->post('oPhone')
);
$this->db->insert('md_orders', $options);
return $this->db->insert_id();
}
and of course I'm using stepsForm script and this is the js code I have:
var theForm = document.getElementById( 'theForm' );
new stepsForm( theForm, {
onSubmit : function( form ) {
var form_data = {
oName: $('#oName').val(),
oPhone: $('#oPhone').val(),
};
$.ajax({
url: "<?php echo base_url() . 'main/order/'; ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
}
} );
and this is the HTML code:
<form id="theForm" class="simform" autocomplete="off">
<ol class="questions" id="questions">
<li>
<span><label for="oName">Your name:</label></span>
<input class="finput" id="oName" name="oName" type="text"/>
</li>
<li>
<span><label for="oPhone">Your Phone Number:</label></span>
<input class="finput ltr" data-validate="number" id="oPhone" name="oPhone" type="text"/>
</li>
</ol>
</form>
and the error I'm getting is :
POST http://localhost/123/main/order/ 500 (Internal Server Error)
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and nothing is stored in the database. What am I doing wrong?!
Try to check your input in controller before send it to model, although it is not mandatory. In your model you need just feed of your array. So you can just set name of parameter.
Your model something like this:
public function order($options) {
$data = array();
$data['client_Name'] = $options['oName'];
$data['client_Phone'] = $options['oPhone'];
$this->db->insert('md_orders', $data);
if($this->db->affected_rows() > 0) {
return $this->db->insert_id();
else {
return false;
}
}
Your controller something like this:
public function order() {
$order = $this->main_model->order($this->input->post());
if( $order !== false ) {
echo "Inserted!";
} else {
echo "Not inserted!";//These are your ajax success function msg parameter
}
}
Also, I can't see the logic of form parameter inside onSubmit property's function( form ). Maybe you could remove it?
In your view,place the following code in your script,please...
one_field = $('#one_field').val();
second_field = $('#second_field').val();
$.ajax({
type:"post",
data:{one_field:one_field, second_field:second_field},
url :'<?=base_url("directory/controller_name/your_method_name")?>',
success: function(data)
{
alert("success");
}
});
Now the place the following in your controller.
function your_method_name()
{
$your_data = array(
"table_field_1" => $this->input->post('one_field'),
"table_field_2" => $this->input->post('second_field')
);
$last_id = $this->your_model->insert_data_function($your_data);
if(isset($last_id)
{
//your code
}
else
{
//your code
}
}
In your Model,place the following.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
return $this->db->insert_id(); //will return last id
}
Instead of using base_url() in your JS, you should try and use site_url()
Your CodeIgniter website runs through the index.php file.
The base_url() function will return the URL to your base directory.
The site_url() will return the URL to your index.php file.
Your form is trying to access "http://localhost/123/main/order" when it should be trying "http://localhost/123/index.php/main/order"
Hope this helps.
Edit
You should also have a look at the form helper.
https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
I am new to codeigniter ajax and i have a problem with sessions.My sessions are not being set and unset
asynchronously and i have to refresh the page just to see the changes.
view/header:
<?php
if(!empty($product)){
$pid=$product[0]['product_id'];
}
?>
<script>
$(document).ready(function(){
if($('.add_to_basket').find('img')){
$('.add_to_basket').click(function(){
var message=$('#badgemessage');
$('#msgcart').append(message);
message.show('slow');
var trigger=$(this);
var param=trigger.attr("rel");
var item=param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url()."cart_c/myfunk/".$pid?>',
data: { id: item[0], job: item[1] },
dataType:'json',
success: function(data) {
console.log(data);
},
error:function(){
alert("error");
}
});
return false;
});
}
});
</script>
model/basket_model:
<?php
class Basket_model extends CI_Model{
function activeButton($sess_id){
$e=$this->session->userdata('basket');
if(isset($e[$sess_id])){
$id=0;
$label="<img src='".base_url()."images/remove.png' />";
}else{
$id=1;
$label="<img src='".base_url()."images/add.png' />";
}
$out="<a href='#' class='add_to_basket' rel='".$sess_id."_".$id."'>".$label."</a>";
return $out;
}
function setItem($pide,$qty=1){
$e=$this->session->userdata('basket');
if(isset($e)){
$e[$pide]['qty']=$qty;
$this->session->set_userdata('basket',$e);
}else{
$arr=array($pide=>array('qty'=>$qty));
$this->session->set_userdata('basket',$arr);
}
}
function removeItem($pide,$qty=null){
$e= $this->session->userdata('basket');
if($qty != null && $qty < $e[$pide]['qty']){
$e[$pide]['qty']=($e[$pide]['qty']-$qty);
$this->session->set_userdata('basket',$e);
}else{
$e[$pide]=null;
unset($e[$pide]);
$this->session->set_userdata('basket',$e);
}
}
}
?>
controller/cart_c:
<?php
class Cart_c extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function myfunk($id){
if(isset($_POST['id']) && isset($_POST['job']))
$out=array();
$pid=$_POST['id'];
$job=$_POST['job'];
if(!empty($id)){
switch($job){
case 0:
$this->basket_model->removeItem($pid);
$out['job']=1;
break;
case 1:
$this->basket_model->setItem($pid);
$out['job']=0;
break;
}
echo json_encode($out);
}
}
}
?>
controller/products:
<?php
class Products extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('catalogue_model');
$this->load->model('products_model');
$this->load->model('basket_model');
}
function product($id){
$kitties['cats']=$this->catalogue_model->get_categories();
$data['product']=$this->products_model->get_product($id);
$data['active_button']=$this->basket_model->activeButton($id);
$this->load->view('header',$data);
$this->load->view('sidebar',$kitties);
$this->load->view('product',$data);
$this->load->view('footer');
}
}
?>
view/product:
<div class="contentwrap">
<div id="content_area">
<?php
$e=$this->session->userdata('basket');
print_r($e);
if(!empty($product)){
foreach($product as $p){
?>
<h1><?=$p['product_name']?></h1>
<div id="product_image">
<img src="<?=base_url()?>/images/<?=$p['image']?>" width="400" height="300" />
</div>
<div id="product_desc">
<?=$p['description']?>
<br><br>
<?=$active_button?>
</div>
<?php
}
}else{
echo "Product unavailable";
}?>
</div>
</div>
The problem is my $active_button in the product view is not changing asynchronously but the sessions are being set and unset
i can see items being pushed into and out of the session array when i refresh the page.When i hit the button my chrome console displays: object{job:0}
ok after looking and studying youre code. you can implement what you want by retrieving the button again when making your AJAX call. The way to retrieve it is by calling that model again, then using jquery to replace the current button. Try the following:
Controller - Cart_c
function myfunk($id) {
if (isset($_POST['id']) && isset($_POST['job'])) {
$out = array();
$pid = $_POST['id'];
$job = $_POST['job'];
if (!empty($id)) {
switch ($job) {
case 0:
$this->basket_model->removeItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
case 1:
$this->basket_model->setItem($pid);
$out['active_button'] = $this->basket_model->activeButton($pid);
break;
}
echo json_encode($out);
}
}
}
JS in header view:
<script>
$(document).ready(function() {
function add_to_basket($this) {
var param = $this.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '<?= base_url() . "cart_c/myfunk/" . $pid ?>',
data: {id: item[0], job: item[1]},
dataType: 'json',
success: function(data) {
console.log(data);
$this.replaceWith(data.active_button);
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
},
error: function() {
alert("error");
}
});
return false;
}
$('.add_to_basket').click(function() {
add_to_basket($(this));
});
});
</script>
Ok I think perhaps we should start by discussing the proper flow of your app. Assuming that your URL looks something like this Products/product/10 and you intially load the page, your function runs providing you with right button and products as expected.. Lets say in this case product 10 does not exist in the session/cart so you see the ADD image button come up.. All good.. Now, when you click add, and from what you are saying, it adds the product to the session/cart, and you get a return JSON of ‘job:0’. So far it works as expected from the code I am seeing. A return of job:0 means that you ran the setItem function. Now the problem you are saying is that the view “is not changing asynchronously”. By this, do you mean that you expect the page to reload and run the function again so that the image can now say “remove”?
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.