I need to hide/show HTML elements in my code.
The page is generated in PHP.
Trying to semplify my code here you area a sample that show my troubles ...
echo '<button type="button" onclick="hide_show('.$n_images.')">Hide / show details</button>';
echo '<script language="javascript">';
echo 'function hide_show(n_images)';
echo ' {';
echo ' element = document.getElementById("details_0");';
echo ' if (element.style.visibility == \'visible\') {';
echo ' element.style.visibility = \'hidden\'';
echo ' }';
echo ' else {';
echo ' element.style.visibility = \'visible\'';
echo ' }';
echo ' }';
echo '</script>';
In this case the code is working and all it's fine.
My problem is that I've several elements to hide /show and so I need to substitute the line
echo ' element = document.getElementById("details_0");';
using a while and I don't know as generalize that code ...
My final code shoud be something like this .. .
echo '<button type="button" onclick="hide_show('.$n_images.')">Hide / show details</button>';
echo '<script language="javascript">';
echo 'function hide_show(n_images)';
echo ' {';
echo ' while (current_index < n_images ) {';
echo ' element = document.getElementById("details_0");'; --> this is the line I need to generalize !!!
echo ' if (element.style.visibility == \'visible\') {';
echo ' element.style.visibility = \'hidden\'';
echo ' }';
echo ' else {';
echo ' element.style.visibility = \'visible\'';
echo ' }';
echo ' current_index = current_index + 1;';
echo ' }';
echo ' }';
echo '</script>';
Any help / suggestions / example?
Thank you in advance!
Cesare
Hi Cesare to make it easier why not just use one php echo statement for your entire JavaScript. before your while loop, initialize current_index to 0. in your js in the line you need to generalize, getElementById("details_" + current_index)
echo '<button type="button" onclick="hide_show('.$n_images.')">Hide / show details</button>';
echo '<script language="javascript">';
echo 'var i = 0';
echo 'function hide_show(n_images)';
echo ' {';
echo ' while (current_index < n_images ) {';
echo ' element = document.getElementById("details_" + i);'; --> this is the line I need to generalize !!!
echo ' if (element.style.visibility == \'visible\') {';
echo ' element.style.visibility = \'hidden\'';
echo ' }';
echo ' else {';
echo ' element.style.visibility = \'visible\'';
echo ' }';
echo ' current_index = current_index + 1;';
echo ' i++;'; //increment variable i value...
echo ' }';
echo ' }';
echo '</script>';
just initialize counter like 'var i' and add that to ever id.
Related
When I want to submit a form with my js i always get this error:
Uncaught TypeError: Cannot read property 'submit' of null
its like the js doesnt find the form
Here the js code:
echo "<script language='javascript' type='text/javascript'>";
echo "function send(ak,id){";
echo "document.getElementById('java').submit(); ";
echo "document.write('submited');";
echo"}";
echo "</script>";
And here the php / html:
echo "<form id='java' method='post' action='reisegruppe.php' >";
echo "<input name='ak' type='hidden' />";
echo "<input name='id' type='hidden' />";
// Reisegruppe ausgeben
if ($result1->num_rows > 0) {
// Reisegruppe ID , von , nach ausgeben
$count = 1;
while($row1 = $result1->fetch_assoc()) {
echo "<br>" . "id: " . $row1["reisegruppe_id"].
" - <b> von: </b> " .'<b>'.'<input name="von" value='.$row1["von"].' size="5" />'.'</b>'. " " .
"<b>nach: </b>" .'<b>'.'<input size="5" name="nach" value='. $row1["nach"].'>'.'</b>'." ". "<br>";
echo "<a href='javascript:send(1,32)';>neu eintragen</a>";
while($row = $result->fetch_assoc()){
if($row1["reisegruppe_id"] == $row["FK_reisegruppe_id"]){
echo " - Name: " . $row["vorname"]. " " . $row["nachname"]. " " . "<br>";}
}
$sql = "SELECT reisegruppe_id, von, nach,teilnehmer_id, vorname, nachname,FK_reisegruppe_id FROM Reisegruppe JOIN Teilnehmer on FK_reisegruppe_id = reisegruppe_id";
$result = $conn->query($sql);
}
} else {
echo "0 results";
}
echo </form>;
comment this line because it is stop the from from submitting
echo "document.write('submited');";
<?php
include_once("db.php");
$result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'");
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ptype'] . "</td>";
echo "<td>" . $row['source'] . "</td>";
echo "<td>" . $row['letterno'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['descrip'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><a href='vex.php?uid={$row['letterno']}' id='id' onClick='addfavourite()'>.{$row['title']}.</a></td>";
//echo "<td><a href='update.php?id={$row['id']}'>Update</a></td>";
echo"<td><img style='width:100px;higth:150px;' src='upload/{$row[image]}'></td>";
addfavourite();
echo addfavourite();
function addfavourite() {
$ide=$_GET['uid'];
//echo $ide;
$sql = "SELECT * FROM stu WHERE letterno = '$ide'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if($row){
$newfav = "UPDATE stu SET open = 1 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);}
else{
$newfav = "UPDATE stu SET open = 0 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);}
}
}
echo $ide;
?>
This is my error code.In this code,there is a fault with mysql query statement.it is not supported with the databse. but onclick() function is working.
You cannot directly execute a PHP function from a JavaScript event. Simply, cannot mix server side and client side logic but you can make two of them interact with each other.
In this case, you can create a JavaScript function which sends an AJAX request to a PHP page on your server containing the code of addfavourite().
A Demo
I haven't tested the code below but assuming that your code logic and rest stuff is correct, this might just work
demo.php
<script>
function addfavourite(uid){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
var url = "addfavourite.php"; // URL of your PHP file
var vars = "uid="+uid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
<?php
include_once("db.php");
$result=mysql_query("SELECT * FROM stu WHERE receiver='DM4'");
echo "<table>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ptype'] . "</td>";
echo "<td>" . $row['source'] . "</td>";
echo "<td>" . $row['letterno'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['descrip'] . "</td>";
echo "<td>" . $row['receiver'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td><a href='#' id='id' onClick='addfavourite({$row['letterno']})'>.{$row['title']}.</a></td>";
echo"<td><img style='width:100px;higth:150px;' src='upload/{$row[image]}'></td>";
}
echo "</table>";
?>
<div id='status'></div>
addfavourite.php
<?php
if(!isset($_POST['uid'])) {
$ide = $_POST['uid'];
$sql = "SELECT * FROM stu WHERE letterno = '$ide'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
$newfav = "UPDATE stu SET open = 1 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);
} else {
$newfav = "UPDATE stu SET open = 0 WHERE letterno = '$ide'";
$createfav = mysql_query($newfav);
}
if ($createfav) {
echo "<script>alert('Added to favourite successfully...')";
} else {
echo "<script>alert('Something went wrong...')";
}
}else{
echo "POST variable not set!";
}
?>
Some notes
You should use mysqli insted of mysql functions as it is deprecated and no longer supported
This here is a good video tutorial on AJAX https://www.developphp.com/video/JavaScript/Ajax-Post-to-PHP-File-XMLHttpRequest-Object-Return-Data-Tutorial
so here's a very simple question but I'm having difficulties on solving it
see i have an iframe and i want to change it's src depending on the link that was clicked
here's the javascript code
function showOverlay(id)
{
var str1 = 'abstract.php?id=';
var link = str1.concat(id);
document.getElementById(id).style['display'] = "block";
document.getElementById(id).style['opacity'] = "1";
document.getElementById('abstract_frame').src = link;
}
function hideOverlay(el, evt)
{
if (el && evt)
{
el.style.display = evt.target == el ? 'none' : '';
}
document.getElementById('abstract_frame').src = '';
}
so I used document.getElementById('abstract_frame').src = link; to set the src then on the hideOverlay function I used
document.getElementById('abstract_frame').src = ''; to set the src back to a blank link.
so the problem is when I call on the showOverlay again to set another src link to the iframe with a different value i get a blank screen
here's the html/php
echo '<div class="SearchResults">';
echo " <span class='top'>";
echo " <a>";
echo " <h3>". strtoupper($title) ."</h3>";
echo " </a>";
echo " <br />";
echo " <h5 class='sub'>";
echo "Authors :";
$tags = explode('|',$run['author']);
foreach($tags as $i =>$key) {
echo '<a class="authors">Dr.'.$key.'</a>';
}
echo "<br><br>";
echo " </h5>";
echo " </span>";
echo " <span class='bottom'>";
echo " <span class='bottomLeft'>";
echo ($run['abstract'] != "" ? " <a class='options' data-articlenum='" . $run['reference_number'] . "' onclick='showOverlay(this.dataset.articlenum)'>Abstract</a><span style='margin:0px 5px;'>|</span>" : "" );
echo " <a target='_blank' href='view.php?filename=".strtolower($run['title'])."' class='options'>";
echo " Full Article";
echo " </a>";
echo " </span>";
echo " <div class='overlay' id='". $run['reference_number'] ."' onclick='hideOverlay(this, event)'> ";
echo " <iframe class='abstract' id='abstract_frame' style='padding:0px;' scrolling='no'>";
echo " </iframe>";
echo " </div>";
echo " <span class='bottomRight'>";
echo " <p class='label'>".$run['journal'].", ". $run['volume'] .", ". date("F, Y",strtotime($run['publication_date'])) ."# Pg.". $run['pages'] ."</p>";
echo " </span>";
echo " </span>";
echo " <br style='clear:both;'/>";
echo "</div>";
here's some visuals
i have a ajax function that is returning a set of values from php page.
i need to get the values to that is only required. how can i do this
ajax.js
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
ajax.php
<?php
require_once('config.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM thr';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['ther_name'] . "</td>";
echo "<td>" . $row['region'] . "</td>";
echo "<td>" . $row['phone_no'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
i need only values of
$row['corrd_lattitude']
$row['corrd_longitude']
how to get the values of this
first you can fetch only required values from table..if i understood correctly you can use following query.
$sql = 'SELECT corrd_lattitude,corrd_longitude FROM thr';
it will return only tw0 column value from table.
$json = json_encode(array($row['corrd_lattitude'], $row['corrd_longitude']));
echo $json;
You could specify parameters with your request.
In GET method:
ajax.php?corrd_lattitude=true&corrd_longitude=true
and in php file you can check this in $_GET array ie:
<?php
[...]
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
if ($_GET['id'] == true) {
echo "<td>" . $row['id'] . "</td>";
}
if ($_GET['ther_name'] == true) {
echo "<td>" . $row['ther_name'] . "</td>";
}
if ($_GET['region'] == true) {
echo "<td>" . $row['region'] . "</td>";
}
if ($_GET['phone_no'] == true) {
echo "<td>" . $row['phone_no'] . "</td>";
}
if ($_GET['address'] == true) {
echo "<td>" . $row['address'] . "</td>";
}
if ($_GET['corrd_lattitude'] == true) {
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
}
if ($_GET['corrd_longitude'] == true) {
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
Better is use json (or plain values) instead of html - your js should pack values into html. It's better for server, client side should build html. Sry for my english.
use json:-----------
=========================================
$sql = "SELECT * FROM thr";
$rs = mysql_query($sql);
$res = mysql_fetch_assoc($rs);
if(mysql_num_rows($rs)>0){
echo json_encode(array('lats'=>$res['corrd_lattitude'],'lngs'=>$res['corrd_longitude']));
}else{
echo json_encode(array('lats'=>'','lngs'=''));
}
here lats and lngs are simply varaiable name to store values inside them and get the value on other page from lats and lngs varaibale.
I am using jQuery to produce some text that is coming from my Database.
However I keep getting the jQuery error:
unterminated string literal
My code in raw format looks like :
+ "<div class='operator-details'>"
+ "<strong>Operator:</strong> Stuart"
+ "<br />"
+ "<br /><strong>Phone:</strong> 01"
+ "<br />"
+ "<br /><strong>Contact:</strong> <a href='#'>x#x.com</a>"
+ "</div>"
+ "<div class='featured-venue'>"
+ "<p>Great venue to vistIt is a pleasure to feature it.</p>"
+ "</div>"
The jQuery code is :
+ "<div class='operator-details'>"
+ "<strong>Operator:</strong> <?php echo $venue->user_firstname; ?> <?php echo $venue->user_surname; ?>"
+ "<br />"
+ "<br /><strong>Phone:</strong> <?php echo $venue->user_telephone; ?>"
+ "<br />"
+ "<br /><strong>Contact:</strong> <a href='mailto:<?php echo $venue->user_email; ?>'><?php echo $venue->user_email; ?></a>"
<?php if($venue->venue_website) { ?>
+ "<br />"
+ "<br /><strong>Website:</strong> <a href='<?php echo $venue->venue_website; ?>' target='_blank'><?php echo $venue->venue_website; ?></a>"
<?php } ?>
+ "</div>"
<?php if($venue->venue_featured == 'Yes') { ?>
+ "<div class='featured-venue'>"
+ "<p><?php echo strip_tags($venue->venue_featured_text); ?></p>"
+ "</div>"
<?php } ?>
Is there any way I can correct this error?
Thanks