Codeigniter and AJAX error - php

I am making an application for a bar.
The application populates #beer_output with "beer form buttons" by executing get_beers_from_customer(); when the document is ready.
Then the bartender serves drinks by clicking on a "beer form button".
Each time the bartender clicks on the "beer form button" an ajax call is made and send to the codeigniter controller where the beer is deleted and echos a response to ajax with the beers left to be served until there are no orders left to be serve.
Once there are no beers left the order gets processed through another function of my controller : process_order_when_all_drinks_served($user_id).
I am using authorize.net as the payment gateway.
The problem is when I order only 1 beer to be serve, but if I have an order of 2 beers everything works fine. process_order_when_all_drinks_served($user_id) outputs the error Trying to get property of non-object.
Here is specifically where the error is happening if($response->response_code=="1") apparently it is not giving a response back. The ajax is posting and it is not giving back any errors. I do not know what is happening. I can give you the link and order 1 drink if that helps.
Here are the ajax functions
$(document).ready(function(){
get_beers_from_customer();
function get_beers_from_customer()
{
//form variables
var user_id = "<?php echo $this->session->userdata('user_id'); ?>" ;
var formData = {user_id:user_id};
ajax_update_content_when_page_is_loaded_beers(formData);
}
function ajax_update_content_when_page_is_loaded_beers(formData)
{
$.ajax({
url : '<?php echo base_url()."index.php/bartender/bartender_serve_beers"; ?>',
async : false,
type : "POST",
cache : false,
data : formData,
dataType: "html",
success : function(data)
{
alert($.trim(data));
$('#beer_output').html($.trim(data));
$('#beer_output').trigger('create'); },
error: function (jqXHR, textStatus, errorThrown)
{
$('#server_message_error_jqXHR').html("here is the jqXHR"+jqXHR);
$('#server_message_error_textStatus').html("here is the textStatus "+textStatus);
$('#server_message_error_errorThrown').html("here is the errorThrown"+errorThrown);
}
});
}
});
once the form is submitted
$(".beer").on("submit",function(event)
{
//variables
var delete_beer = $(this).find(".delete_beer").val();
var beer_id = $(this).find(".beer_id").val();
var user_id ="<?php echo $this->session->userdata('user_id');?>";
// alert( "delete_beer="+delete_beer+"beer_name=" +beer_name +"beer_id="+beer_id );
//form variables
var formData = {delete_beer:delete_beer,beer_id:beer_id,user_id:user_id}; //Array
submit_ajax_form_beers(formData);
//get_beers_from_customer();
});
function submit_ajax_form_beers(formData)
{
$.ajax({
url : '<?php echo base_url()."index.php?/bartender/bartender_serve_beers"; ?>',
async : false,
type : "POST",
cache : false,
data : formData,
dataType: "html",
success : function(data){
$('#beer_output').trigger('create');
console.log($(this).data(formData));
},
error: function (jqXHR, textStatus, errorThrown){
$('#server_message_error_jqXHR').html("here is the jqXHR"+jqXHR);
$('#server_message_error_textStatus').html("here is the textStatus "+textStatus);
$('#server_message_error_errorThrown').html("here is the errorThrown"+errorThrown);
}
});
}
Codeigniter controller
public function process_order_when_all_drinks_served($user_id)
{
$bartender_id = $this->session->userdata('bartender_id');
//load model
$this->load->model('authorizenet_model');
//finalize order with authorizenet prior authorize and capture
$response = $this->authorizenet_model->priorauthcapture($user_id);
print_r($response);
if($response->response_code=="1")
{
//stores the order_line before it is deleted
$this->bartender_model->store_past_order_line($user_id);
//deletes customer from order line if all beers and mixed drinks have been served
$this->bartender_model->delete_customer_from_order_line($user_id);
//order was successful
$response_message= '<center><strong>'.$response->response_reason_text.'</strong></center>';
}
else
{
//store userdata in unprocess orders
$this->bartender_model->store_unprocessed_order($user_id,$bartender_id);
//then erases it from order_line
$this->bartender_model->delete_customer_from_order_line($user_id);
$response_message= '<center><strong style="color:red;">'."There was a problem with the order.<br/>"
.$response->response_reason_text.$response->error_message.'</strong></center>';
}
return $response_message;
}
public function bartender_serve_beers(){
//checks if there are any drinks left to process order
if(isset($_POST['delete_beer']) && isset($_POST['user_id'])
{
$user_id = $_POST['user_id'];
$beer_id = $_POST['beer_id'];
//then it is deleted from the paid beers
$this->bartender_model->delete_beers($user_id,$beer_id);
//checks if there are any drinks left to be processed
$checks_any_drinks_left= $this->bartender_model->checks_if_mixed_drinks_beers_left_to_process_order($user_id);
if($checks_any_drinks_left=="1")
{
$user_id = $this->session->userdata('user_id');
$proccess_drinks_message= $this->process_order_when_all_drinks_served($user_id);
//outputs the response message to bartender
echo $proccess_drinks_message;
}
else
{
$user_id = $this->session->userdata('user_id');
//continues outputting beers
echo $beers_served_button = $this->bartender_model->output_beers_served_button($user_id);
}
}
else
{
$user_id = $this->session->userdata('user_id');
echo $beers_served_button = $this->bartender_model->output_beers_served_button($user_id);
}
}

I don't see nesessity to have output of session variable to frontend.
You will have it in next controller too. Better would be to check in next controller if it still exists.
Add one check in inside else like:
//...
else if ($this->session->userdata('user_id') != false && !empty($this->session->userdata('user_id')) ) {
$user_id = $this->session->userdata('user_id');
//continues outputting beers
echo $beers_served_button = $this->bartender_model->output_beers_served_button($user_id);
}//...rest of the code
Also, you check for $_POST['delete_beer'] and than assign $_POST['beer_id'] to $beer_id variable. Although I can't see you passed any beer variable through AJAX. As far as I can see, you pass only session output.

Related

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Ajax div to refresh on success not working

I have a DIV which contains how many likes fetching from Mysql database.
I click on button which says like and it will go through ajax function like(id1) with parameter.
Ajax use page likes.php and does all job adding to database. And it gives out JSON data as feedback with code zero if successful. And one if fails.
In success section ajax _js.code is one then its already liked. Thus shows us message. But my problem is I cannot refresh DIV likes when code is zero which is success. It either goes to top of the page instead of staying at DIV likes.
For information it also appends hash TAG at the end of URL.
Button line, I want like button which should work as facebook or other major app does. Without moving page on top. And update like button immediately when clicked.
My main page
<input type="checkbox" id="like" onclick="like(<?php echo $_SESSION["id"];?>);"/>
<div id="likes">
<?php
$like = 0;
$conditions = "WHERE id = $_SESSION[id]";
echo $total = $ll->get_likes($conditions); //displaying how many likes
?>
</div>
Ajax
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}
likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' = 0,
'message' = ""
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
change following in HTML and JS
<input type="checkbox" id="like" onclick="return like(<?php echo $_SESSION["id"];?>);"/>
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
return false;
}
#tashi,
There is a syntax error in likes.php. Use => operator when declaring arrays. The code should be as follows.
$return = array (
'code' => 0,
'message' => ""
);
if you want to display no of likes on success the change your code as follows
In likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' => 0,
'message' => "",
'likes_count' => $likes_count //get updated likes count from db
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
//here you do not need to send the like count
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
javascript code
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
$('#likes').html(_js.likes_count);//this will update your likes count
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}

