I have rows of data in a mysql table called user_timeline.
I have a column in this table labeled deleted.
I'm running my query to fetch all results in my table where deleted = 0.
$result = $conn ->query ("SELECT * FROM user_timeline WHERE user_id = '$p_id' AND deleted = '0' ORDER BY time_date DESC");
I want to give the user the option to be able to mark a result as deleted in the table by setting this to 1.
I figure i can do this by creating a link that will post to my page del_timeline.php
if(isset($_SESSION['CUSTOMER_ID'])){
echo '<a id="del_t" href="assets/del_timeline.php?t_id='.$row['id'].'"><div class="delete_timeline"></div></a>';
}
In del_timeline.php i have the following update query:
<?php
session_start();
include 'connect.php';
if(isset($_GET['t_id'])){
$t_id = $conn->real_escape_string($_GET['t_id']);
$myID = $_SESSION['CUSTOMER_ID'];
$conn->query("Update user_timeline Set deleted = '1' Where id = $t_id AND user_id = $myID") ;
}
?>
As you can imagine, each result in my table will have a specific/unique ID. So that it can keep track of which result the user is trying to set as deleted. Whilst this works via a normal href click event. I am trying to get this to run using ajax to avoid a page refresh.
I am not entirely sure how to pass a mysql $row parameter through ajax. I have tried the following but it doesn't seem to work.
<script>
$( "#del_t" ).submit(function( event ) {
event.preventDefault(); // <---- Add this line
$.ajax({
type: "POST",
url: "assets/del_timeline.php?t_id=$row['id']",
data: $( "#del_t" ).serialize(),
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
</script>
please can someone show me where I am going wrong?
First of all, you need to attach event handler to prevent page reload when users click on href links. Consider something like this in your javascript:
$( document ).on( 'click', 'a[id="del_t"]', function( event ) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: $( this ).attr( 'href' )
} )
.done( function( response ) {
// Do something with the success response...
// Maybe delete the row containing deleted data
} );
} );
Then, you'll need to send some data from your del_timeline.php.
Use PHP's echo to pass mysql result or any PHP variable to the client browser (your javascript code).
<?php
session_start();
include 'connect.php';
if(isset($_GET['t_id'])){
$t_id = $conn->real_escape_string($_GET['t_id']);
$myID = $_SESSION['CUSTOMER_ID'];
$conn->query("Update user_timeline Set deleted = '1' Where id = $t_id AND user_id = $myID") ;
// Send some success response
echo 'success'; // or any data you want to send
}
// Send some error response
echo 'error';
?>
You not need to add the id from php to ajax function. You can use the href address from the link.
$( "#del_t" ).click(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('href'),
data: '',
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
Or, better, put the id into an attribute in <a> (ex. in title), use $_REQUEST in php. In ajax get the id from that attribute to pass it in data sent via post. In php:
echo '<a id="del_t" href="assets/del_timeline.php?t_id='.$row['id'].'" title="'.$row['id'].'"><div class="delete_timeline"></div></a>';
In del_timeline.php:
if(isset($_REQUEST['t_id'])){
$t_id = $conn->real_escape_string($_REQUEST['t_id']);
//your code
}
Ajax:
$( "#del_t" ).click(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'assets/del_timeline.php',
data: 't_id='+$(this).attr('title'),
success: function(data) {
// print here
},
dataType: 'html' // for json response or 'html' for html response
});
Related
Please help to fix this issue with like counting.
i create a news feed like facebook using php mysql and ajax.
problem is that when i click on like button it prints like count from (this value) and showing to all, let say i have 5 posts and like current value for different posts are 100, 200 , 70 , 80 , 578. when I click on first post ajax success count 100+1 = 101 for first post and for all other post printting same 101 likes. now if i will go to 2nd post and its like value 200, ajax will show 200+1 =201 like. so after click on 2nd post all 5 posts like will show 201. its creating problem for me. I understand that after ajax success i mentioned to show the value to div class (.ajax_like_result), thats why its showing in every post, same result until i am not clicking on different post.
how to fix this so that when I click on any post it wil show only its real like value??
I try to change the DIV attribute id , instead of class then it only works for first post. other post totally not working. if i set div atribute to class then like is working but printing incorrectly as i mentioned above.
I have pasted below- html , php and ajax code . thanks for your help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.ajax_like').on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(".ajax_like_result").html(data);
}
});
});
});
</script>
html :
<li class="ajax_like" type="submit" name="data-id" data-id="<?php echo $page;?>" value="<? echo $post_id;?>">
<div class= "ajax_like_result" ><?php print $likes;?></div>
</li>
like.php code :
<?php //user info start
session_start();
$conn=mysqli_connect("localhost", "u1068033_ab24", "ab#24", "u1068033_ab24");
mysqli_set_charset($conn,"utf8");
$id=$_SESSION['id'];
$get_post_id = $_POST['post_id'];
$page = $_POST['page'];
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
$likes=$row['likes'];
$sql="UPDATE $page SET `likes`=$likes+1 WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
echo $row['likes'];`enter code here`
?>
You should need some corrections on your jQuery
$(document).ready(function(){
$('.ajax_like').each( function(){
$(this).on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(this).find(".ajax_like_result").html(data);
}
});
});
})
});
you are writing the result to all HTML elements with the same class "ajax_like_result" when using this line:
$(".ajax_like_result").html(data);
you can use something such as:
$("li[data-id='"+page+"'] div.ajax_like_result").html(data);
Also better using native JavaScript and not jQuery, using document.querySelector
document.querySelector(`li[data-id='${page}'] div.ajax_like_result`).innerHTML = data;
and replace the jQuery AJAX with the native JavaScript fetch
example in one piece of code block with native JavaScript (no need for jQuery):
document.addEventListener("DOMContentLoaded", (event) => {
document.querySelectorAll('li[data-id]').forEach((elem)=>{
elem.addEventListener('click', event => {
const domElem = event.target;
const postId = domElem.getAttribute('value');
const page = domElem.getAttribute('data-id');
const data = {post_id:postId, page:page};
console.log({data});
fetch('like.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
const selector = `li[data-id='${page}'] div.ajax_like_result`;
document.querySelector(selector).innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
});
});
});
and better also to remove from the PHP code the '?>' as the PHP ends the script execution at the end and it will reduce some possible unwanted white spaces.
I have a datatable from which I want to take the text from a clicked cell and use it as a variable in PHP, so that I use that variable to query mysql. My codes so far as follows:
<script type="text/javascript">
$(document).ready( function () {
$('#priority tbody').on('click', 'tr', function() {
var celldat = $(this).find('td:first').text(); //gets the text from the first column when a row is clicked.
$.ajax({
url: 'prioritize.php', //my url
method: "POST",
async: 'false',
data: {variable:celldat},
success: function(data) {
alert(celldat); //The alert is perfect. It returns the text from the first column.
window.location.reload(true);
}
})
});
});
</script>
In my PHP I am trying to echo the same value:
<?php
$selected=$_POST['variable'];
echo $selected;
?>
But it is not working. Essentially I want to use the $selected in mysql select query to populate another table.
in data: try to make it like this : "data: {variable:"+celldat"}"
Try to do this $_POST['data'] this will give you all data sent from the ajax request
Following the comments, you need to modify your jQuery
success: function(data){ alert(celldat); }
to
success: function(html){ alert(html); }
PHP side
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$selected = $_POST['variable'];
echo"$selected";
?>
You need to do something with the response, as, upon success, with the code you showed first, you just send the page to itself: update a div or table cell...
Ajax let you use the data sent back from PHP without refresh, why would you reload then ?
example of udating a div with PHP response:
success: function(html){ // 'html' is PHP response
$("#responsediv").html(''+html+''); // update a div with ID 'responsediv'
// as ID have to be unique, it makes sure you have the proper data in the correct div
},
error: function (request, status, error) { // handle error
alert(request.responseText);
}
I have a file called post-blog.php this is collecting the data and storing it in a variable called page.
var page = title + content+ image + datetime +categories;
I'm then sending this off to publish.php, if sent correctly send the user to that page.
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: page,
success: function( page ) {
alert(page);
window.location.href = "publish.php";
}
});
return false;
This I my php script which is on the 2nd page (publish.php). How can I store the jquery data into php varible. So that I can display them on publish page.
<?php
if ( $_POST['page'] == true )
{
echo "Inserted";
}
?>
You can send this by setting data as follow:
data: {'page': page},
jQuery has some examples on the $.ajax and $.post page:
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.post/
You can send data using query string variable in url like this
$.ajax({
type: 'POST',
cache: false,
url: 'publish.php',
data: page,
success: function( page ) {
alert(page);
window.location.href = "publish.php" + "?page=" + page ;
}
});
return false;
Then on publishing page you could get data using following code
if (isset($_POST['page']) && $_POST['page'] != '') {
var_dump($_POST['page']);
echo 'inserted';}
?>
you can pass your variable like this
var page = {
title : title,
content : content,
image : image ,
datetime : datetime ,
categories : categories
}
and then in php
<?php
if(isset($_POST["title"])){ // you can use content , image ,... same way
$title = $_POST["title"];
echo $title;
}
?>
and in ajax
success: function( response) { //response is the data which returned from php .. for sure (page) will work but just to be clear
alert(response);
//window.location.href = "publish.php";
}
if you want to use page as an array you can use
var page = [];
page.push(title);
page.push(content);
.......
then in php use
<?php
if (isset($_POST['page'])) {
print_r($_POST['page']);
}
?>
I'm making a chat function where staff members with the appropriate privileges can delete a line that has been posted to the chat room.
I'd like this function to work without refreshing the page, but I can't seem to get the jQuery / AJAX part of it right? Nothing happens at all.
As a jQuery newbie I was hoping that someone could point out the line that I'd have to look at?
a href that needs to be clicked to delete line:
for (var i in json.lines) {
lines.push("[<a class='delete' href='#' data-lineID='" + json.lines[i].id + "'>x</a>] " + json.lines[i].user + json.lines[i].divide + " " + json.lines[i].message);
}
jQuery:
$('a.delete').on('click', function(event) {
var id = $(this).data('lineID');
/* Request to .php file */
var request = $.ajax({
url: "/communications/chat.php?page=delete",
type: "POST",
data: { id : id },
dataType: "html"
});
event.preventDefault();
return false;
});
Part of the PHP script to execute:
case 'delete' :
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
try {
$query = $udb->prepare("UPDATE `chat_lines` SET `deleted` = '1' WHERE `id` = ?");
$query->bindValue(1,$id);
$query->execute();
} catch (Exception $e) {
die($e->getMessage());
}
}
break;
Any help is appreciated :)
This could be a long shot, but I think that your issue is caused by HTML element not being there when you load the Javascript.
jQuery will attach an event listener (in this case the click one) when the script is loaded.
If the element is added after the script loads, the listener is not attached so it won't trigger your code.
What you have to do is to use event delegation. This means that you have to change your javascript code to this:
$('#mainContainerOfYourChat').on('click', 'a.delete', function(event) {
var id = $(this).data('lineID');
/* Request to .php file */
var request = $.ajax({
url: "/communications/chat.php?page=delete",
type: "POST",
data: { id : id },
dataType: "html"
});
event.preventDefault();
return false;
});
In this way jQuery will listen to the main container of your page, when a click is fired, if it matches the a.delete selector, it will trigger your code.
If your PHP is deleting the post from the DB your only problem is it stays loaded on the client side until you reload the page.
If that is so you'll only need to include a line to remove the comment if the ajax call is successful:
var request = $.ajax({
url: "/communications/chat.php?page=delete",
type: "POST",
data: { id : id },
dataType: "html",
success: function(){
$("a.delete[data-lineID="+id+"]").parent().remove();
}
});
At the moment i have this piece of javascript code:
//Display custom confirm box and delete multiple message
$(document).ready(function () {
$(".delete_button-multiple").click(function () {
//Get message id as variable
var id = $(this).attr("id");
var dataString = 'id=' + id;
var parent = $(this).parent();
//Display custom Confirm box
jConfirm('Are you sure you want to delete this message?', '', function (r) {
if (r == true) { //initiate delete message if agreed
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: dataString,
cache: false,
success: function () {
window.location = "mail_inbox.php";
}
});
return false;
}
});
});
});
delete-mail_ajax.php:
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete FROM mail WHERE mail_id='$id'";
mysql_query( $sql);
}
This is a working code for deleting only one mail item.
I wrote the following code to delete multiple messages from checkboxes:
//Multiple delete mail
if(!empty($_POST['message'])){
$list_mail = $_POST['message'];
foreach ($list_mail as $messageID){
$sql = "delete FROM mail WHERE mail_id='$messageID'";
mysql_query($sql);
//deletion complete, refresh the page
header("Location: mail_inbox.php");
}
}//end delete multiple
The difficulty i'm having is changing the working code above to incorporate the multiple selection, and deletion, of selected mails.
Any help on this issue would be appreciated
-Callum
Assuming you're using checkboxes, your code would look something like:
var messages = new Array();
$("input[name='mail_items[]']:checked").each(function() {
messages.push($(this).val());
});
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: { message: messages } //jQuery should translate this to an array that PHP should understand
cache: false,
...
});
You may need to json_decode the input to the $_POST['message'] variable, but I'd do a var_dump() on the stuff first just to make sure what PHP is doing in the background. Can't check at the moment, sorry.
I guess you have trouble submitting the form via Ajax? There is a neat plugin that does that for you: http://jquery.malsup.com/form/