PHP not displaying server results online - php

We have built this online prototype and it worked just perfectly on our local environment, but after moving it online, some buttons and a table are not working. The buttons are all buttons that, have conditions to only show if eg. the user is logged in or has a certain user type (in this case a tutor). The table is not showing the search results.
It's possible to register a user and also login, but when entering the subpages, only logout, search button and logo is responding. And we can see that user are being saved in our database.
Can anyone give a hint to what it is we do wrong? I've displayed one of the buttons code here below.
HTML:
<ul>
<li><a class="modal-button modal-button-user" data-modal="modalEditUser"><i class="far fa-user"></i> Hello <?php echo $_SESSION["firstName"];?>!</a></li>
<li>
<form action='_home.php' method='post'><button class="logout_button" type="submit" name="logOutBtn" id="logOutBtn">Log Out</button></form>
</li>
</ul>
JS:
var modalBtns = [...document.querySelectorAll(".modal-button")];
modalBtns.forEach(function(btn){
btn.onclick = function() {
var modal = btn.getAttribute('data-modal');
document.getElementById(modal).style.display = "block"
}
});
var modalBtnsTutor = [...document.querySelectorAll(".modal-button-tutor")];
modalBtnsTutor.forEach(function(btn){
btn.onclick = function() {
var modal = btn.getAttribute('data-modal');
document.getElementById(modal).style.display = "block"
}
});
var closeBtns = [...document.querySelectorAll(".close")];
closeBtns.forEach(function(btn){
btn.onclick = function() {
var modal = btn.closest('.modal');
modal.style.display = "none";
}
});
window.onclick = function(event) {
if (event.target.className === "modal") {
event.target.style.display = "none";
}
}
PHP:
<?php
require 'config.php';
//try to make logout/login/welcomeMessage appear/disappear whether you're
logged in or not
if (isset($_SESSION["userID"])) {
echo "<script>
window.onload = function() {
document.getElementById('navUser').style.display = 'block';};
</script>";
$go = "home.php";
} else {
echo "<script>
window.onload = function() {
document.getElementById('navVisit').style.display = 'block';};
</script>";
$go = "index.php";
}
?>

Related

How to get the href click event to work with a variable?

