I need to refactor this code, Im not a php developer so i dont understand the syntax thats apparent here, what i want is this button to activate the moment the page is loaded.
<?php
$h = '';
if ($newsermonstomove) {
foreach ($newsermonstomove as $vettel) {
$h .= "<div style=\"padding: 5px;\">";
$h .= "<button id=\"btn_" . $vettel->ID . "\" class=\"btn btn-primary btn-xs\" onclick=\"doMe(" . $vettel->ID . ");\" >s3</button><span style=\"padding-left:5px;\">Channel: " . $vettel->ChannelID . ", Sermon: " . $vettel->ID . " " . $vettel->SermonTitle . "</span> <div style=\"display:none;color:blue;\" id=\"msg_" . $vettel->ID . "\"></div><br/>";
$h .= "</div>";
}
} else {
$h = "<h3>No new sermons.</h3>";
}
echo $h;
?>
From what i understand, the onclick has an escape in it onclick=\"doMe(" . $vettel->ID . ");\" In HTML i know that with a button if you do onclick=doMe its a reference to a function, which i feel like is the same thing thats happening here with the escape keys in it. its making a reference to the function doMe, but i want the function to fire automatically when the page loads.
Ok, i was able to figure out the answer I needed using JQuery.
$("document").ready(function() {
setTimeout(function() {
$(".btn").trigger('click');
},10);
});
essentially what this function does is wait for the page to load then after 10 milliseconds it targets all buttons on the screen with the class name btn and triggers the click functionality of the button, thus firing off the button on the page load.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if (!empty($newsermonstomove)) {
$h = '';
foreach ($newsermonstomove as $vettel) {
$h .= '<div style="padding: 5px;">';
$h .= '<button data-id="' . $vettel->ID . '" class="btn-vettel btn btn-primary btn-xs">s3</button><span style="padding-left:5px;">Channel: ' . $vettel->ChannelID . ', Sermon: ' . $vettel->ID . ' ' . $vettel->SermonTitle . '</span> <div style="display:none;color:blue;" id="msg_'.$vettel->ID.'"></div><br/>';
$h .= '</div>';
}
} else {
$h = '<h3>No new sermons.</h3>';
}
echo $h;
?>
<script>
$(function() {
$('.bt-vettel').on('click', function(e) {
var id = $(this).data('id');
doMe(id);
});
});
<script>
Related
I have used a widget called addthisevent to allow users to add a class booking to their calendar. It is all working as indented but when I echo the link to the page I get a random ‘1’ next to the button. As you can see here -- http://oi60.tinypic.com/10fu8ac.jpg --
==add_event.php==
<?php
//Call session variables
$start_time = $_SESSION['class_time_start'];
$end_time = $_SESSION['class_time_end'];
$date = $_SESSION['class_date'];
$class_name = $_SESSION['class_name'];
$client_F_name = $_SESSION['firstname'];
$client_L_name = $_SESSION['lastname'];
$client_email = $_SESSION['email'];
//echo addthisevent script
echo '<script type="text/javascript" src="https://addthisevent.com/libs/ate-latest.min.js"></script>';
//echo addthisevent with the variables in place, ready to be converted using the JS function
echo '<a href="http://example.com/link-to-your-event" title="Add to Calendar" class=" addthisevent" id="addthisevent">'
, 'Add to Calendar'
, '<span class="_start">' . $date . ' ' . $start_time . '</span>'
, '<span class="_end">' . $date . ' ' . $end_time . '</span>'
, '<span class="_zonecode">36</span>'
, '<span class="_summary">' . $class_name . ' Class</span>'
, '<span class="_description">Your ' . $class_name . ' class with ****</span>'
, '<span class="_location">*****</span>'
, '<span class="_organizer">*****</span>'
, '<span class="_organizer_email">******</span>'
, '<span class="_facebook_event">*****</span>'
, '<span class="_all_day_event">false</span>'
, '<span class="_date_format">YYYY/MM/DD</span>'
, '</a>';
?>
Let me know if you need more code as I understand this is a weird issue I'm having.
I really can't work out what is causing it. I know it is definitely coming from the php above. If there is a way to fix this issue or just to simply remove the '1' after the page has loaded as a workaround that would be great
Thanks
The page link is http://217.37.5.115/content/temppage.php
you will need to select the dropdown boxes for it to appear
In short:
I use this function below to run a php script when the value of one of the dropdown boxes changes
===temppage.php (main page)===
<script>
function class_space_Update(str) {
if (str == "") {
document.getElementById("class_spaces").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("class_spaces").innerHTML = xmlhttp.responseText;
addthisevent.refresh();
}
}
xmlhttp.open("GET", "../includes/get/class_spaces.php?id=" + str, true);
xmlhttp.send();
}
}
</script>
===class_spaces.php===
<?php
//Set session variables
//Session 'class_time_start'
$_SESSION['class_time_start'] = $start_time;
//Session 'class_time_end'
$_SESSION['class_time_end'] = $end_time;
//Session 'class_date'
$_SESSION['class_date'] = $date;
//Session 'space_left'
$_SESSION['space_left'] = $space_left;
//Include add_event.php
echo include_once ($_SERVER["DOCUMENT_ROOT"] . "/includes/add_event.php");
//Close MySQLi connection
mysqli_close($mysqli);
?>
This isn't all of that file as it isn't really necessary.
If I comment out the echo include_once add_event.php part then the '1' does not appear.
Quick solution I can offer for you is:
<?php
//Call session variables
$start_time = (isset($_SESSION['class_time_start']))?$_SESSION['class_time_start']:'';
$end_time = (isset($_SESSION['class_time_end']))?$_SESSION['class_time_end']:'';
$date = (isset($_SESSION['class_date']))?$_SESSION['class_date']:'';
$class_name = (isset($_SESSION['class_name']))?$_SESSION['class_name']:'';
$client_F_name = (isset($_SESSION['firstname']))?$_SESSION['firstname']:'';
$client_L_name = (isset($_SESSION['lastname']))?$_SESSION['lastname']:'';
$client_email = (isset($_SESSION['email']))?$_SESSION['email']:'';
//echo addthisevent script
ob_start();
echo '<script type="text/javascript" src="https://addthisevent.com/libs/ate-latest.min.js"></script>';
//echo addthisevent with the variables in place, ready to be converted using the JS function
echo '<a href="http://example.com/link-to-your-event" title="Add to Calendar" class=" addthisevent" id="addthisevent">'
, 'Add to Calendar'
, '<span class="_start">' . $date . ' ' . $start_time . '</span>'
, '<span class="_end">' . $date . ' ' . $end_time . '</span>'
, '<span class="_zonecode">36</span>'
, '<span class="_summary">' . $class_name . ' Class</span>'
, '<span class="_description">Your ' . $class_name . ' class with ****</span>'
, '<span class="_location">*****</span>'
, '<span class="_organizer">*****</span>'
, '<span class="_organizer_email">******</span>'
, '<span class="_facebook_event">*****</span>'
, '<span class="_all_day_event">false</span>'
, '<span class="_date_format">YYYY/MM/DD</span>'
, '</a>';
exit();
So first off, I'm new with jQuery and Ajax. I'm curious to learn more and decided to make a project for myself that is based on Ajax/PHP/jQuery/JavaScript and so on... I want to combine all languages. Now i ran into an problem wich is:
The code of my JavaScript, this call's the PHP file:
function fetchDatabase(method, value) {
document.getElementById("database_result").innerHTML = '<p class="loading">Laden...</p>';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("database_result").innerHTML = xmlhttp.responseText;
}
}
if (value != 'none') {
xmlhttp.open(method, 'php/fetch_browse.php?value=' + value);
} else {
xmlhttp.open(method, 'php/fetch_browse.php');
}
xmlhttp.send();
}
Now here is my PHP file, this fetches data out of my database:
<?php
include('database.php');
if (isset($_GET['value'])) {
$value = $mysqli->real_escape_string($_GET['value']);
$filequery = "SELECT * FROM files WHERE filelocation='".$value."'";
$folderquery = "SELECT * FROM folders WHERE folderlocation='".$value."'";
} else {
$filequery = "SELECT * FROM files";
$folderquery = "SELECT * FROM folders";
}
foreach ($mysqli->query($folderquery) as $row) {
echo '<a class="browseclick">';
echo '<div class="browse-item">';
echo '<img src="img/browse-item/folder.png">';
echo '<p title="' . $row['foldername'] . '">' . $row['foldername'] . '</p>';
echo '</div>';
echo '</a>';
}
foreach ($mysqli->query($filequery) as $row) {
echo '<a class="browseclick">';
echo '<div class="browse-item">';
echo '<img src="img/browse-item/' . $row['filetype'] . '.png">';
echo '<p title="' . $row['file'] . '">' . $row['file'] . '</p>';
echo '</div>';
echo '</a>';
}
mysqli_close($mysqli);
?>
As you can see, in my PHP code the <a>'s have a class: ".browseclick"
I want with jQuery if i click this i can execute a function.
So my jQuery code is:
$('.browseclick').click(function() {
var test = $(this).text() + ' - < This is a test';
console.log(test);
});
But it doesn't console.log() anything. not even the '< This is a test'.
So I tried to put script tags with an alert in the PHP file it self. Also this won't work.
Anyone an idea how i CAN execute javascript with content my ajax has fetched?
Thanks,
I've got this code:
while ($row = mysql_fetch_assoc($result1)) {
echo "
<a href='#'id='VV".$row['id']."'>
<p>".$row['title']."</p>
<p>".$row['date']."</p>
<img onload='scale()' id='II".$row['id']."' src='../res/videos/img/".$row['img']."'/>
</a>
<script type='text/javascript'>
function scale(){
var image = document.getElementById('II".$row['id']."');
var width = image.width;
var height = image.height;
if (width > 150) {
image.style.width = '150px';
image.style.height = 'auto';
}
width = image.width;
height = image.height;
if (height > 80) {
image.style.height = '80px';
image.style.width = 'auto';
}
width = image.width;
height = image.height;
}
VV".$row['id'].".onclick = function() {
var Result = '".$row['id']."';
location.href='loged.php?Result=' + Result;
}
</script>
";
}?>
I want the resize function be called on every image loaded, but it is called when the last image is loaded, and only the last image takes effect. What should i change?
You are placing the script for each $row. I would have 1 copy of the javascript function and then you can call that single function N times passing the id to the function. This way it will work for all rows, not just the last (since the last copy of the JS function will be the only one called as you've found out).
Short answer: make your function better by taking a id parameter and only put that function on the page once. allow you foreach to call said function with each id.
I think you are trying to fit an image in a 150x80 area. If that's the case, I suggest you use CSS background-size: contain to do the scaling for you.
while ($row = mysql_fetch_assoc($result1))
echo "<a href='#' id='VV" . $row['id'] . "'>" .
"<p>" . $row['title'] . "</p>" .
"<p>" . $row['date'] . "</p>" .
"<div id='II" . $row[id] . "' " .
"style='width: 150px; " .
"height: 80px; " .
"background: url(../res/videos/img/" . $row['img'] . "); " .
"background-size: contain; " .
"background-repeat: no-repeat;'>" .
"</div>" .
"</a>";
It'd be a good idea to abstract out the styling into a CSS file.
while ($row = mysql_fetch_assoc($result1))
echo "<a href='#' id='VV" . $row['id'] . "'>" .
"<p>" . $row['title'] . "</p>" .
"<p>" . $row['date'] . "</p>" .
"<div id='II" . $row[id] . "' " .
"class='my_img_box' " .
"style='background: url(../res/videos/img/" . $row['img'] . ");'>" .
"</div>" .
"</a>";
The CSS
div.my_img_box {
width: 150px;
height: 80px;
background-size: contain;
background-repeat: no-repeat;
}
My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']
I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.