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.
Related
I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER
Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.
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.
I am send a ajax request to php file where i will update the database and and i will select a value according to my condition. But how to return that $variable in ajax callback and show it in input text box.
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
}
});
my PHP file is
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['id']==2) //taking
{
$book_id = $_GET['bookid'];
$startdate = $_GET['startdate'];
$update_validity = "UPDATE booking SET valid = '2',start_date_timestamp = '$startdate' where book_id = '$book_id'";
$query = mysql_query($update_validity);
if($query==TRUE)
{
$get_select_query = "select start_date_timestamp from booking where book_id = '$book_id'";
$get_query = mysql_query($get_select_query);
$row = mysql_fetch_assoc(get_query);
$startdate_return = $row['start_date_timestamp'];
echo $startdate_return;
}
}
?>
You should use json format like:
in your php file
$arrFromDb = array(
'id' => 1,
'bookName' => 'Da Vinci Code'
)
echo json_encode( $arrFromDb ); exit();
in you script
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
var book = $.parseJSON(data) // now book is a javascript object
var bookName = book.bookName;
}
});
I hope this will help you
Create an element in your page like <span> and give it a unique ID like <span id="testspan"></span>. This is where the text gets displayed. Then in your JS;
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
$( "#testspan" ).html(result);
}
});
Just echo in your php file, the output (instead of being shown by the browser as a default PHP page) will be usable in the JS as the result of the ajax call (data)
Try to use val(),
HTML
<input type="text" id="inputId" />
Js
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
$( "#inputId" ).val(data);
}
});
PHP CODE
<?php
echo $bookid= isset($_REQUEST['bookid']) ? $_REQUEST['bookid'] : "No bookid";
// you can use $_GET for get method and $_POST for post method of ajax call
return
?>
In updatenewuser.php
//after all operations
echo $variable_to_pass;
Then in the ajax request :
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
alert(result);//result will be the value of variable returned.
$("#input_box").val(result); //jquery
document.getElementById("input_box").value = result; // Javascript way
}
});
HTML being :
<input type="text" id="input_box" value=""/>
Cheers
oI am having problem fetching comments from MySQL database using jQuery.
I am trying this way, but its not working.
PHP (comments.php)
<?php
if (isset($_POST['value1'])) {
$id = ($_POST['value1']);
}else{
$id = '';
}
if (isset($_POST['value2'])) {
$database = ($_POST['value2']);
}else{
$database = '';
}
if (isset($_POST['value3'])) {
$tablename = ($_POST['value3']);
}else{
$tablename='';
}
require_once('rt-connect.php');
$find_data = "SELECT * FROM $tablename";
$query = mysqli_query($connection, $find_data);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['comment']; ?></p></div>
</div>
<?php endwhile;?>
Jquery(comments.html)
var id=2;
var database='comments_db';
var tablename='comments';
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').load('comments.php .comment-container');
});
Html(div on comments to load on comments.html)
<div id="comments"></div><!--end of comments-->
Please see and suggest any possible way to do it.
Thanks
Try This one it will help you.
This is jquery Ajax post method requesst if you want to show your data is loaded or not just remove the commet.
$.ajax({
type: "POST",
url: url,
data: { value1:id, value2:database, value3:tablename}
}).done(function( data ) {
//alert(data); return false;
$("#comments").html(html);
});
You have $.load() inside success function of $.post(), try this..
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').html(data);
});
In your javascript, you are posting data to a url, accepting response and if the response is successful, you are sending another request to the PHP script, this time without parameters. Your comments box is displaying the result of your second request.
You do not require :
$('#comments').load('comments.php .comment-container');
in your javascript, since you have already received a response. Instead, use :
$('#comments').html(data);
which will display the response data in the comments div.
You could try this one,
var id = 2;
var database = 'comments_db';
var tablename = 'comments';
$.ajax({
type :"POST",
data :"id="+id+"&database="+database+"&tablename="+tablename,
url : comments.php,
success: function(msg){
$("#comments").html(msg);
}
});
When I click on share on a users link..It shares that post fine, yet it posts it twice. I've checked firebug and when clicked (Once) it shows up two POST requests, inserts two posts to the database and then shows them in the users feed.
I really don't understand where I'm going wrong.
SHARE LINK
echo'<a class="sharelink" title="Share '.$poster_name['fullusersname'].'s status" href="#"
data-streamitem_creator='.$streamitem_data['streamitem_creator'].'
data-streamitem_target='.$_SESSION['id'].'
data-streamitem_content='.$streamitem_data['streamitem_content'].'
data-streamitem_type_id=4>Share</a>';
AJAX
$(document).ready(function() {
$('.sharelink').click(function(e) {
e.preventDefault();
var streamitem_creator = $(this).data('streamitem_creator');
var streamitem_target = $(this).data('streamitem_target');
var streamitem_content = $(this).data('streamitem_content');
var streamitem_type_id = $(this).data('streamitem_type_id');
$.ajax({
type: "POST",
url: "../include/share.php",
data: {
streamitem_creator: streamitem_creator,
streamitem_target: streamitem_target,
streamitem_content: streamitem_content,
streamitem_type_id: streamitem_type_id
},
success: function(data) {
$(".usermsg").html(data);
}
});
});
});
SHARE.php
<?
session_start();
require"load.php";
if(isset($_POST['streamitem_type_id'])&isset($_POST['streamitem_creator'])&isset($_POST['streamitem_content'])&isset($_POST['streamitem_target'])){
user_core::create_streamitem(4,$_SESSION['id'],$_POST['streamitem_content'],1,$_POST['streamitem_creator']);
}
?>
LOAD.PHP
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,UTC_TIMESTAMP(),'$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser= rawfeeds_user_core::getuser($creatorid);
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
I can't see any problem.. By any chance, don't you have that $('.sharelink').click handler registered twice within your page?