I am working on jquery to click on the mail folder href links for my emails so I could do something. But I have got a problem with clicking on the href links because when I click on the href links, nothing will happens.
When I try this:
$(document).on('click', 'a[href^=#'+folder+']', function(e) {
alert("Now you are working on mailfolder");
});
Here is the PHP:
$folders_list = imap_listmailbox($mailbox, $mailserver, "*");
$folders_arr = array();
$key = array();
sort($folders_list);
if (is_array($folders_list)) {
unset($folders_list[0]);
$imp = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Archive.Important';
$trash = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Trash';
$sent = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Sent';
$draft = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Drafts';
$archive = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Archive';
$junk = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Junk';
$spam = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.spam';
$key1 = array_search($imp, $folders_list);
$key2 = array_search($trash, $folders_list);
$key3 = array_search($sent, $folders_list);
$key4 = array_search($draft, $folders_list);
$key5 = array_search($archive, $folders_list);
$key6 = array_search($junk, $folders_list);
$key7 = array_search($spam, $folders_list);
$key = [$key1, $key2, $key3, $key4, $key5, $key6, $key7];
sort($key);
foreach ($key as $val) {
unset($folders_list[$val]);
}
foreach ($folders_list as $mailbox_name) {
$mailbox_name = str_replace("{imap.example.com:993/imap/ssl/novalidate-cert}", "", $mailbox_name);
$mailbox_name = str_replace("INBOX.", "", $mailbox_name);
$folders_arr[] = $mailbox_name;
}
}
sort($folders_arr);
<ul class="folder-nav inbox-divider">
<li> <h4>Folders</h4></li>
<?php
foreach ($folders_arr as $folders) {
?>
<div style="width: 100%;">
<li>
<i style="margin-left: -7px;" class="folder_icon"></i><span style="margin-left: 7px;"> <?php echo $folders;?></span>
</li>
</div>
<?php
}
?>
</ul>
Here is the jquery:
var hash = window.location.hash;
var folder = hash.split('/')[0].replace('#', '');
$(document).on('click', 'a[href^=#'+folder+']', function(e) {
e.preventDefault();
start_idx = 0;
alert("Now you are working on mailfolder");
if ($("#movetoFolder").css('display') == 'block') {
$('#movetoFolder').hide();
}
if (openMail == true) {
openMail = false;
}
if(window.location.hash == '#'+folder) {
$("#click_nav_prev").addClass("disabled");
$("#click_nav_next").removeClass("disabled");
loadEmailBodyContent = false;
$(".bottom_space").show();
$(".emailMessages").hide();
$(".emailBodyShowUp").hide();
$("#opt_refresh").show();
$('.tbody_maillist').show();
mailfolder();
}
else
{
mailfolder();
}
});
I have already tried this:
$(document).on('click', '.mailfolder', function(e) {
....etc
});
It works fine, but it wont add the folder name in the url like http://example.com/#foldername when I click on the href links.
What I am trying to do is I want to get the href click event to work for any folder that I click on the a tag using with the variable so I can work on the code to fetch the data from the mail folders.
Can you please show me an example how I can get the href click event to work with the variable called folder?
Thank you.
I think you want something like this:
$(".mailfolder").on('click', function(e) {
e.preventDefault();
var folder = $(this).attr("href");
start_idx = 0;
alert("Now you are working on mailfolder");
if ($("#movetoFolder").css('display') == 'block') {
$('#movetoFolder').hide();
}
if (openMail == true) {
openMail = false;
}
if (window.location.hash == folder) {
$("#click_nav_prev").addClass("disabled");
$("#click_nav_next").removeClass("disabled");
loadEmailBodyContent = false;
$(".bottom_space").show();
$(".emailMessages").hide();
$(".emailBodyShowUp").hide();
$("#opt_refresh").show();
$('.tbody_maillist').show();
mailfolder();
} else {
mailfolder();
}
});
If you use a variable in an event delegation selector, the variable is expanded at the time you create the delegation, not every time the event occurs. So you can't have the delegation check automatically whether the link matches the current hash.
Another way you could do this is with a hashchange event handler. It could add a class to the link that matches the new hash, and remove the class from other links, and you can delegate to that class. Like this:
$(window).on("hashchange", function() {
$(".mailfolder").removeClass("current");
$(`.mailfolder[href=${window.location.hash}]`).addClass("current");
});
// Special code just for current folder
$(document).on('click', ".mailfolder.current", function(e) {
$("#click_nav_prev").addClass("disabled");
$("#click_nav_next").removeClass("disabled");
loadEmailBodyContent = false;
$(".bottom_space").show();
$(".emailMessages").hide();
$(".emailBodyShowUp").hide();
$("#opt_refresh").show();
$('.tbody_maillist').show();
});
// Common code for all mail folder links
$(".mailfolder").on("click", function() {
e.preventDefault();
var folder = $(this).attr("href");
start_idx = 0;
alert("Now you are working on mailfolder");
if ($("#movetoFolder").css('display') == 'block') {
$('#movetoFolder').hide();
}
if (openMail == true) {
openMail = false;
}
window.location.hash = $(this).attr("href");
mailfolder();
});

when i add new comment the delete button doesn't work till i reload the page?

