I am currently trying to update a textarea when a user clicks elsewhere. I'm not well-versed in AJAX and Jquery. However, the script doesn't seem to be updating the row in the DB.
Jquery/Text area:
<textarea id="<?php echo $item_id; ?>_textarea"><?php echo $notes; ?></textarea>
<script type="text/javascript">
$('<?php echo $item_id; ?>_textarea').on('blur',function () {
var notesVal = $(this).val(), id = $(this).data('id');
var itemVal = <?php echo $item_id; ?>;
$.ajax({
type: "POST",
url: "updateNotes.php",
data: {notes:notesVal , id:id, itemId:itemVal},
success: function(msg) {
$('#'+id).html(msg);
}
})
});
</script>
updateNotes.php:
<?php
include('db_connect.php');
include('order_functions.php');
$email = $_SESSION['username'];
$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];
$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if(result) {
return "Notes Updated";
}
?>
You forgot the $ in your last if-statement in your php-code and you should use "echo" (or likewise) instead of "return" as you are not in a function.
<?php
include('db_connect.php');
include('order_functions.php');
$email = $_SESSION['username'];
$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];
$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result) {
echo "Notes Updated";
}
?>
Your html/javascript-code is a bit wrong. This is how i guess you wanted it to work:
<div id="<?php echo $item_id; ?>_div">
<textarea id="<?php echo $item_id; ?>_textarea" data-id="<?php echo $item_id; ?>"><?php echo htmlentities($notes); ?></textarea>
</div>
$('#<?php echo $item_id; ?>_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "updateNotes.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
success: function (msg) {
$('#' + id + '_div').html(msg); //Changes the textarea to the text sent by the server
}
});
});
Good luck
Related
What I'm trying to achieve is a user to follow another user without having to refresh the page. So far I've played around and had no problem inserting and deleting the rows in mysql table, but now when I'm trying with AJAX I can't get it to work.
jquery
$(document).ready(function(){
$("#followbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#followbutton').hide();
$('#unfollowbutton').show();
// $("#unfollowbutton").hover(function(){
// $(this).text("Unfollow");
// }, function(){
// $(this).text("Unfollow");
// });
}
});
});
});
$(document).ready(function(){
$("#unfollowbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitUnfollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#unfollowbutton').hide();
$('#followbutton').show();
//I want the button to change its text to Following and when hovering it should say unfollow if user is followed
}
});
});
});
followuser.inc.php
<?php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if (isset($_POST["submitFollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('INSERT INTO userfollow (thefollower, theuserid, followstatus) VALUES (?,?,?)');
$followstatus = 1;
$stmt->bind_param('sss', $userthatisfollowed, $theuserid, $followstatus);
$stmt->execute();
echo $response = "<span>Followed!</span>";
$stmt->close();
} else if(isset($_POST["submitUnfollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('DELETE userfollow FROM userfollow WHERE thefollower = ? AND theuserid = ?');
$stmt->bind_param('ss', $userthatisfollowed, $theuserid);
$stmt->execute();
echo $response = "<span>Unfollowed!</span>";
$stmt->close();
} else {
echo "DID NOT WORK";
}
profile.php
if(isset($_SESSION["userid"]) && $_SESSION["userid"] != $userthatisfollowed) {
?>
<form action="<?php echo htmlspecialchars("includes/followuser.inc.php");?>" id="followform" method="post">
<?php
if ($resulted->num_rows > 0){
$subscribe_status = "Unfollow";
$subscribe_text = "Following";
} else {
$subscribe_status = "Follow";
$subscribe_text = "Follow";
}
echo "<button name='submit".$subscribe_status."' id ='unfollowbutton' type='submit' style='display:none'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
echo "<button name='submit".$subscribe_status."' id ='followbutton' type='submit'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
// echo "<button name='submit".$subscribe_status."' id ='notificationbell' type='submit' style='display:none'>";
// echo "<i class='fa fa-bell'></i>";
// echo "</button>";
echo "<div id='followmessage'></div>";
?>
<input type="hidden" name="theuserid" id="theuserid" value="<?php echo $_SESSION["userid"] ?>">
<input type="hidden" name="thefollower" id="thefollower" value="<?php echo $userthatisfollowed; ?>">
</form>
<?php
}
What's worth noting is that I'm getting the response DID NOT WORK which tells me that if(isset($_POST["submitUnfollow"])) is not set. However, If I try with if(isset($_POST["theuserid"]) && (isset($_POST["thefollower"])) then it actually works for the insert query but not for the delete query.
You're missing the submitFollow parameter in the data: object. Instead, you have followbutton: true, which isn't used by the PHP code. So change that to:
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFolow': 'true'},
And for the unfollow button, use submitUnfollow instead.
I am doing my first project in web development. i am using php ajax and jquery. I am looking for a solution to the following problem:
When a user clicks 'add to cart' button, that (product/'add to cart' button for that product) should be disabled for that particular user until the user removes the product from his cart page. i.e user should not be able to add the same product again and again into the cart.
this is my javascript file,"init.js"
('.add_to_cart').on('click dblclick',adding);
//$("body").on(".add_to_cart","click",adding);
function adding(e) {
e.preventDefault();
var prodid =$(this).attr("id");
var that = $(this);
that.off("click dblclick");
$.ajax({
type: "POST",
url: "addcart.php",
data:{prodid:prodid}
}).done(function(msg) {
alert(msg);
}).always(function() {
that.off("click dblclick",adding);
})
};
this is php file,"addcart.php"
<?php
session_start();
/*if(isset($_SESSION['islogged'])){
if(!isset($_SESSION['username']))
echo "Please log in to add books to your cart";
}
*/
require_once 'connect.inc.php';
if (isset($_POST['prodid'])) {
if (!empty($_POST['prodid'])) {
if (!isset($_SESSION['username'])) {
echo "Please log in to add books to your cart";
} else {
$product_id = $_POST['prodid'];
$username = $_SESSION['username'];
$query = "SELECT * FROM `books1` where `id`='$product_id'";
$query_run = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($query_run)) {
$productname = $row['name'];
$productid = $row['id'];
$productauthor = $row['author'];
$productpublication = $row['publication'];
$productcategory = $row['category'];
$productsubcategory = $row['sub_category'];
$productborrowalprice = $row['borrowal price'];
$productimage = $row['image'];
$query1 = "INSERT into `cart`(`user_name`,`p_id`,`p_name`,`p_author`,`p_publication`,`p_category`,`p_subcategory`,`p_borrowalprice`,`p_image`,`qty`)VALUES('$username',$productid,'$productname','$productauthor','$productpublication','$productcategory','$productsubcategory','$productborrowalprice','$productimage',0)";
$result = mysqli_query($link, $query1);
if ($result) {
echo 'successful';
} else {
die(mysqli_error($link));
}
}
}
}
}
?>
you use btn.loading and btn.reset. save your btn as a variable to avoid clashes when the scope changes.
$('.add_to_cart').on('click dblclick',adding);
//$("body").on(".add_to_cart","click",adding);
function adding(e) {
var cur = $(this).button("loading");
e.preventDefault();
var prodid =$(this).attr("id");
var that = $(this);
that.off("click dblclick");
$.ajax({
type: "POST",
url: "addcart.php",
data:{prodid:prodid}
}).done(function(msg) {
alert(msg);
}).always(function() {
that.off("click dblclick",adding);
cur.reset()
})
};
I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}
I want to get the latest post_id in the table without refreshing it, but the problem is whenever a user inserts a value to the database, It echoes infinitely the last post_id. I want it to echo only once. But I still want to get the latest post_id from the table.
Here is my main php:
<div id = "this_div">
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id ASC LIMIT 20";
$execute_query = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($execute_query))
{
$get_this_id = $row['post_id'];
echo $get_this_id."<br>";
}
$_SESSION['get_this_id'] = $get_this_id;
?>
</div>
here is my jQuery ajax:
<script>
var refreshId = setInterval(function(){
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
$.ajax({
url: 'another_file.php',
data: {},
success: function(data)
{
if(compare_session != data)
{
$('#this_div').text($('#this_div').text()+data);
}
}
});
},400);
</script>
here is the php code of another_file.php
<?php
include 'connect.php';
session_start();
$query = "SELECT post_id FROM tbl_posts ORDER BY post_id DESC LIMIT 1";
$execute_query = mysqli_query($con,$query);
if($row = mysqli_fetch_assoc($execute_query))
{
echo $get_this_id = $row['post_id'];
}
?>
You are not updating the compare_session variable , it holds always the initial value . So update it inside success callback function
compare_session = "<?php echo $_SESSION['get_this_id']; ?>";
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: {},
success: function (data) {
if (compare_session != data) {
$('#this_div').text($('#this_div').text() + data);
}
compare_session = data;
}
});
}, 400);
I am working on a voting system in jquery. I have it where a user can vote up or if they change their mind vote down and it deducts from the upvote and puts it in on the down vote. But my problem is I cant get both numbers to refresh when a vote is selected so it just uses the original number instead of the updated number.
Vote Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
</script>
<?php
$sql=mysql_query("SELECT * FROM uploads LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['title'];
$mes_id=$row['id'];
$up=$row['up'];
$down=$row['down'];
?>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?> up
</a>
<div class='down'>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?>
</a>
</div>
<div class='box2' >
<?php echo $msg; ?>
</div>undefined</div>undefined
<?php } ?>
The up_vote.php page..
(down_vote.php is exactly the same as up_vote except it just changes up to down.)
<?php
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
if ($_POST['id']) {
$id = $_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql = mysql_query("select ip from votes where img_id='$id' and ip='$ip'");
$count = mysql_num_rows($ip_sql);
if ($count == 0) {
// Update Vote.
$sql = "UPDATE uploads SET up=up+1 WHERE id='$id'";
mysql_query($sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into votes (id,img_id,ip,type) values ('','$id','$ip','up')";
mysql_query($sql_in);
} else {
//if already voted change it..
$result = mysql_query("SELECT * FROM votes WHERE img_id='$id' AND ip='$ip'");
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
$up = mysql_query("UPDATE uploads SET up=up+1 WHERE id='$id'");
$down = mysql_query("UPDATE uploads SET down=down-1 WHERE id='$id'");
$vote = mysql_query("UPDATE votes SET type=up WHERE img_id='$id' AND ip='$ip'");
}
}
$result = mysql_query("select up from uploads where id='$id'");
$row = mysql_fetch_array($result);
$up_value = $row['up'];
echo $up_value;
}
?>
Not an answer but too long for a comment. This script:
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
/* ... */
}
I don't think you need it like it is now. You are actually only using the last fetched row, not all of them. If that's your intention (because there's only one), then you don't need the while() at all. You could change it for:
$row = mysql_fetch_row($result);
$vote_type = $row['type'];
if ($vote_type == 'down') {
/* ... */
}
Furthermore, I'd recommend to change your code to PDO. It's more secure and mysql_* is deprecated.