I have been working on Like and Unlike feature with jquery, ajax and php. My problem is little bit difficult to understand. Lets try to understand it first.
I have 2 php pages, viewProfile.php and LikeMail.php. LikeMail.php is being called by ajax function in viewProfile.php.
Here is Section of viewProfile.php page's description
-----------------
| Like/Unlike |
-----------------
Here is button which actually comes from LikeMail.php by this ajax function
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('Like').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
HTML:
<div id="Like"></div>
Output is being shown here in this div. Button above may be Like or Unlike depends on the condition in LikeMail.php which will be described below in LikeMail.php description section.
When one of them (buttons) Like or Unlike is clicked. It then calls respective jquery click function which sends post request to LikeMail.php.I have mentioned Indirect page in title because Like or Unlike buttons actually exists in LikeMail.php page. But due to ajax call these buttons are being shown in viewProfile.php page. So I then send post requests through viewProfile.php to actual page LikeMail.phpIt is jquery post for Unlike button
$(document).ready(function(){
$('#Unlike').unbind().click(function(){
$.post("LikeMail.php",
{Unlike: this.id},
function(data){
$('#response').html(data);
}
);
});
});
It is jquery post or Like button
$(document).ready(function(){
$('#Like').unbind().click(function(){
$.post("LikeMail.php",
{Like: this.id},
function(data){
$('#response').html(data);
}
);
});
});
End of description section of viewProfile.php page
Here is Section of LikeMail.php page's description
Like or Unlike button is shown in viewProfile.php page depends upon this code:
$check_for_likes = mysqli_query($conn, "SELECT * FROM liked WHERE user1='$user1' AND user2='$user2'");
$numrows_likes = mysqli_num_rows($check_for_likes);
if (false == $numrows_likes) {
echo mysqli_error($conn);
}
if ($numrows_likes >= 1) {
echo '<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">';
}
elseif ($numrows_likes == 0) {
echo '<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">';
}
Button depends upon these two above conditions.
Now when Like button is clicked, post request from viewProfile.php comes here
if(isset($_POST['Like'])) //When Like button in viewProfile.php is clicked then this peace of code inside if condition should run and insert some record in database
{
$total_likes = $total_likes+1;
$like = mysqli_query($conn, "UPDATE user SET user_Likes = '$total_likes' WHERE user_id = '$user2'");
$user_likes = mysqli_query($conn, "INSERT INTO liked (user1,user2) VALUES ('$user1','$user2')");
$query3 = "INSERT INTO notification (user1, user2, alert, notificationType) VALUE ('$user1','$user2','unchecked','like')";
if (mysqli_query($conn, $query3)) {
echo "Like";
} else {
echo mysqli_error($conn);
}
}
Similarly when Unlike button is clicked. This peace of code should run.
if(isset($_POST['Unlike'])) //This is the condition for Unlike button. It should delete record from databse
{
$total_likes = $total_likes-2;
$like = mysqli_query($conn, "UPDATE user SET user_Likes='$total_likes' WHERE user_id='$user2'");
$remove_user = mysqli_query($conn, "DELETE FROM liked WHERE user1='$user1' AND user2='$user2'");
$query3 = "DELETE FROM notification WHERE user1='$user1' AND user2='$user2' AND notificationType='like'";
$check = mysqli_query($conn, $query3);
if ($check) {
echo "Unlike";
} else {
echo mysqli_error($conn);
}
}
Problem:
Main problem which I faced is that when I click Like or Unlike both executes the condition of Like button code. Both inserts the data into database as Unlike condition should delete data from database but it also inserts data as condition for Like button do. Kindly can you please help me that how to tackle this problem. Thanks in advance!
Update:When I delete all the respective code for Like button. The condition for Unlike button starts working correctly.
I think there's a duplicated ID somewhere, perhaps the DIV. Take a look at this.
<div id="Like_2"></div>
<input type="submit" name="Unlike" value="Unlike" id="Unlike" class="btn btn-lg btn-info edit">
<input type="submit" name="Like" value="Like" id="Like" class="btn btn-lg btn-info edit">
<div id="response"></div>
$(document).ready(function(){
$(document).on('click','#Unlike', function(){
$('#response').html(this.id);
//ajax call
});
$(document).on('click','#Like', function(){
$('#response').html(this.id);
//ajax call
});
});
And the javascript function:
function like()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState==4 && req.status==200)
{
document.getElementById('Like_2').innerHTML=req.responseText;
}
}
req.open('POST','LikeMail.php','true');
req.send();
}
setInterval(function(){like()},1000);
https://jsfiddle.net/wx38rz5L/2103/
Related
I have a table displaying data from a database, buttons with javascript that update the sql and display the result on the table, till here all good, my problem is I want to put more buttons with different SQL queries, this only check the value="" of the button and use it as $var on the final SQL
Note that I mark the buttons id as btn_01, btn_02..
function load_data(query) {
$.ajax({
url:"fetch",
method:"POST",
data:{query:query},
success:function(data) {
$('#result').html(data);
}
});
}
var names = new Array('Italy','Denmark','France','UK');
$(".btn").bind("click",function(e) {
var btn = this.id.split('_');
var data=( show_mssg(btn[1]) );
load_data(data);
});
function show_mssg(id) {
return names[id];
}
here is the "fetch" file, is a php file to conned to db
$connect = mysqli_connect("dbhost","dbname","user","pass");
$output = '';
if(isset($_POST["query"])) {
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "SELECT * FROM `Developers` WHERE `country` LIKE '%".$search."%' ";
}
$result = mysqli_query($connect, $query);
if ($result) {
$output='<table></table>';
}
echo "$output";
and the html buttons
<span id='btn_0' class="btn" value='Italy'>Italy</span>
<span id='btn_1' class="btn" value='Denmark'>Denmark</span>
<span id='btn_2' class="btn" value='France'>France</span>
<span id='btn_3' class="btn" value='UK'>UK</span>
finally to display the result
<div id="result"></div>
I tried to make similar function with a different array for different buttons but seems like is not working, also i tried with
if(isset($_POST["query"]))
to not necessary make another function and later try to bind the click on different buttons and just change the sql.
This is a toggle of a ‘follow-unfollow’ button of a Twitter like following system. When the button has the class unfollow it takes two clicks to trigger to fire. When the button has the class follow it fires in one click. This is related to the if statement. If the script does not need to run through the if statement it fires well on one click which is the part of the else section of the script. It is worth noting, that when two clicks are needed, if there is no refresh in the page, you then can toggle back and forth with just one click as it is supposed to be. Do you know how can I avoid using two clicks when the script needs to go through the if statement?
Thanks in advance.
<button class="followUnfollow" id="boton<?php echo $member->id; ?>" type="button" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>"> <?php echo $status; ?> </button>
<script>
$(document).ready(function() {
$("#boton<?php echo $member->id; ?>").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
if($("#boton<?php echo $member->id; ?>").hasClass('unfollow')) { // TWO CLICKS TO FIRE
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
} else { // WORKS WELL, ONE CLICK TO FIRE
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
}
});
});
</script>
I am currently working on a multi-user privat chat-system (pretty similar to the Facebook chat). There is a sidebar with all users and when I click on a user a chat window gets dynamically generated by JavaScript.
The chat window contains a .chat-container with all messages between the selcted user and the logged in user.
The .chat-container has to get updated like every 3 seconds with AJAX, but for some reason I am unable to make it work!
My current try is the following:
Every user-element in the sidebar has a hidden form .chat-ident-form inside it. The form has two inputs "to_user" and "from_user", which values get populated with PHP:
<div class="sidebar-name">
<form class="chat-ident-form" action="./src/assets/widgets/chat-widget/get-messages.php" method="post" onclick="submit_ident_form_via_ajax();">
<a href="javascript:register_popup('<?php echo $member['username'] ?>', '<?php echo $member['username'] ?>');">
<img class="img-circle chat-sidebar-user-avatar" src="<?php echo $member["avatar"]; ?>" />
<span><?php echo $member['username'] ?></span>
</a>
<input type="hidden" name="to_user" value="<?php echo $member['username'] ?>">
<input type="hidden" name="from_user" value="<?php echo $_SESSION['username'] ?>">
</form>
</div>
When the user clicks on a user-element in the sidebar a chat window opens up (which is working!) and then the trouble begins!
I then want to submit the hidden .chat-ident-form to a PHP-Script (at ./src/assets/widgets/chat-widget/get-messages.php) via AJAX. I currently trigger the AJAX with onclick, when the user clicks on the user-element in the sidebar.
The PHP-Script then gathers the massages between the users from the database and echos them as HTML-Code, which I then want to retrieve again via AJAX to display it in the .chat-container.
First things first, the PHP-Script is working. When it gets the neccessary $_POST-Variables it produces the HTML for the messages:
if (isset($_POST["from_user"]) && isset($_POST["to_user"])) {
try {
$from_user = $_POST["chat_user"];
$to_user = $_POST["chat_target_user"];
$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";
$statement = $db->prepare($query);
$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));
$to_messages = $statement->fetchAll(PDO::FETCH_ASSOC);
$from_user = $_POST["chat_target_user"];
$to_user = $_POST["chat_user"];
$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";
$statement = $db->prepare($query);
$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));
$from_messages = $statement->fetchAll(PDO::FETCH_ASSOC);
$all_messages = array_merge($to_messages, $from_messages);
usort($all_messages, "sortFunction");
$html_messages = "";
foreach ($all_messages AS $message) {
if ($message["from_user"] == $to_user) {
$html_messages .= "<div class='chat-massage-container'><div class='chat-massage-a'>". $message["message"] ."</div></div>";
} else {
$html_messages .= "<div class='chat-massage-container'><div class='chat-massage-b'>". $message["message"] ."</div></div>";
}
}
echo $html_messages;
} catch (PDOException $ex) {
echo "An error occured!";
}
}
Sadly the PHP-Skript does not receive the neccessary $_POST-Variables. So there has to be something wrong with the AJAX submitting the .chat-ident-form. It looks like this:
function submit_ident_form_via_ajax () {
$(this).ajaxSubmit(function() {
getMessages();
});
setTimeout(submit_ident_form_via_ajax, 3000);
}
function getMessages () {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
document.getElementsByClassName('.chat-container').innerHTML = request.responseText;
}
};
request.open('GET', './src/assets/widgets/chat-widget/get-messages.php', true);
request.send();
}
Notice that I am using the jQuery Form Plugin for the AJAX. When the submission returns success the getMessages() function is called, which retrieves the HTML from the PHP-Script and displays it in the .chat-container. Well at least in theory it does. In reality, nothing happens. So the form is not submitted by the AJAX and the HTML is neither retrieved from the PHP-Script nor displayed in the .chat-container.
I am pretty new to AJAX and I am completely lost here! What would be the right AJAX to send the .chat-ident-form to the PHP-Script? (Can be with JS, jQuery or jQuery Form Plugin... idc) How should I trigger the submission of the .chat-ident-form? Via onclick - as I currently do - or is there a better way?
And then there is also the question: How do I retrieve the HTML echoed by the PHP-Script and display it in the dynamically generated .chat-container? What is the correct AJAX to do that? When does this happen? Does it happen with the submission or does it happen seperatly? How does it get triggered?
So I need to know two things from you guys:
The right AJAX to send the hidden .chat-ident-form and how to trigger it.
The right AJAX to get the HTML echoed in the PHP-Skript and display it in the dynamically generated .chat-container and also when to do this.
Overall I am just confused and my brain hurts after several hours of thinking about it!!! Maybe there is a much easier way, but I dont see it right now. Or maybe my whole thought process is flawed... =/
Anyways, I tried to explain my problems as well as I could. If anything is missing feel free to ask and please have some mercy (this is my first ever question at StackOverflow).
I would be really happy, if anyone has a solution. =)
I have built a follow/unfollow Twitter like system using PHP. With help of this forum I have been successful creating a dynamic button that allows you to “follow” or “unfollow” each user, using AJAX/JQUERY to run the PHP/MySQL code in the back and avoid refreshing the page when the action happens. The thing is that I am able to run this script on the background only once. Let’s say a user unfollows a member by mistake (my AJAX/JQUERY script won’t have any problem with that), but then wants to follow him again, this is where I am stuck. The page will have to be refresh to make this happen. I know this is happening due to the PHP dynamic data that I am using as you will see in my code.
In the PHP code am running an iteration that output all the members in the database. I am outputting here (for simplicity) just the member’s name and a follow/unfollow button to each one. The php variable $what_class is the result of a PHP function that looks into the database to determine if the user is following or not that member. $what_class will output the strings “follow” of “unfollow” so the class can be defined, and then be targeted by either of the two the Jquery scripts.
PHP CODE
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<button class="<?php echo $what_class; ?>" type="button" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" ><?php echo $what_class; ?></button>
<?php } ?>
Below is the JQUERY scripts, as mentioned before, the button class will be defined by PHP through $what_class. This is the problem when trying to re-use the button after the first time, class won´t change in PHP’s $what_class unless the page is refreshed. I tried to use $(this).removeClass('unfollow').addClass('follow') to change the class using Jquery and have the button to be re-usable but it isn’t working.
JQUERY SCRIPTS TO FOLLOW OF UNFOLLOW
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("button.follow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
});
});
</script>
Does anyone knows how I accomplish having a reusable button without reloading the page? I thank you in advance.
Previous Answer:
What I do for that kind of scenario is to have two buttons. One will be shown to the user, and the other one will be hidden.
<button class="follow" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Follow</button>
<button class="unfollow" style="display:none" data-member_id="<?php echo $member->id; ?>" user_id="<?php echo $id;?>" >Unfollow</button>
Just tweak your php code what to show and what not.
When a button is click, hide this button and show the other one.
$(document).ready(function(){
$(".follow").on("click", function(){
$(".follow").hide(200);
$(".unfollow").show(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
$(".unfollow").on("click", function(){
$(".follow").show(200);
$(".unfollow").hide(200);
/* PUT YOUR OTHER PROCESSES HERE */
});
});
Check this JSfiddle.
Update:
We can use toggleClass() of jQuery.
<button class="follow" data-member_id="12" user_id="12">Follow</button>
And the script:
$(document).ready(function(){
$(".follow, .unfollow").on("click", function(){
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
$(".follow, .unfollow").toggleClass("follow unfollow");
$(this).text(function(i, text){
return text === "Follow" ? "Following" : "Follow";
});
});
});
Check this JSfiddle.
use <button class="followUnfollow <?php echo $what_class; ?>"
You need to write as less code as possible. Have a common class such as followUnfollow and then check if follow class exists within this element using hasClass function from jQuery.
Have a look at the code below.
<script type="text/javascript">
$(document).ready(function() {
$("button.followUnfollow").on('click', function() {
var memberId = $(this).attr('data-member_id');
var userId = $(this).attr('user_id');
if($(this).hasClass('follow')) { // FOLLOW
$.get("follow_actions.php", {follow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('unfollow');
$(this).removeClass('follow').addClass('unfollow');
} else { // UNFOLLOW
$.get("follow_actions.php", {unfollow_id:memberId, user_id:userId} , function(data) {
});
$(this).html('follow');
$(this).removeClass('unfollow').addClass('follow');
}
});
});
</script>
In table (that contains records, customers credentials, from my db) I have a delete button for each row.
I want that if I click on the delete button, this will delete the row, passing the ID of the record to the deletecustomer.php
When I click on the delete button, I have a ajax modal that ask if you want to confirm the action or not.
The problem is that if I click on CONFIRM (in the modal), my modal will go in delete-utente.php (where I have the query for the delete of the row) but the ID isn't passed.
In delete-utente.php I have a message if the query it's ok (delete complete), and another message if the delete can't be done.
After I click confirm I always have the OK message, but the customer has not been deleted.
I guess that the problem is not the deletecustomer.php because if I use a simple javascript alert, the query it's ok and I pass the identifier successful, but with the ajax modal, the identifier is not passed.
It's the first time that I use ajax, so I think that the problem it's ajax code.
code of the table in my main page (newcustomer.php)
<table class="simple-table responsive-table" method="POST" id="customer-list">
//code thead
//rows rows..
<?php echo '<button type="input" class="button icon-trash with-tooltip confirm" onclick="openConfirm()" href="deletecustomer.php?customerid='.$idcustomer.'" title="Delete"></button>'; ?>
//....
</table>
ajax modal
function openConfirm()
{
$.modal.confirm('Sicuri di voler cancellare il cliente?', function()
{
window.location.href = "deletecustomer.php"; //the php file where I have the delete query
}, function()
{
window.location.href = "newcustomer.php";
});
};
and I take the values in my deletecustomer.php like this
$customeridd=(int) $_GET['customerid'];
Sorry if is a stupid mistake or a stupid question ^^"
And thank in advice
You can use like this :
<?php
echo '<button type="input" class="button icon-trash with-tooltip confirm" onclick="openConfirm('.$idcustomer.')" href="deletecustomer.php?customerid='.$idcustomer.'" title="Delete">button</button>';
?>
And
function openConfirm(id)
{
alert(id);
$.modal.confirm('Sicuri di voler cancellare il cliente?', function()
{
window.location.href = "deletecustomer.php?customerid="+id; //the php file where I have the delete query
}, function()
{
window.location.href = "newcustomer.php";
});
};
Try the following code:
<?php echo '<a class="button icon-trash with-tooltip confirm" onclick="return confirm(\'Are you sure?\');" href="deletecustomer.php?customerid='.$idcustomer.'">Delete</a>'; ?>