Jquery, Codeigniter 2.1 - How to check if update is succesfull - php

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.

Related

Return JSON Data from PHP and Ajax

In my web application just I trying to returning JSON data from MySQL database using PHP and AJAX query. This is where I follow a tutorial on internet. In case in my application it shows and error like;
data = "↵↵↵↵Notice: Undefined index: lymph in
C:\xampp\htdocs\Hospital\hospitalwebsite\test_query\fetch_count.php
on line 29
Here is my AJAX Code :-
<script>
$(document).ready(function () {
$('select').material_select();
$('#search').click(function () {
var id = $('#test_list').val();
if (id != '') {
$.ajax({
url: 'test_query/fetch_count.php', // Url to which the request is send
method: 'POST', // Type of request to be send, called as method
data: { id: id },
//dataType:"JSON",
success: function (data) {
$('#success_mes').fadeIn().html(data);
$('#test_info').css('display', 'block');
$('#1').text(data.WBC);
$('#2').text(data.lymph);
$('#3').text(data.Mid);
}
});
} else {
alert('sdsd');
$('#test_info').css('display', 'none');
}
});
});
</script>
Below is the PHP Code :-
<?php
session_start();
require_once "../phpquery/dbconnection.php";
if (isset($_POST['id'])) {
//$id = $_POST['id'];
$stmt = $con->prepare("SELECT * FROM testing_report WHERE testing_report_id = ? AND test_id='7' ");
$stmt->bind_param("s", $_POST['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0);
while ($row = $result->fetch_assoc()) {
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
foreach ($medRecords as $key => $object) {
$data["WBC"] = $object['WBC'];
$data["lymph"] = $object['lymph'];
$data["Mid"] = $object['Mid'];
}
}
}
echo json_encode($data);
}
?>
SQL schema
Really I am appreciating if someone can help me. Thank you
The issue is that your data structure is split over several array elements, something like...
[
{
"WBC": "1"
},
{
"lymph": "5"
}
]
so each loop round the array only has 1 piece of information. This code combines all of that data into 1 set of information using array_merge() and then extracts the data from the result.
I've also added ?? 0 to default the values to 0 if not present, there may be a better default value.
$data = [];
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
$medRecords = array_merge(...$medRecords);
$data["WBC"] = $medRecords['WBC'] ?? 0;
$data["lymph"] = $medRecords['lymph'] ?? 0;
$data["Mid"] = $medRecords['Mid'] ?? 0;
}
JQuery work file if the result be json:
$(document).ready(function(){
$('#search').click( function () {
$.ajax({
url: "https://reqres.in/api/users?page=2",
method: "GET",
success:function(data)
{
console.log("page:", data.page);
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="search">Search</button>
i think you have to add correct header to your result:
<?php
header('Content-Type: application/json');
add this code into first line of your php page. then jQuery know result is json.

Asynchronously query the database by using ajax and jquery and post the result back in codeigniter View

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

Codeigniter Ajax Post not working

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();?>'},
});

Codeigniter loading ajax request

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)

my jquery code is not working code igniter

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") { // ...

Categories