I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';
Related
I want to create async AJAX query to check server status when web page finish loading. Unfortunately when it comes to data display from processed PHP, I receive only single value.
JS:
<script>
window.onload = function() {
test();
};
function test()
{
var h = [];
$(".hash td").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('.result').replaceWith(data);
}
});
}
});
}
</script>
PHP:
<?php
require_once ('inc/config.php');
require_once ('inc/libs/functions.php');
if (isset($_POST['hs'])) {
$hash = json_decode($_POST['hs']);
serverstatus($hash);
}
function serverstatus($hash) {
$address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);
$address_exploded = explode(":", $address['address']);
$ip = $address_exploded[0];
$port = $address_exploded[1];
$status = isServerOnline($ip,$port);
if ($status) {
$s = "Online $ip";
} else {
$s = "Offline";
}
echo $s;
}
?>
I embed result from PHP to a table row. I see that AJAX iterating over the array, but all rows receive same value (last checked element in array).
$('.result') matches all elements with the class result. replaceWith will then replace each of them with the content you provide.
If you want to only affect the .result element within some structure (perhaps the same row?), you need to use find or similar:
function test()
{
var h = [];
$(".hash td").each(function(){
var td = $(this); // <====
var hash = td.closest('#h').text();
var result = td.closest("tr").find(".result"); // <====
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
result.replaceWith(data); // <====
}
});
}
});
}
Obviously the
var result = td.closest("tr").find(".result"); // <====
...will need to be tweaked to be what you really want it to be, but that's the idea.
This line in your question suggests an anti-pattern:
var hash = $(this).closest('#h').text();
id values must be unique in the document, so you should never need to find the one "closest" to any given element. If you have more than one id="h" element in the DOM, change it to use a class or data-* attribute instead.
Thank you all for help. My final, obviously very dirty but working code:
function testServerPage()
{
var h = [];
$(".hash li").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
//async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('#' + hash).replaceWith(data);
}
});
}
});
return false;
}
I just added dynamic variable to element:
success: function(data) {
$('#' + hash).replaceWith(data);
}
When the user hovers over an image an information box comes up about that image, the information them changes inside the box as I move over another image but when I am over no images the information box stays. I can't close the information box (i.e. tooltips).
JS :
var id;
$(document).ready(function () {
$('a').mouseenter(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
});
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
});
How can I get the information box to disappear on mouse out?
I have tried multiple tests but the box doesn't even appear with them, the last one I tried is in the code above.
$('a').onmouseleave(function () {
id = $(this).data.display = 'none';
}
I am only starting out with javascript, jquery etc. in the last year.
Thank you in advance!!
Here is the php.
<div class="thumbnails">
<?php
$query = mysqli_query($connection, "select * from portfolio");
print "<ul>";
while ($row = mysqli_fetch_assoc($query)) {print "<li><img onClick=preview.src=" . $row['image'] . "name=" . $row['folio_id'] . "src={$row['image']}></td></li>";
}
print "</ul>";
?>
</div>
<!--Folio Information-->
<div id="fillFolio">Project Information</div>
I'm not sure, but try to use :
$('a').onmouseleave(function () {
$("#fillFolio").empty();
}
Hope this helps.
$("a").hover(function(){
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
}, function(){
//im not sure u want to hide or want to just clear your question not clear
$("#fillFolio").empty();
$("#fillFolio").hide();
});
Why not use jQuery hover = (mouseenter + mouseleave)
<script type="text/javascript">
var id;
$(document).ready(function () {
$('a').hover(function () {
//var id = $(this).parent().attr('myval');
id = $(this).data('myval');
$.ajax({//create an ajax request to foliobase.php
type: "GET",
//link to the foliobase.php file "?subj" here is the connector
url: "foliobase.php?subj=" + id,
dataType: "html",
success: function (response) {
$("#fillFolio").html(response);
}
});
,function () {
id = $(this).empty();
});
</script>
I have a notification functionality, and it updates in the table when read/viewed.
What i have is a list of li of the notifications & when the button was clicked it calls the ajax function to mark it as read, however my problem is how can I update the counter in the page since it count only for the notifications that wasn't read yet.
my js code is here:
<script type="text/javascript">
$(function() {
$(".confirm").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
var closest_li = $(this).closest('li');
$.ajax({
type: "POST",
url: "mark_read.php",
data: dataString,
cache: false,
beforeSend: function() {
closest_li.animate({'backgroundColor':'#fb6c6c'},300).animate({ opacity: 0.35 }, "fast");;
},
success: function() {
closest_li.slideUp('fast', function() {$(this).remove();});
}
});
return false;
});
});
And here is the file content of the mark_read.php
<?php
if(isset($_POST['id'])) {
$id = $_POST['id'];
$id = mysqli_real_escape_string( connect(), $id );
$result = query("UPDATE tbl_notifications SET log_stat='1' WHERE log_id='$id'");
}
?>
and my counter is a label that echoes the php sql query of count num rows.
I have this JavaScript function in the header of my site. On first page load everything works as expected, i get the response back onsuccess is fired and it updates the div tag specified.
I use var reqid = "<?= $_GET['id']; ?>"; to get the id of the page.
When i navigate through my app and load the same page but with a different id in the url string var reqid = "<?= $_GET['id']; ?>"; does not update and reverts to the previous value. how can i get this to update every time the page is shown?
var request = function() {
function onSuccess(data, status)
{
$("#notif").fadeIn(2000);
data = $.trim(data);
if(data == "SUCCESS"){
$("#notif").html('<div class="notification-box-green"> <img class="notification-icon" src="images/lists/list-tick.png" alt=""> <p class="notification-text">Success!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
});
} else if(data == "LIMIT")
{
$("#notif").html('<div class="notification-box-yellow"><img class="notification-icon" src="images/lists/list-warning.png" alt=""><p class="notification-text">Please Wait!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
});
} else if(data == "NO_WIFI")
{
$("#notif").html('<div class="notification-box-yellow"><img class="notification-icon" src="images/lists/list-warning.png" alt=""><p class="notification-text">Connect to hostspot!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
});
}
}
var reqid = "<?= $_GET['id']; ?>";
$.ajax({
type: "POST",
url: "req_sub.php",
cache: false,
data: "id="+ reqid,
success: onSuccess
});
}
The function is called with a button click.
EDIT
I modified my code slightly and placed it into its own js file.
the id now seems to update as expected.
one problem still remains, the code in onsuccess doesnt execute second time round. first load or on a refresh the div changes as expected, navigation back to the page with a different id in the url doesnt update the div.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var request = function() {
var reqid = getUrlVars()["id"];
function onSuccess(data, status)
{
Edit 2
I cloned the div and replaced it when i was done.
var divClone = $("#notif").clone();
var request = function() {
var reqid = getUrlVars()["id"];
function onSuccess(data, status)
{
$("#notif").fadeIn(2000);
data = $.trim(data);
if(data == "SUCCESS"){
$("#notif").html('<div class="notification-box-green"> <img class="notification-icon" src="images/lists/list-tick.png" alt=""> <p
class="notification-text">Success!</p></div>').fadeIn(4000);
$('#notif').fadeOut(4000, function() {
$("#notif").replaceWith(divClone);
Doubt this has been the proper way to achieve my goal, will further test after sleep and update with results.
I'm a pretty new programmer who made an application that sends out a heartbeat every 3 seconds to a php page and returns a value, the value of which decides which form elements to display. I've been fairly pleased with the results, but I'd like to have my jquery as fast and efficient as possible (its a little slow at the moment). I was pretty sure SO would already have some helpful answers on speeding up heartbeats, but I searched and couldn't find any.
So here's my code (just the jquery, but I can post the php and html if needed, as well as anything anyone needs to help):
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'POST',
contentType: "application/json",
cache: true,
data: { "dataid": dataid },
success: function(data){
var msg = $.parseJSON(data);
if (msg == ""){ //after reset or after new patient that is untouched is added, show checkin
$e.find('.checkIn').show();
$e.find('.locationSelect').hide();
$e.find('.finished').hide();
$e.find('.reset').hide();
}
if ((msg < 999) && (msg > 0)){ // after hitting "Check In", Checkin button is hidden, and locationSelect is shown
$e.find('.checkIn').hide();
$e.find('.locationSelect').show();
$e.find('.finished').hide();
$e.find('.reset').hide();
$e.find('.locationSelect').val(msg);
}
if (msg == 1000){ //after hitting "Checkout", Option to reset is shown and "Finished!"
$e.find('.checkIn').hide();
$e.find('.locationSelect').hide();
$e.find('.finished').show();
$e.find('.reset').show();
}
}
});
});
},3000);
$('.checkIn').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "checkin.php",
// Data used to set the values in Database
data: { "checkIn" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.locationSelect').show();
$container.find('.locationSelect').val(1);
}
});
});
$('.reset').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "reset.php",
// Data used to set the values in Database
data: { "reset" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.checkIn').show();
}
});
});
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
$e = $(this);
var data = $e.data("param").split('_')[1] ;
$.ajax({
type: "POST",
url: "checkout.php",
// Data used to set the values in Database
data: { "checkOut" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.finished').show();
$container.find('reset').show();
}
});
}
else{
$e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of select (1 for the first select)
// You can map this to the corresponding select in database...
$.ajax({
type: "POST",
url: "changeloc.php",
data: { "locationSelect" : $(this).val(), "selectid" : data},
success: function() {
// Do something here
}
});
}
});
});
</script>
Thanks for all and any help! Please just ask if you need any more details! Thanks!
Alot of factors could be causing slowness. Some things to consider:
The speed of the heartbeat is not dependent on your client-side javascript code alone. There may be issues with your server-side php code.
Also, a heartbeat every three seconds is very frequent, perhaps too frequent. Check in your browser's developer debug tools that each of the requests is in fact returning a response before the next 3 second interval. It could be that your server is slow to respond and your requests are "banking up".
You could speed your your jQuery a fraction by streamlining your DOM manipulation, eg:
if (msg == "")
{
$e.find('.checkIn').show();
$e.find('.locationSelect, .finished, .reset').hide();
}