I have coded the two HTML pages below.
Page2d.php is intended to display a select element that allows the client to select an ID, then open a new window with that ID showing on a new page (Page3b.php) when the button is clicked. The parent (Page2d.php) keeps an array of child windows globally.
Problem 1: ID number selected did not write to child window.
Because the script is malfunctioning I receive an error in the Google console stating "Uncaught TypeError: Cannot set property 'innerHTML' of null".
I am using an array of IDs to record those selected and I realize this might not be the best idea but I tried so many different ways with no success. Help !!!!
Page2d.php
<!doctype html>
<html>
<head>
<title>Page 2d</title>
<script type='text/javascript'>
var IDS = [];
var WindowTabs = 0;
var WindowRef = [];
function TestIfOpen() {
var OkToOpen = 1; //true
//Get the ID selected
var sel = document.getElementById('_ID');
var opt = sel.options[sel.selectedIndex];
var IDselected = opt.value;
if (WindowRef.length == 0) {
IDS[WindowTabs] = IDselected;
WindowRef[WindowTabs] = window.open('Page3b.php?TAB=' + WindowTabs, '');
WindowRef[WindowTabs].document.getElementById('_ID').innerHTML = "ID equals " + IDselected;
} else {
for (var x = 0; x < WindowRef.length; x++) {
if(!WindowRef[x].closed) {
if(IDS[x] == IDselected) {
OkToOpen = 0; //false
alert("A window for this ID is already opened");
}
} else {
IDS[x] = 0;
}
}
if (OkToOpen == 1) {
WindowTabs++;
IDS[WindowTabs] = IDselected;
WindowRef[WindowTabs] = window.open('Page3b.php?TAB=' + WindowTabs, '');
WindowRef[WindowTabs].document.getElementById('_ID').innerHTML = "ID equals " + IDselected;
}
}
}
</script>
</head>
<body>
<?php
echo "<form method='POST' action='$PHP_SELF'>";
$IDS = array("200","201","202","203","204","205","206");
echo "Select an ID:<p><select name='_ID' id='_ID'>";
foreach($IDS as $value) {
echo "<option value='".$value."'";
if($value == $_POST['_ID']) {
echo " selected ";
}
echo ">".$value."</option>";
}
echo "</select></p>";
echo "<button type='button' onclick='TestIfOpen();'>Click Here to Open a window for this ID</button></form>";
?>
</body>
</html>
Page3b.php
<!doctype html>
<html>
<head>
<title>Page 3b</title>
</head>
<body>
<span id='_ID'>This is original text</span><br>
</body>
</html>
P.S.
My original post contained errors in array management that I discovered and have repaired in the code above.
Related
i have a ads script which i stored in my database using textarea field. but when i echo that script in php. then it will not working.
this is my script which i saved in database by using textarea field.
<script type="text/javascript">
( function() {
if (window.CHITIKA === undefined) { window.CHITIKA = { 'units' : [] }; };
var unit = {"calltype":"async[2]","publisher":"seeknfameads","width":300,"height":250,"sid":"Chitika Default","color_site_link":"337ab7","color_text":"337ab7"};
var placement_id = window.CHITIKA.units.length;
window.CHITIKA.units.push(unit);
document.write('<div id="chitikaAdBlock-' + placement_id + '"></div>');
}());
</script>
<script type="text/javascript" src="//cdn.chitika.net/getads.js" async></script>
And when i fetch field and try to echo this. it is not working.
$sql4 = "SELECT * FROM abc ORDER BY id DESC LIMIT 1";
$query4 = $conn->query($sql4);
$row4 = $query4->fetch(PDO::FETCH_ASSOC);
$video_des=$row4['video_des'];
$rowc = $query4->rowCount(PDO::FETCH_ASSOC);
if ($rowc>=1){
<script><?php echo $video_des;?></script>
}
please help to fix this problem.
As you are already inserting value of video_des with <script> and </script> tag
You don't need to add <script> tag again, Please try below.
$sql4 = "SELECT * FROM abc ORDER BY id DESC LIMIT 1";
$query4 = $conn->query($sql4);
$row4 = $query4->fetch(PDO::FETCH_ASSOC);
$video_des=$row4['video_des'];
$rowc = $query4->rowCount(PDO::FETCH_ASSOC);
if ($rowc>=1){
echo $video_des;
}
Simply do this at your if condition result
if ($rowc>=1){
echo $video_des; // remove script tag from here
}
This is the first time I use this medium to ask for help. I wanted to know how , in my code , include two listbox . One that makes querying the database and , through a button , send it to the other, and to do so with more than one option , and then , as in the php code to put the data from the second listbox on a table database. Thank you.
<?php
include("server.php");
$conexion = mysql_connect($server,$user, $pass) or die ("<br> No se puede conectar con la base de datos");
$conectarbase = mysql_select_db ($bd);
$consulta = mysql_query("SELECT * FROM modalidad")
?>
<html lang = "es">
<head>
<meta charset = "iso-8859-1"/>
<meta name = "description" content = "Ejemplo de HTML5"/>
<meta name = "keywords" content = "HTML5, CSS3, Javascript"/>
<title>PRECEPTORÍA</title>
<link rel="shortcut icon" href="./style/favicon.png" />
<link rel = "stylesheet" href = "./style/style.css">
</head>
<body class = "body">
<section class = "section">
<div class = "div">
<form>
<fieldset id = "fieldsetalum">
<legend id = "legendalum">Registro de nuevos alumnos</legend>
<select name="combo1" multiple size="8">
<?php
while ($fila = mysql_fetch_row($consulta))
{
echo "<option value='".$fila['0']."'>".$fila['1']."</option>";
}
?>
</select>
<select name="combo2" multiple size=></select>
</fieldset>
</form>
</div>
</section>
</body>
</html>
Your form needs an action to submit to itself:
<form name="form" id="form" action="<?php echo echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>" method="post">
You could add an onChange(); event to your select1 dropdown
<select name="combo1" multiple size="8" onChange="submit_this();">
and have a JavaScript script in your <head>
<script language="javascript"> function submit_this(){ this.form.submit();}</script>
Then you would have to use php to collect the values from the submitted page
$combo1 = mysqli_real_escape_string( $_POST['combo1'] );
and then you could return the page with the second dropdown, constructed in much the same way as you made the first one, using the data you get back from the first one to set up the second one. You could wrap the first dropdown in an isset():
if( !isset( $combo1 ) ){
// make your first select boxes
}
and the second one in
if( isset( $combo1 ) ){
// make your second select boxes if combo1 returned a value
}
so that they will only appear when needed.
As #NanaPartykar says, mysqli is the only way to go.
It will be dependent on JavaScript, so, if you prefer, you could have a submit button instead of the JavaScript function:
<input type="submit" name="submit" value="Pick Sizes" />
This looks a handy referenc e for how to use select boxes: PHP code to get selected text of a combo box
I hope this will give you an idea of how it could be done - the SESSION variables remain to be properly defined in the loop for the second dropdown but they will probably come directly from your database at that point rather than from the session array used for demo purposes.
All values are set as numbers;
intval(); converts whatever is submitted to an integer to clean it up.
Then you can get back the corresponding value of what was submitted from the session variable you set from your database originally.
That way you will only be getting a single number value from your dropdowns which you can use to look up to get the answer you want
<?php session_start(); ?>
<!DOCTYPE html>
<html lang = "es">
<head>
<title>PRECEPTORÍA</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<?php
$main_opt = array();
$_SESSION['opt_vals'] = array();
$main_opt[0] = "Select Item";
$main_opt[1] = "Ice Cream";
$main_opt[2] = "Trousers";
$main_opt[3] = "Tee Shirts";
$_SESSION['opt_vals'][1][0] = "Select Flavour";
$_SESSION['opt_vals'][1][1] = "Vanilla";
$_SESSION['opt_vals'][1][2] = "Chocolate";
$_SESSION['opt_vals'][1][3] = "Strawberry";
$_SESSION['opt_vals'][1][4] = "Tuttifrutti";
$_SESSION['opt_vals'][2][0] = "Select Colour";
$_SESSION['opt_vals'][2][1] = "Black";
$_SESSION['opt_vals'][2][2] = "Red";
$_SESSION['opt_vals'][2][3] = "Green";
$_SESSION['opt_vals'][2][4] = "Blue";
$_SESSION['opt_vals'][3][0] = "Select Size";
$_SESSION['opt_vals'][3][1] = "Small";
$_SESSION['opt_vals'][3][2] = "Medium";
$_SESSION['opt_vals'][3][3] = "Large";
$_SESSION['opt_vals'][3][4] = "X Large";
$i = 0;
if(!isset($_POST['combo1']) && !isset($_POST['combo2'])){
echo '<select name="combo1" onChange="submit();">' . "\n";
//while ($fila = mysqli_fetch_row($consulta)){
while($i < count($main_opt)){
echo "<option value='".$i."'>".$main_opt[$i]."</option>\n";
$o = 0;
// load your sub options array here
if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
while($i < count($_SESSION['opt_vals'][$i])){
$_SESSION['opt_vals'][$i] = $o;
if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
$_SESSION['opt_vals'][$i][$o] = $_SESSION['opt_vals'][$i][$o];
$o++;
}
$i++;
}
echo '</select>' . "\n";
}else{
if(intval($_POST['combo1']) >= 1) $_SESSION['combo1_val'] = $combo1_val =intval($_POST['combo1']);
if(intval($_POST['combo1']) >=1){
$i = 0;
echo '<select name="combo2" onChange="submit();">' . "\n";
while($i < count($_SESSION['opt_vals'][$combo1_val])){
echo "<option value='".$i."'>".$_SESSION['opt_vals'][$combo1_val][$i]."</option>\n";
$i++;
}
}
echo '</select>' . "\n";
}
if(intval($_POST['combo2']) >= 1) $_SESSION['combo2_val'] = $combo2_val =intval($_POST['combo2']);
if($_SESSION['combo1_val'] >=1 && $_SESSION['combo2_val'] >=1){
// use the result to do whatever you want
echo 'Thank you! You have selected ' . $_SESSION['opt_vals'][$_SESSION['combo1_val']][$_SESSION['combo2_val']] . " " . $main_opt[$_SESSION['combo1_val']] . '.';
}
// Do any mysqli adjustments to your database here
// reset to go again
if($_SESSION['combo2_val'] >= 1){
$_SESSION['combo1_val'] = 0;
$_SESSION['combo2_val'] = 0;
}
?>
</form>
Click to start a new selection
</body>
</html>
You could remove onChange="submit();" and replace it with a normal submit button on the form if you prefer.
i'm making an online barcode scanner application and having some issues with sending a javascript variable to php for my query , and getting it back in my html file with the data.
User scans barcode (studentNr)
studentnr --> variable is going to be posted to the php file.
in php file : query to compare with variable
result of query --> back to the parameter of function(data)
print result.
Sounds easy, but how do I do this correctly?
Index.html :
<head>
<meta charset="utf-8" />
<!-- Set the viewport width to device width for mobile -->
<meta name="viewport" content="width=device-width" />
<script src="javascripts/jquery.js"></script>
</head>
<body>
<div>
<input type="text" name="barcode" id="barcode"> // BARCODE SCAN
<input type="text" id="student" placeholder="studentenNaam" size="30"> //NAME FROM DB
<!-- <input type="text" id="barcode" placeholder="Waiting for barcode scan..." size="40">
<input type="text" id="student" placeholder="studentenNaam" size="30">-->
</div>
// just the script for scanning the barcode :
<script>
var barcodeParsed = null;
var studentenNr = null;
$(document).ready(function() {
var pressed = false;
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function(){
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
barcodeParsed = barcode;
var barcodeParsing = barcodeParsed.substring(5,11);
$("#barcode").val("s" + barcodeParsing);
studentenNr = "s" + barcodeParsing;
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
$("#barcode").keypress(function(e){
if ( e.which === 13 ) {
console.log("Prevent form submit.");
$.post('testdb.php', {'studnr' :studentenNr}, function(data){ //POST JS VAR TO PHP FILE
$('#student').html(data); //RECEIVE DATA FROM DB INTO ID ELEMENT
});
e.preventDefault();
}
});
</script>
</body>
And in my testdb.php file it looks like this :
<?PHP
$studnr = htmlspecialchars($_POST['studnr']);
if(isset($studnr)){
$user_name = "root";
$password = "";
$database = "Student";
$hostname = "127.0.0.1";
$db_handle = mysql_connect($hostname, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM student where studentenNr= '$studnr'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
/* Here needs the data to fetch*/
print $db_field['naam'] . "<BR>";
print $db_field['studentenNr'] . "<BR>";
print $db_field['voornaam'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
The problem is i can't receive any data from my html file in to my php file, plus i don't know how i can put the received data back in to my html file.
in the php-file..How do I write it back to the html ?
Do I need to use Ajax,Jquery,..
Any other solutions ?
Thank you for helping me out !
UPDATE
when adding this between the if(db_found) brackets I get an Internal Server Error 500.
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
$sql->execute($arraytest = array(':studnr' => studentenNr,naam );)
$sql->execute(array(":studentenNr" => $studnr));
$data = $sql->fetchAll();
foreach($item as $data){
print($item["naam"]);
log($item["naam"]);
On your javascript you're sending studnr parameter:
$.post('testdb.php', {'studnr' :studentenNr}, function(data){
In your php script you trying to get the value from studentenNr parameter:
$studnr = htmlspecialchars($_POST['studentenNr']);
You need to cahnge your script to
$studnr = htmlspecialchars($_POST['studnr']);
Edit:
You're getting internal error because of this line:
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
You need to prepare the SQL statement with the parameters and then bind them, so the line should be (something like):
$sql = $db->prepare("select * from student where studentenNr= :studnr");
$sql->execute(array(':studnr' => $studnr ));
I'm not sure if it's just me or what but this seems really odd. When I click a button I have jquery send out javascript variables to a php site to be handled there. However on the php site they come up as undefined indexes. The weird part, is that they show on the html page through php's echo. NOTE: The html button is an input type="button", not a submit because I don't want to reload the page.
jquery:
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
php:
//used for troubleshooting, returns Array() on the php page and Array ( [posttimestampst] => 1399973296 [postobjNamest] => test2-1
print_r($_POST);
//when the if and else are used it the php page always echos Not Working, meaning that the $_POST is not set somehow. However, the html page shows the echoed variables in the "divResult" as it should.
//when I try the code without the if and else, the php page returns Undefined Index: posttimstamp/postobjNamest. However, the html page still shows the echoed variables.
if(isset($_POST["posttimestampst"])){
$timestamp = $_POST["posttimestampst"];
echo $timestamp;
echo "<br>";
$objName = $_POST["postobjNamest"];
echo $objName;
echo "<br>";
}
else{
echo "Not Working";
}
Any help is greatly appreciated!
EDIT:
//gets selected object from a dropdown menu
selectedObj = document.getElementById("selectObj").value;
//objName in javascript taken from $objName var in php that is and the beginning of the html page.
objName = <?php echo json_encode($objName); ?>;
//objInst takes the value of the dropdown menu and assigns it as the [] in objName array
objInst = objName[selectedObj];
//timestamp is set in php and imported to java
var timestamp = <?php echo $timestamp; ?>;
EDIT 2:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js""> </script>
</head>
<h3>Optionen und Berechnen</h3>
<form name="myForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div id="divCalc">
</div>
<input id="addObject" type="button" onclick="addObj()" value="Add Object">
<br>
<br>
<div id="divAddObj" hidden="true">
</div>
<br>
<div id="divCalc">
</div>
<div id="divResult"></div>
</form>
<script type="text/javascript" name="addObject">
var objName;
var selectedObj;
var objInst;
var timestamp = <?php echo $timestamp; ?>;
//Start select dropdown
var select_element = document.createElement("select");
select_element.setAttribute("id", "selectObj");
select_element.setAttribute("name", "selectObject");
options = new Array();
objName = <?php echo json_encode($objName); ?>;
for ( var i = 0; i < (<?php echo $arrayNum; ?>); i++ ){
options.push(new Option(objName[i], i, false, false));
}
options[0].selected = true;
for ( var option in options ){
select_element.appendChild(options[option]);
}
//End select dropdown
//check selected object
selectedObj = document.getElementById("selectObj").value;
objInst = objName[selectedObj];
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
</script>
Change your code to:
objNamest = objInst.value;
timestampst = timestamp.value;
$.post("sendCalc.php", {
postobjNamest: objNamest,
posttimestampst: timestampst },
function(data){
$("#divResult").html(data);
});
You are missing the data parameter of $.post().
From the docs about post():
data
Type: PlainObject or String:
A plain object or string that is sent
to the server with the request.
Your params postobjNamest & posttimestampst do not exist for the $.post() method
It should be
$.post("sendCalc.php", {
// An "on-the-fly" created JavaScript object, which is valid
data: {
postobjNamest: objInst,
posttimestampst: timestamp
},
function(data){
var content = $.parseJSON(data);
window.console.log(content.postobjNamest);
window.console.log(content.posttimestampst);
}
});
From the docs about parseJSON():
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
And in the PHP:
$objName = $_POST['postobjNamest'];
$timestamp = $_POST['posttimestampst'];
// Returning your values to client
// Don't echo them in PHP
echo json_encode(array(
'postobjNamest' => $objName,
'posttimestampst' => $timestamp
);
From the docs about json_encode():
json_encode — Returns the JSON representation of a value
The Javascript Object:
// Declaration
var Obj = {
propertyOne: 'value', // string
propertyTwo: 52.3654, // float
methodOne: function () {
// your function code
},
methodTwo: function () {
// your function code
}
}
//Instances
var objOne = new Obj();
objOne.methodOne();
objOne.propertyTwo;
var objTwo = new Obj();
objTwo.methodOne();
objTwo.propertyTwo;
In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.
I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.
(To simplify the example code, I left out the AJAX part and am using an alert instead.)
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var shelve = document.getElementById( 'books' );
var books = shelve.getElementsByTagName( 'li' );
for( var i=0; i < books.length; i++ ){
books[i].onclick = function(){
alert(books[i].title); //I know this doesn't work
};
}
}
</script>
</head>
<body>
<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>
<?php show_allBooks(); ?>
</body>
</html>
<?php
function show_allBooks(){
db_connect();
$query = "Select * from tblBooks order by title";
$result = mysql_query($query);
echo "<ul id='books'>";
while ($row = mysql_fetch_array($result))
{
echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
}
echo "</ul>";
db_close();
}
?>
I tried fooling around with variations of the following code, but this did not seem to work either.
books[i].getAttribute("title")
Can anyone point me in the right direction? Any help would be greatly appreciated.
By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = function () {
alert(this.title);
};
}
http://jsfiddle.net/gilly3/cPMAU/
However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:
function createBookHandler(books, i) {
return function() {
alert(books[i].title);
};
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = createBookHandler(books, i);
}
http://jsfiddle.net/gilly3/cPMAU/1/
Start with
books.item(i)
Then it depends how title is stored in the list. If its
<li title="">
then
books.item(i).getAttribute("title")
But the closure related answer is probably more important.