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
}
}
});
}
Related
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.
Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>
here's the deal, i've created a search results page and i'd like to open a modal and retrieve profile data via ajax in php but i'm not too sure on how i can implement it. I've created the modal but but i don't know how i would go about getting the 'id' from clicking the search result, passing it onto ajax to retrieve the profile details.
Twitter has this kinda feature; when you click a username in a feed and it opens a modal and gives you a brief overview of the profile with a link to the full profile.
It would mean so much to me if someone could help me out or point me in the right direction! :)
P.S. I'm using codeigniter, if anyone is wondering what framework i'm using.
EDIT: here's the code
<?php
/*** PHP Search Results Loop ***/
if ($num > 0){
foreach ($query->result_array() as $row)
{
echo "link to ajax"'>";
}
} else {
echo "<strong>results not found :(</strong>";
}?>
<script> /* jQuery Runs When Result Has Been Clicked */
$('#ResultText').click(function() {
var targetid = {
id: /*Profile Id*/,
ajax: '1'
};
/* Modal Code */
$('.modal-backdrop, .modal-profilebox').css('display', 'block');
$('.modal-backdrop').animate({'opacity':'.50'}, 100, 'linear');
$('.modal-profilebox').animate({'opacity':'1.00'}, 200, 'linear');
$.ajax({
url: "<?php echo site_url('finder/modal'); ?>",
type: 'POST',
data: form_data,
success: function(profileData) {
$('.modal-profilebox').html(profileData);
}
});
return false;
});
</script>
Try something like this
public function ajax_user_profile($user_id)
{
if( !$this->input->is_ajax_request() )
{
redirect('/'); //only allow ajax requests
}
try
{
$user_profile = ''; //grab user object from DB
if( !$user_profile )
throw new Exception("Error Message");
}
catch(Exception $e)
{
log_message('error', $e->getMessage());
echo json_encode(array(
'error' => 1
));
exit;
}
$data = $this->load->view(array(
'some_view' => 'some_view',
'user' => $user_profile
), TRUE); //NO Template, just the view by adding TRUE
echo json_encode(array(
'error' => 0,
'data' => $data
)); //return view data
}
--
<a rel="modal" data-user-id="1" >Joe Bloggs</a>
--
(function($){
var userObj = {
init : function(){
this.getProfile();
},
getProfile : function(){
var modalSearch = $("a[rel='modal']");
modalSearch.on('click', function(){
//trigger the modal window
//request ajax
$.ajax({
url : BASEPATH + 'users/profile/' + $(this).data('user-id'),
type : 'POST',
dataType: 'json',
success : function(callback){
if(callback.error ==0)
{
$('.modal-profilebox').html(callback.data);
}
}
});
});
}
}
$(function(){
userObj.init()
});
})(jQuery);
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";
Building a comment system with Ajax and JQuery and I want the div the comments are in to reload after a comment is added. It posts just fine. This is what I have so far.
The function getComments queries the database and generates the html
$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){
????????? What should go here... it is a div with id#commentBody
}
<div id="commentBody">
<ul>
<?php
$q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
getComments($row,$postID,$custID);
endwhile;
?>
</ul>
</div>
Since you're regenerating the entire div I would use replaceWith.
$('#commentBody').replaceWith(html);
When you post it, you should return the data you want from your server side script. Then you can use the .html() jQuery function to update your div.
So, like:
$('#commentBody').html(html);
You could also return just the latest comment (optionally as a JSON object) and then just use the .append() method to add it to your #commentBody.
I would create a JSON object which has a status property and a data property. When the status is -1 (or whatever) there was an error adding the comment and you could put a message in the data property. When the status is 0, it was successful and the latest comment information would be available available in the data property.
Example
PHP
//Check postback variables, add comment and retrieve
// comment information (such as ID) if necessary
if (postedsuccessfully) {
$ary = array("status" => 0,
"data" => array("id" => $commentidvar,
"user" => $commentuser,
"text" => $comment)
);
echo json_encode($ary);
} else {
$ary = array("status" => -1,
"data" => "There was a problem adding your comment.");
echo json_encode($ary);
}
JavaScript
success: function(json){
if (json.status == 0) {
$mydiv = $('<div>');//construct your comment div using json.data.id,
//json.data.user, and json.data.text
$('#commentBody').append($mydiv);
} else {
alert(json.data);
}
}