first page
ajax and jquery code
<script>
$(document).ready(function(){
$(".delete_buttom").click(function(){
var x = $(this).attr('id');
click_delete(x);
});
function click_delete(commentId){
$.post("ajax_comments3.php",
{
task : "this is the task",
commentId : commentId
}).success(
function(data){
$('#comment_' + commentId).remove();
}).error(function(){
alert("404 not found");
});
}
</script>
======================================================================
second page code
<?php
if(isset($_POST['task']) && $_POST['task'] == "this is the task"){
$server_id = $_POST['ajax_id'];
$server_comment = $_POST['ajax_text'];
$user_name = $_POST['ajax_uname'];
$connection = mysqli_connect("localhost","root","","comments")
$insert_query = "insert into comment (commet_text,user_id)
values ('$server_comment','$server_id')";
$excute_insert = mysqli_query($connection,$insert_query) or die("insert query error");
?>
this the the li tage which will insert into ul tage (i have a ul tage in html code)
<li class="li_style" id="comment_<?php echo mysqli_insert_id($connection) ?>">
<img src="profile.jpg" class="user_img_src" />
<h5 class="username"><?php echo $user_name ; ?></h5>
<div class="delete_buttom" id="comment_<?php echo mysqli_insert_id($connection) ?>">X</div>
<div class="user_comment"><?php echo $server_comment ; ?> </div>
</li>
<?php
}
?>
when i type a new comment it inserted into database and appear in the web browser as well but the problem is that i have a delete button when i clicked on it right after typing comment it doesn't work i have to reload the page the the delete button works fine any solutions.
Correct. That is because theres no event on that new button.
Maybe like this:
var deleteButton = function() {
$(".delete_buttom").off('click');
$(".delete_buttom").on('click', function() {
var x = $(this).attr('id');
click_delete(x);
});
}
Now, in your success (after you added the new entry):
success(function(data) {
// add your entry...
deleteButton();
});

cannot click items echoed by another page using ajax - $(document).on is not working

updated
i'm having 2 pages. An index page connected to a js file. This js file containing ajax code fetching data from database.
this is my js file
$(document).ready(function() {
// getting links from db andshow sub_menu div //
$(".menu_item").mouseover(function(){
$(this).addClass("selected").children().slideDown(500,function(){
var id = $(".selected").attr("id");
var ajax= false;
ajax = new XMLHttpRequest();
var qst = "?id="+id;
ajax.open("GET","ajax/get_sub_cats.php"+qst);
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
$(".sub_menu[title="+id+"]").html(ajax.responseText);
}
}
ajax.send(null);
});
});
// hiding sub_menu div //
$(".menu_item").mouseout(function(){
$(this).removeClass("selected").children(".sub_menu").slideUp(500);
});
// keeping sub_menu div visible on mouse over //
$(".sub_menu").mouseover(function() {
$(this).stop();
});
// clicking sub menu link in the menu //
$(document).delegate("a#subCatLink","click",function(){
alert("test");
});
// document ready end
});
and this is get_sub_cats php file used to fetch links from db
<?php
require('../_req/base.php');
$id = $_REQUEST['id'];
$getSubcatsQ = "select * from sub_cats where Main_Cat_ID = '$id'";
$getSubcatsR = mysql_query($getSubcatsQ);
$numrows = mysql_num_rows($getSubcatsR);
while($row = mysql_fetch_array($getSubcatsR)){
?>
<a id="subCatLink" href="products.php?id=<?php echo $row['Sub_Cat_ID']; ?>"><?php echo $row['Sub_Cat_Name']; ?></a><br />
<?php
}
mysql_close($connect);
?>
clicking links coming from the other php file using ajax is not working at all
Sorry, maybe this will help, maybe not. But...
Why don't you use something like this:
jQuery
$(".menu_item").mouseover(function(){
var id = $(".selected").attr("id");
var qst = "?id="+id;
var html = '';
$.getJSON('ajax/get_sub_cats.php'+qst, function(data){
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<a id="subCatLink'+data[i].Sub_Cat_ID+'" href="products.php?id='+data[i].Sub_Cat_ID+'">'+data[i].Sub_Cat_Name+'</a>';
}
$(".sub_menu[id="+id+"]").html(html);
});
});
PHP
require('../_req/base.php');
$return = array();
$id = $_REQUEST['id'];
$sql = "select * from sub_cats where Main_Cat_ID = '$id'";
$result = mysql_query($sql);
while($ln = mysql_fetch_array($result)){
$return[] = $ln;
}
echo json_encode($return);
ok try this
$(document).delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
});
That should, as a test, show the href for every link on your page. If that works, put all the links you want to show in a div. Then call it with
$('#divID').delegate("click","a",function(){
var target = $(this).attr("href");
alert(target);
})

Turn Regular Javascript Into jQuery

