I have been googling for a couple of hours now, but I just can't figure it out. This is the script:
<script type="text/javascript">
$(document).ready(function(){
$('article').readmore({
maxHeight: 75,
speed: 300,
moreLink: 'Read more...',
lessLink: 'Read less...'
});
$('.plus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
$('.minus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
$("#infobox").click(function(){
$(this).hide();
});
});
$("#loader").hide();
var load = 0;
var nbr = "<?php echo $nbr; ?>";
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$("#loader").show();
load++;
if(load * 10 > nbr){
$("#messages").text("No more posts");
$("#loader").hide();
}
else{
$.post("php/newquery.php",{load:load},function(data){
$("#contentwrapper").append(data);
$("#loader").hide();
$('.plus-button').on("click", function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
alert("Liked");
}
});
});
$('.minus-button').on("click", function(){
var postid = $(this).data('postid');
$(this).siblings('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
alert("Disliked");
}
});
});
$('article').readmore({
maxHeight: 75,
speed: 300,
moreLink: 'Read more...',
lessLink: 'Read less...'
});
});
}
}
});
</script>
PS: Alerts are only used for troubleshooting.
The problem is that when the new items are loaded with the infinite scroll part of the script and I click the post items I get the alert "liked" or "disliked" twice each time I click either one of them. I do realize I have the script copied, but I need to have the script both inside and outside of the infinite scroll script for it to work. The article thing is just a read more plugin (also need this both inside and outside of infinite scroll). I have tried moving things around, but nothing seems to work. And to clarify: I only have problems after the new posts are loaded. The first posts outside infinite scroll works fine.
newquery.php
<?php
session_start();
require_once("connect.php");
require_once("config.php");
$load = htmlentities(strip_tags($_POST['load'])) * 10;
$query = mysqli_query($connect,"SELECT * FROM posts WHERE totalupvotes < $trendmin AND deleted=0 ORDER BY added DESC LIMIT " . $load . ",10");
while($row = mysqli_fetch_array($query)){
$postloopid = $row['id'];
echo '<div id="postlist">
<div style="width:400px; font-size:18px; font-weight:bold;">
<a target="_blank" href="post.php?id=' . $row['id'] . '">' . $row['title'] . '</a>
</div><br />
<article class="slide">' . nl2br($row['post']) . '</article>
<br />';
include("votebox.php");
echo '
<br />
by <a style="font-size:18px;" href="profile.php?id=' . $row['submittedby'] . '">' . $row['submitteduser'] . '</a>';
echo ' at <span style="font-size:12px;">' . $row['added'] . '</span><span style="float:right; margin-right: 10px;"><a target="_blank" href="post.php?id=' . $row['id'] . '#commentfield">' . $row['totalcomments'] . ' comments</a></span></div>';
}
?>
Votebox.php included in all the posts listed:
<?php
// If postid is from frontpage use $postloopid as $postid
if(isset($postloopid)){
$postid = $postloopid;
}
include("connect.php");
// If user logged in show votebox
if(isset($_SESSION['username'])){
$userid = $_SESSION['userid'];
$sql2 = mysqli_query($connect,"SELECT * FROM posts WHERE id='$postid' AND deleted=0");
if($sql2){
$voterow = mysqli_fetch_assoc($sql2);
$checkupvote = $voterow['upvoters'];
$checkdownvote = $voterow['downvoters'];
$checkupvote = explode(" ",$checkupvote);
$checkdownvote = explode(" ",$checkdownvote);
if($checkupvote = array_search($userid,$checkupvote) == true){
echo '<div class="voteboxwrapper">';
echo '<div class="plus-button liked" data-postid="' . $postid . '" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="' . $postid . '" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
echo $postid;
echo '</div>';
}
elseif($checkdownvote = array_search($userid,$checkdownvote) == true){
echo '<div class="voteboxwrapper">';
echo '<div class="plus-button" data-postid="' . $postid . '" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button disliked" data-postid="' . $postid . '" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
echo $postid;
echo '</div>';
}
else{
echo '<div class="voteboxwrapper">';
echo '<div class="plus-button" data-postid="' . $postid . '" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="' . $postid . '" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
echo $postid;
echo '</div>';
}
}
else {
echo 'No result <br />';
}
}
else {
echo 'Cant find user';
}
?>
Any ideas?
EDIT: Have tried .off() and .unbind() all ways I could think of. I still get the double and triple popups of "liked" and "disliked" (supposed to be only 1). Any ideas except unbind and off?
EDIT2: Updated all scripts with new suggestions. Still don't work.
Instead of doing $('.plus-button').click(... you want to use $('.plus-button').one('click', ... which, as the name suggests, binds once and only once!
see the official docs
Try moving $(window).scroll..... outside of document ready function
Related
I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
I have this script which is triggered when a button with the class .press_me is pressed.The buttons are on a column from a php generated mysql table:
$result = mysqli_query($con,"SELECT * FROM tbname");
echo "<table id='main'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='right-middle user'>" . $row['ID'] . "</td>";
echo "<td class='right-middle user'>" . $row['Nume'] . "</td>";
echo "<td class='right-middle done'>" . $row['Teme_facute'] . "</td>";
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me'>" ."</td>";
echo "<td class='right-middle undone'>" . $row['Teme_nefacute'] . "</td>";
echo "<td class='right-middle uncheck'>" . "<img src='img/uncheck.png'>" . "</td>";
echo "<td class='side-table resetDone'>" . "<img src='img/resetDone.png'>" . "</td>";
echo "<td class='side-table resetUndone'>" . "<img src='img/resetUndone.png'>" . "</td>";
echo "</tr>";
}
echo "</table>";
And the script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
And counter.php:
<?php
echo $_POST["id"];
if(!empty($_POST["id"]))
{
$id = $_POST["id"];
$connection=mysqli_connect("host","user","pass","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
mysqli_query($connection,"UPDATE tbname SET amount= (amount+ 1) WHERE ID = '" . $id . "'");
mysqli_close($connection);
echo 'OK';
}
else
{
echo 'NO ID PASSED';
}
?>
I'm having trouble updating only the value on the same row as the button pressed.When i run the page in this configuration counter.php returns no id passed and i think the problem is with the passing of the row id. Can anyone help me update only the value on the row with the pressed button?
I'm aware of sql injection but it's not the main problem now
Your id is empty
try this
echo "<td class='right-middle check'>" . "<img data-id='{$row['ID']}' src='img/check.png' class='press_me'>" ."</td>";
And in the script use this
var id=$(this).data("id");
change you javascript, looks like you are not sending data at all
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo json_decode('$row[ID]'); ?>;
var request = $.ajax({
type: "POST",
url: "counter.php",
// add this line
data: { id: id}
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
Replace below script:
<script>
$(function (){
$('.press_me').click(function(){
var id=<?php echo $row[ID]; ?>;
var request = $.ajax({
type: "POST",
url: "counter.php"
});
request.done(function( msg ) {
alert('Success');
location.reload();
return;
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
NOTE: I assume that you are working with single record. If not then it
will going wrong.
If this is working wrong then replace .press_me line with below:
$id = $row['ID'];
echo "<td class='right-middle check'>" . "<img src='img/check.png' class='press_me' id='<?php print($id);?>' >" ."</td>";
And script is like:
var id = $(this).attr("id");
Hope this help you well!
I am very new to using AJAX and passing data with json_encode. I have this "aht" button when clicked it will send an AJAX request to my show_aht.php script, which will run a query. I want to save the results and display it to my map.php.
Problem:
In my map.php I have a while loop that outputs square(desk) DIVs with another DIV(station) when clicked that displays content inside of it. Here is the fiddle so you may understand. I want the results of show_aht.php "TIME" to be displayed in the DIVs being produced by my WHILE LOOP in map.php.
How is it possible to do this? I know that AJAX and PHP cannot interact with eachother and thats why I need help. If this can't be done, how else can I display the TIME from show_aht.php to their corresponding usernames on each DIV being output? I have around 200 of them being displayed.
Thanks in advance.
map.php (only showing the last line of the while loop, outputs all DIVs)
//desk DIV
while(somequery){
....
echo '<div class="' . $class . '" data-rel="' . $id . '" style="left:' . $x_pos . 'px;top:' . $y_pos.'px;">' . $sta_num . '</div>' . "\n";
}//end while
//station DIV
while(some query){
.....
echo '<div class="station_info_" id="station_info_' . $id . '" style="left:' . $x_pos . 'px;top:' .$y_pos . 'px;"><p class="numb">User:' . $user .'<br>Station:' . $hostname . '<br>Pod:' . $sta_num . '<br>Section:' . $sec_name . '<br>State:' . $state .'<br></p></div>' . "\n";
}//end while
map.php (AJAX part)
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht.php (showing the loop and part I where I want the data to be returned)
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo "User: " . $m . " Time: N/A <br>";
}
}
}
Don't output anything except one valid json string. In your case you do that by replacing the echo's with building an array (or object...) and output that at the very end:
For example:
$data = array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$data[] = " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
$data[] = "User: " . $m . " Time: N/A <br>";
}
}
}
// Output your json string
echo json_encode($data);
Note that I have simply replaced your echos with an assignment but you could also add arrays in your array to return just the data parts and process that afterwards in javascript.
For example (this would depend a bit on your exact data structure...):
...
$data[] = array($m, $v['avg_handle_time']);
...
change show_aht.php to
$res=array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$res[]= " User: " .$m. " Time: " . $v['avg_handle_time'];
}
elseif( $v['memo_code'] != $m){
$res[]= "User: " . $m . " Time: N/A <br>";
}
}
}
echo json_encode($res);
and map.php ajax to
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
for(i=0;i<data.length;i++){
//append data[i] to div
}
}//end success
});//end ajax
});//end click
});//end rdy
I tried all the things but none of them are working.
Here is the code to call the lightbox_me:
$('#buynow').click(function(e) {
$('#pop').lightbox_me({
centered: true,
});
e.preventDefault();
});
And I am calling close function using a href link:
function close()
{
$('#pop').trigger('close');
}
I am sending ajax request to get the car product
$("#buynow").click(function() {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "displaycart.php",
data: '1',
cache: false,
success: function(result) {
$('#pop').html(result);
}
});
return false;
});
I am getting all the values from another file which contains html code
here is that code
while ($fetch_pro = mysql_fetch_array($pro)) {
$product = mysql_query("select * from product where id ='" . $fetch_pro['pro_id'] . "'");
while ($fetch_product = mysql_fetch_array($product)) {
echo '<tr><td class="padd_botton">';
echo '<img src = "images/product_images/'.$fetch_product['image'].'" height="60px" width="60px" >';
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
echo $fetch_product['product_name'].'<br> Remove ';
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
echo '<input class="textqua" id="qty'.$fetch_pro['id'].'" type="text" value="'.$fetch_pro['qua'].'" onchange="javascript:update('.$fetch_pro['id'].');" >';
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
echo 'Rs.'.$fetch_product['price'];
echo '</td><td class="padd_botton">';
echo '</td><td class="padd_botton">';
$total = $fetch_pro['qua'] * $fetch_product['price'];
echo '<span style="color:#6e8a02">Rs.'.$total.'</span>';
echo '</tr>';
$final_total = $total+$final_total;
}
}
I have a form with an id or 'display'. It has one value to send which is a select item that I gave an id of 'services' to.
I want to send the value of 'services' to a function I have created in a seperate php page. The page is called 'functs.php' and the function name is called 'searchResults'.
The 'searchResults' function works, this much I know. It queries a database and outputs 8 seperate php echo statements. I have ran the PHP function and know it works. I know the issues is with my javascript because, well, I am not the greatest at JavaScript and usually shy away from it.
As of right now, the code is not doing anything. My form has its own action to post to a seperate php page.
<form id="display" action="resultPage.php" method="POST">
I am trying to use the javascript/ajax to instantly update the contents of a div BUT if the user has jscript turned off, I want the form to ppost to the alternate page. Here is my jscript.
$(document).ready(function() {
$('#display').submit(function(e) {
var formData = $('#services');
$.ajax({
type: "POST",
url: functs.php,
data: '$formData',
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
e.preventDefault();
return false;
});
});
PHP CODE:
<?php
function searchResults()
{
require 'db_config.php';
$sql= "SQL CODE HERE"
$theStyle = <<<HERE
"height:100%;
width:70%;
margin:4% AUTO 0;
padding:1.75em;
font-size:1.25em;
border-radius:5em;
color:white;
background-color:#b72027;
;"
HERE;
while ($row = mysql_fetch_array($result))
{
echo ("<div style = $theStyle>");
echo ("<table>");
echo ("<tr><td>" . $row["0"] . "</td></tr>");
echo ("<tr><td>" . $row["1"] . "</td>");
echo ("<tr><td>" . $row["2"] . ", " . $row["3"] . " " . $row["4"] . "</td></tr>");
echo ("<tr><td>Phone: " . $row["5"] . "</td></tr>");
echo ("<tr><td>" . "" . $row["6"] . "" . "</td></tr>");
echo ("<tr><td>" . $row["8"] . " " . $row["9"] . ", " . $row["10"] . "</td></tr>");
echo ("<tr><td>" . $row["11"] . "</td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td>" . $row["7"] . "</td></tr>");
echo ("</table>");
echo ("</div>");
echo ("<br />");
}
}
?>
Your JS code has a couple of issues. The PHP script name needs to be a string inside of quotation marks, and the formData variable has an unnecessary "$." Try this:
$(document).ready(function() {
$('#display').submit(function(e) {
e.preventDefault();
var formData = $('#display').serialize();
$.ajax({
type: "POST",
url: 'functs.php',
data: formData,
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
});
});