I am trying to write an UPDATE query in codeigniter but for some reason it's inserting a new record with default values

I am trying to update an existing message. A message has a message_id, category, subject and the message. Upon clicking on edit, an AJAX call is made ...
Here's my AJAX call from .js file (VIEW)
if(checkEditMessage()){ // checkEditMessage is to check for validation
console.log("EDIT");
var cat_id = $("#cat_id").val();
var commentsubject = $("#commentsubject").val();
var chat_post_message = $("#chat_post_message").val();
$.ajax({
url: base_url + "chat/editMessage",
async: false,
type: "POST",
data: {
"v_id" : id,
"v_cat_id" : cat_id,
"v_commentsubject" : commentsubject,
"v_chat_post_message" : chat_post_message
},
error: function(err){
console.log(err);
},
success: function (result) {
console.log(result);
}
});
}
Here's my chat.php (CONTROLLER)
function editMessage(){
$posted_data = $this->input->post();
if(isset($posted_data) && !empty($posted_data))
{
$id = $posted_data['v_id'];
$cat_id = $posted_data['v_cat_id'];
$commentsubject = $posted_data['v_commentsubject'];
$chat_post_message = $posted_data['v_chat_post_message'];
$data = $this->chat->updateMessage($id, $cat_id, $commentsubject, $chat_post_message);
echo $data;
}
}
Here's my (MODEL)
function updateMessage($id, $cat_id, $commentsubject, $chat_post_message){
$data=array('cat_id'=>$cat_id,'subject'=>$commentsubject,'message'=>$chat_post_message);
$this->db->where('message_id',$id);
$this->db->update('chat_message',$data);
$err = $this->db->_error_message();
if(empty($err))
{
return "EDIT COMPLETE";
}
return false;
}
Your question is not totally clear, because I don't see any insert, and in order to insert it's really needed the insert clause in your query. I can only tell you some improvements you may want to do.
Which version are you using of codeigniter? Because I don't see you using the word _model which is necessarily.
$message['v_id'] = $posted_data['v_id'];
$message['v_cat_id'] = $posted_data['v_cat_id'];
$message['v_commentsubject'] = $posted_data['v_commentsubject'];
$message['v_chat_post_message'] = $posted_data['v_chat_post_message'];
// `chat_model` and not `chat`
$result = $this->chat_model->updateMessage($message['v_id'], $message);
On the other hand, all you need to do in your model function is
public function updateMessage($id, $data)
{
$this->security->xss_clean($data);
$this->db->where('message_id', $id)
->update('chat_message', $data);
return empty($this->db->_error_message());
}
In you ajax change this
url: "<?php echo base_url() ?>chat/editMessage",
async: false,// remove this
data: {
"v_id : id,
v_cat_id : cat_id,
v_commentsubject : commentsubject,
v_chat_post_message"} ,
and your model and controller looks ok
You can try the following:
Make sure your message_id is getting posted properly. i.e. echo $posted_data['v_id']; in editMessage() to see if the correct value is being received.
Make sure the id you are trying to update exists, and that message_id in your database is the PRIMARY KEY field.

Updated values are not being added to server database using ajax? [duplicate]

This question already exists:
Database values are not updating?
Closed 8 years ago.
I am using this code to call ajaxvote.php
$('.vote').click(function(){
$.ajax({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false',
success: function () { alert("Success!"); } ,
error: function () { alert("Error!"); }});
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var postid = parent.data('postid');
var score = parent.data('score');
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('.vote-score').html(++score).css({'color':'orange'});
self.css({'color':'orange'});
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('.vote-score').html(--score).css({'color':'red'});
self.css({'color':'red'});
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
parent.addClass('.disabled');
This is the code from my webpage
<div class="item" data-postid="<?php echo $rows['ID'] ?>" data-score="<?php echo $rows['VOTE'] ?>">
<div class="vote-span">
<div class="vote" data-action="up" title="Vote up"><i class="fa fa-camera-retro"></i></div>
<div class="vote-score"><?php echo $rows['VOTE'] ?></div>
<div class="vote" data-action="down" title="Vote down"><i class="fa fa-camera-retro"></i></div>
</div>
This is my php code
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) && (isset($_POST['action']))) {
$postId = $_POST['postid'];
if (isset($_SESSION['vote'][$postId])) return;
$query = $mysqli - > query("SELECT VOTE from stories WHERE ID = $postId LIMIT 1");
while ($rows = mysqli_fetch_array($query)) {
if ($_POST['action'] === 'up') {
$vote = ++$rows['VOTE'];
} else {
$vote = --$rows['VOTE'];
}
$mysqli - > query("UPDATE stories SET VOTE = $vote WHERE ID = $postId ");
$_SESSION['vote'][$postId] = true;
}
}
}
I know I can connect to database because I can login. I also get the alert success I have set up above, However, the values are not updating in Database.
EDIT
I have added more Ajax code that I had already written.
When posting via ajax, you need to send through the data you actually want to post.
var postData = {name:"Mister",lastName:"Frodo"}; //Array
$.ajax({
url : "ajaxvote.php",
type: "POST",
data : postData,
success: function(data, textStatus, jqXHR)
{
//Handle response
},
error: function (e) {
// Handle error
}
});
In this case, the post ID and score needs to be grabbed. You also need to grab what kind of action is clicked (typically through a click event bind on the divs with class="vote". For example purposes, let's just set it to "up" for now:
var postId = $('div.item').attr('data-postid').val();
var score = $('div.item').attr('data-score').val();
var postData = {postId: postId, score: score, action: 'up'}
You can now post that "postData" to your ajaxvote.php.
Also, you can use jQuery's $.POST method
$.post("ajaxvote.php", { name: "Mister", lastName: "Frodo" } );
Now for parsing your form, have a look at jQuery's serialize which goes through your form takes each input's [name] attribute along with the value to create a data-string.
Example
name=Mister&lastName=Frodo
This is ideal for sending through with the "data" attribute in $.ajax. Have a look at this answer for more regarding jQuery's serialize.

Ajax method calls same function in controller but needs to load different results in different areas

I am a bit stuck with my website, currently on the new section of my site(among others) the user rolls over a thumbnail and gets the articles abstract displayed below it, and then when they click on said thumbnail the article appears on the left of the page,
The ajax works by pulling the href from the link that surronds the thumbnail image and using that as the url for the method call, the problem is that the click version will also be using the same function call, I cannot work out how to show the different content depening on what even happends, currently I have this as my code,
<?php
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class='$v[category_name]'><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
?>
<script>
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
});
</script>
The method that gets called is,
public function get_content_abstract() {
$this->load->model('content_model');
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
This is called by the ajax following the link /get_content_abstract/3, where 3 or any other number is the articles ID.
How can I sort so that I can use this function again, but only show that body content of the article instead of the abstract if the link is clicked and mouseovered?
You can pass a call type variable and check for it in your php code. Notice I added data to your ajax calls.
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
data: "calltype=abstract",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
data: "calltype=full",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
pass a GET variable in the url of the ajax call.
You just pass an variable to the handler via GET or POST that tells the handler which content to show. As your AJAX calls are simple, you can simplify the calls and use load(). If you can't use $_GET or $_POST, just append the data in the URL:
$("a.contentlink").mouseover(function() {
// URL becomes index.php/home/get_content_abstract/3/abstract
$('#abstract').load($(this).attr("href")+'/abstract');
});
$("a.contentlink").click(function(ev) {
$('#main_menu').hide();
// URL becomes index.php/home/get_content_abstract/3/full
$('#left-content').load($(this).attr("href")+'/full');
return false;
});
And in PHP, you can use something like this:
public function get_content_abstract() {
$this->load->model('content_model');
if($this->uri->segment(4) == 'full') {
// Load full content
} else {
// Load abstract
}
$this->load->view('template/abstract', $data);
}

Categories