I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
because my code works perfectly with:
<?php echo 'var oInner = document.createTextNode("Newoption");'; ?>
I don't know why createtextnode doesn't want to take my PHP var... I thought it could be a same origin policy since the database is located on a server outside my website.
I don't know.
You'll find enclosed the complete code:
In my HTML I have:
//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
<option value"France">France</option>
</select>
//Empty region list
<select name="regionm" id="regionm">
</select>
//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>
In my Javascript I have:
//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
var choixco = countrym.options[countrym.selectedIndex].value;
document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;
In my PHP region.php file, I have:
<?php
// Get my choice
$codepays = $_GET['choix'];
//Retrieve the regions corresponding to the country
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();
while($donnees)
{
// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);
?>
//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");
//Here is my big issue:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
oOption.value = "none";
oOption.appendChild(oInner);
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");
regionm.appendChild(oOption);
</script>
<?php
$donnees = $req->fetch();
}
$req->closeCursor();
exit();
?>
Have you tried simply oOption.innerHTML = '<?php echo $donnees["name"] ?>'; ?
I am suspecting that the indexed element cannot be found. But is all cases, this below should work.
<?php echo 'var oInner = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>
Found the solution: it was the php inserting \n so the solution is to do the following:
$desc= 'var oInner = document.createTextNode("'.$donnees["name"].'");';
$desc= str_replace("\n", "",$desc);
$desc= str_replace("\r", "",$desc);
Thanks everybody
Related
I am trying to create javascript variable from php, this is what i want to get.
<?PHP echo "var color_name=[<?PHP echo $color_name;?>]"; //var color_name=["Green","Pink"];
<?PHP echo "var style_name=[<?PHP echo $style_name;?>]"; //var style_name=["Basic","Classic"];
this is my predefined_attributes table
this is what i have tried,
<?php
$predifined_qry = "SELECT attribute_column_name
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columnNames = Array();
while ($predifined_result_row = mysqli_fetch_assoc($predifined_result)) {
$columnNames[] = $predifined_result_row['attribute_column_name'];
}
now i can get the attribute_column_name in an array using a foreach loop, but i dont know how to get the attribute_column_value array in a variable like this $style_name, $color_name. please help.
First of all, if you only need 1 column, and the resource/data you get is not massive, you could just fetch all and extract the column
You could expose your php variables in js through JSON
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
?>
<script>
var columnames = JSON.parse("<?= json_encode($columnNames); ?>");
</script>
So now if we add in the other field :
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
$columnValues = array_column($predifined_rows, 'attribute_column_value');
// array_combines uses the first array as the key and the second as the value
$columns = array_combine($columnNames, $columnValues);
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
Edit
as in the comments, a key can only appear once in a hashtable/array
so we need to generate an array of values per key
<?php
$predifined_qry = "SELECT attribute_column_name, attribute_column_value
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columns = [];
while($row = mysqli_fetch_assoc($predifined_result)) {
if(!array_key_exists($row['attribute_column_name'], $columns)) {
$columns[$row['attribute_column_name']] = [];
}
$columns[$row['attribute_column_name']][] = $row['attribute_column_value'];
}
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
1st : You need to select attribute_column_value column too
SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id
2nd : You need push both column value in two different array like this
while ( $predifined_result_row = mysqli_fetch_assoc($predifined_result) ) {
$color_name[] = $predifined_result_row['attribute_column_name'];
$style_name[] = $predifined_result_row['attribute_column_value'];
}
3rd : simple apply json_enocde and echo like this
<script>
var color_name=<?php echo json_encode($color_name); ?>;
var style_name=<?php echo json_encode($style_name); ?>;
</script>
$columnValues[] = $predifined_result_row['attribute_column_value'];
You can paste this code into your while loop
And dont't forget to get the need field form database:
$predifined_qry="SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id";
I am new with AJAX and JQuery. I am trying to use it to call two PHP scripts. I found some examples online but just to call functions. I am just trying to call the scripts so it will load everything on my main PHP file that will then be display on the screen the results withouth refreshing the page.
Here is the fiddle example, it works if I put all my PHP scripts in one file : http://jsfiddle.net/vw4w3ay5/
thanks in advance, your help is very much appreciated!
main_php file (where I want to call my other PHP scripts):
<div id="map_size" align="center">
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
display_desk.php (Script I want to call):
<?php
include 'db_conn.php';
//query to get X,Y coordinates from DB for the DESKS
$desk_coord_sql = "SELECT coordinate_id, x_coord, y_coord FROM coordinates";
$desk_coord_result = mysqli_query($conn,$desk_coord_sql);
//see if query is good
if($desk_coord_result === false) {
die(mysqli_error());
}
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
display_stationinfo.php(second script I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
echo "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
What about? :
<div id="map_size" align="center">
<?php
echo "<script>";
include "display_desk.php";
include "display_stationinfo.php";
echo "</script>";
?>
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
To be sure add $(document).ready(function(){
});
/EDIT/
Hum you want to use Ajax . did you try with :
$.post("yourURL.php",function(html){
/*here what you want to do*/
/*return of your script in html*/
});
I have two innoDB tables in my database named customers and vessels. I also have a form with 2 select boxes one having the column: company_name of table: customers as options, and the other having the column: vessel_name of table: vessels.
What i want to do is make the options of the 2nd select box populate according to the customer's company_name chosen in the 1st select box.
Finally please take into consideration that i am a complete newbie in Javascript and jQuery and thats why i am asking here how can i achieve the above result.
The form:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
The php to make the above form work :
<?php
// For customers
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if($pelat = $db->query($sqlpelates)) {
$pelates = array();
while($pelate = $pelat->fetch_object()) {
$pelates[] = $pelate;
}
$pelat->free();
}
// For vessels
$sqlploia = "SELECT * FROM vessels ORDER BY vessel_name";
if($plo = $db->query($sqlploia)) {
$ploia = array();
while($ploi = $plo->fetch_object()) {
$ploia[] = $ploi;
}
$plo->free();
}
?>
UPDATE: Below is the single .php page where i am trying to achieve the above result:
<?php
require 'db/connect.php';
//check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
$pelates = array();
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
}
// modify the query to filter out only what your ajax request wants
$where = $ajax ? ' WHERE company_name="'.$_POST['companyName'].'"' : '';
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
$ploia = array();
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
if ($ajax) {
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client wants to know
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="jquery.js">
// Your code goes here.
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://prinseapals-marine.com/filing/drop_down.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
</script>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
FINAL-UPDATE :
test.php:
<?php
require 'db/connect.php';
$cus = array();
if($cterm = $db->query("SELECT * FROM `customers`")) {
while($cterm2 = $cterm->fetch_object()) {
$cus[] = $cterm2;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form id="form1" name="myform">
<select name="selection" onchange="load('bdiv', 'test2.php');">
<?php
foreach($cus as $c) {
?>
<option value="<? echo $c->company_name ?>"><? echo $c->company_name ?></option>
<?php
}
?>
</select>
<div id="bdiv"></div>
</form>
</body>
</html>
test.js:
function load (thediv, thefile) {
// body...
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile+'?selection='+document.myform.selection.value, true);
xmlhttp.send();
}
test2.php:
<?php
require 'db/connect.php';
if (isset($_GET['selection'])) {
# code...
$selection = $_GET['selection'];
}
$ves = array();
if ($vterm = $db->query(
"SELECT `vessel_name` FROM `vessels` WHERE `company_name` = '$selection'")) {
while ($vterm2 = $vterm->fetch_object()) {
$ves[] = $vterm2;
}
} else {
echo 'Please type a customer name.';
}
?>
<select>
<?php
foreach($ves as $v) {
?>
<option value="<?php echo $v->vessel_name ?>" ><?php echo $v->vessel_name ?></option>
<?php
}
?>
</select>
This is not the first time I see this asked but I will dive in
Warning: this answer has javascript, with jQuery. I will also append a php file afterwards with some changes to allow the same script to be called for the ajax request
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://localhost/test/stackoverflow.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
The logic behind the js code is to allow user interaction. When the user makes a selection a request is fired to the server and the response is processed in the client and populates your 2nd <select>
Now, a modified version of your php script (warning: this works with the template I append next)
<?php
// your model, check for whitespaces outside php tags, do not allow output yet
require 'db/connect.php';
// check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// required for the template
$pelates = array();
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
} else {
// modify the query to filter out only what your ajax request wants
$where = ' WHERE company_name="'.$_POST['companyName'].'"';
// required for the ajax request
$ploia = array();
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client want's to know
exit;
}
?>
Next comes a modified version of your html template
<!DOCTYPE html>
<html>
<head>
<title>Your title</title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name"><?php
foreach($pelates as $p) echo '<option value="'.$p->company_name.'">'.$p->company_name.'</option>';
?></select>
<!-- leave empty, we will populate it when the user selects a company -->
<select name="vessel"></select>
</form>
<!-- add jQuery lib here, either your own or from a CDN; this is google's version 2.0.3 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- The code should be in a seperate file, load here if you want (but after jQuery lib) -->
<script src="your/javascript/file.js"></script>
</body>
</html>
Ok, now some pointers
you should be carefull with the php script I left there, there are other ways of doing what I intended which are cleaner and easier to maintain
the javascript is not the best, there are better solutions out there so be sure to check those out as well
If you do not understand parts of any of the scripts don't hesitate to ask
Beware any whitespace, do not allow any output before the php script, this is very important. All output should be left to the template
I hope this has been helpfull
Use ajax for this, Pass your company id to the javascript
<script>
function showCustomer(str)
{
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("myresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true); // Pass value to another page Here->test
xmlhttp.send();
}
</script>
<select name="company_name" onchange="showCustomer(this.value)">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<div id="myresult">
</div>
Now On test.php Simply Call Value & put select box,
<?php
$q = $_GET['q'];
// Here fetch values for particular q(company name)
// put select box
I am trying to pass $post; a variable created in a mysql query, to javascript function showDiv.
Currently this doesnt work.
$post = $row['id'];
?>
<script type="text/javascript">
function showDiv() {
var note = "<?php echo $post ?>";
document.getElementById("<?php echo $post; ?>").style.display = "inline";
}
</script>
<?php
$addnote = '<input type="button" value="addnote" onclick="showDiv()"><div id="'.$postid.'" style="display:none;" class="'.$postid.'"> WELCOME</div>';
But if I change $post to have a html value e.g
$post = '11';
then this code works.
I am novice in javascript so please be gentle,
Any help is greatly appreciated.
Thank you.
If you are in a loop, I think JS doesn't like redeclare your function "showDiv()". Try this :
$post = $row['id'];
$addnote = '<input type="button" value="addnote" onclick="showDiv('.$post.')"><div id="'.$post.'" style="display:none;" class="'.$post.'"> WELCOME</div>';
And the javascript NOT in the loop :
<script type="text/javascript">
function showDiv(note) {
document.getElementById(note).style.display = "inline";
}
</script>
check your $row['id'] if it's returning something.
<?php echo $row['id']; ?>
or check your source code.
your code might look something like
<script type="text/javascript">
function showDiv() {
var note = "";
document.getElementById("").style.display = "inline";
}
</script>
Assuming that: $post = $row['id'] has a value. You want var note to have a value of a string. JS wraps strings in single or double quotes. so wrap <?php echo $post ?> in a string like this:
var note = "'"+<?php echo $post ?>"'";
This will prepend and append the quotes around the $post value so that JS can recognize it as a string.
I want to change the innerHTML with PHP code. But I cannot get it to work, and I do not understand why. I want it to change some text on the page but from another file. And so I thought that I could use this:
document.getElementById ("page"). innerHTML = "<? php echo $ home?>";
But it does not work.
Here is my code:
<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
function ChangePage(page)
{
if(page == "home")
{
document.getElementById("page").innerHTML = "<?php echo $home ?";
}
}
</script>
There are many small typos. Try removing the space between $ and 'home' and before 'php'. This is the right statement:
document.getElementById ("page"). innerHTML = "<?php echo $home?>";
Also, where's your closing php tag?
<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
function ChangePage(page)
{
if(page == "home")
{
document.getElementById("page").innerHTML = "<?php echo $home; ?>";
}
}
</script>
Although this is a bad practice. Why would you want to do this instead of simply loading the php in the right place? Also, you do realize that 'page' should be the id of a pre-existing div in your html, right? Something like this would be better:
<html>
<body>
<div id = "page">
<?php echo file_get_contents("home.php"); ?>
</div>
</body>
</html>