I have some code that involves clicking on a button and either you are logged in and you go to the next page or you are logged out and you get an alert. I have never liked onClick inside HTML and so I would like to turn this around into clicking on the id and having the jQuery do its magic.
I understand the click function of jQuery, but I don't know how to put do_bid(".$val["id"]."); down with the rest of the Javascript. If I haven't given enough information or if there is an official resource for this then let me know.
<li class='btn bid' onclick='do_bid(".$val["id"].");'> Bid </li>
<script>
//Some other Javascript above this
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
</script>
UPDATE: This is the entirety of the Javascript code. I think none of the answers have worked so far because the answers don't fit the rest of my Javascript. I hope this helps
<script language="JavaScript">
$(document).ready(function(){
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "" + s + "";
}
function CountBack() {
<?
for($i=0; $i<$total_elements; $i++){
echo "myTimeArray[".$i."] = myTimeArray[".$i."] + CountStepper;";
}
for($i=0; $i<$total_elements; $i++){
echo "secs = myTimeArray[".$i."];";
echo "DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,1000000));";
echo "DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));";
echo "DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));";
echo "DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));";
echo "if(secs < 0){
if(document.getElementById('el_type_".$i."').value == '1'){
document.getElementById('el_".$i."').innerHTML = FinishMessage1;
}else{
document.getElementById('el_".$i."').innerHTML = FinishMessage2;";
echo " }";
echo "}else{";
echo " document.getElementById('el_".$i."').innerHTML = DisplayStr;";
echo "}";
}
?>
if (CountActive) setTimeout("CountBack()", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor, id) {
document.write("<span id='"+ id +"' style='background-color:" + backcolor + "; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined") BackColor = "white";
if (typeof(ForeColor)=="undefined") ForeColor= "black";
if (typeof(TargetDate)=="undefined") TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined") DisplayFormat = "%%D%%d, %%H%%h, %%M%%m, %%S%%s.";
if (typeof(CountActive)=="undefined") CountActive = true;
if (typeof(FinishMessage)=="undefined") FinishMessage = "";
if (typeof(CountStepper)!="number") CountStepper = -1;
if (typeof(LeadingZero)=="undefined") LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0) CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
var myTimeArray = new Array();
<? for($i=0; $i<$total_elements; $i++){?>
ddiff=document.getElementById('el_sec_'+<?=$i;?>).value;
myTimeArray[<?=$i;?>]=Number(ddiff);
<? } ?>
CountBack();
function do_bid(aid)
{
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
if(loged_in=="")
{
alert('You must log in to bid!');
}
else
{
document.location.href="item.php?id="+aid;
}
}
}</script>
If you want to attach click event handler using jQuery. You need to first include jQuery library into your page and then try the below code.
You should not have 2 class attributes in an element. Move both btn and bid class into one class attribute.
Markup change. Here I am rendering the session variable into a data attribute to be used later inside the click event handler using jQuery data method.
PHP/HTML:
echo "<li class='btn bid' data-bid='".$val["id"]."'>Bid</li>";
JS:
$('.btn.bid').click(function(){
do_bid($(this).data('bid'));
});
If you don't want to use data attribute and render the id into a JS variable then you can use the below code.
var loged_in = "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>";
$('.btn.bid').click(function(){
if(!loged_in){
alert('You must log in to bid!');
}
else{
do_bid(loged_in);
}
});
First, you need to make the <li> have the data you need to send, which I would recommend using the data attributes. For example:
echo "<li class=\"btn bid\" data-bid=\"{$val['id']}\">Bid</li>";
Next, you need to bind the click and have it call the javascript method do_bid which can be done using:
function do_bid(bid){
//bid code
}
$(function(){
// when you click on the LI
$('li.btn.bid').click(function(){
// grab the ID we're bidding on
var bid = $(this).data('bid');
// then call the function with the parameter
window.do_bid(bid);
});
});
Assuming that you have multiple of these buttons, you could use the data attribute to store the ID:
<li class='btn' class='bid' data-id='<?php echo $val["id"]; ?>'>
jQuery:
var clicked_id = $(this).data('id'); // assuming this is the element that is clicked on
I would add the id value your trying to append as a data attribute:
Something like:
<li class='btn' class='bid' data-id='.$val["id"].'>
Then bind the event like this:
$('.bid').click(function(){
var dataId = $(this).attr('data-id');
doBid(dataId);
});
You can store the Id in a data- attribute, then use jQuery's .click method.
<li class='btn' class='bid' data-id='".$val["id"]."'>
Bid
</li>
<script>
$(document).ready(function(){
$("li.bid").click(function(){
if ("" === "<?= $_SESSION["BPLowbidAuction_LOGGED_IN"] ?>") {
alert('You must log in to bid!');
}
else {
document.location.href="item.php?id=" + $(this).data("id");
}
});
});
</script>
If you are still searching for an answer to this, I put a workaround.
If data is not working for you, try the html id.
A working example is here: http://jsfiddle.net/aVLk9/

jQuery/PHP Hide Div, Update Information from MySQL, Show Div New Information

jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});

Categories