select echo from PHP not working - php

I have an echo from a PHP script which is this:
echo "<select class='form-control' id='backgroundcolor' onchange='uploadFile()'>";
foreach($backgroundcolors as $cc => $name) {
echo '<option value="' . $name . '">' . $cc . '</option>';
}
echo "</select>";
It returns the following:
<select class='form-control' id='backgroundcolor' onchange='uploadFile()'><option value="#CD5C5C">Indian Red</option><option value="#000000">Black</option></select>
I then use the following code to add it to a div:
_("backgroundcolor").innerText = event.target.responseText;
Where I have defined the following function _:
function _(el) {
return document.getElementById(el);
}
BUt instead of giving me a select option it just shows the html in plain text on the site. If I copy the code and paste it to my site manually it works.

Use innerHTML instead of innerText:
_("backgroundcolor").innerHTML = event.target.responseText;
innerText adds the content as plain text, while innerHTML adds the content as it is without encoding html characters.

You can use _("backgroundcolor").innerHTML = event.target.responseText; But if you are using jquery, you can also use $('#backgroundcolor').html(event.target.responseText); without those function above (function _(el)).

Related

Include a PHP page based on URL retrieved from an SQL database using Ajax

I have a page, index.php, with <select> <options> which act as filters. Through Ajax, information is retrieved from an SQL database and echoed into a <div> on the same page. One of the fields that is echoed contains the URL to another page such as a1701.php. Thus far, everything works perfectly.
However, rather than having the URL displayed, I would like the content of the page e.g. a1701.php to be displayed in the same way it would be if I had used <?php include 'a1701.php' ?>.
I have read a lot of posts on SO but haven't found any describing this situation (maybe I am looking for the wrong thing in which case please advise). Following the advice of other partially-related posts, I have tried several things including:
using absolute rather than relative links with $_SERVER['DOCUMENT_ROOT']
include 'a1701.php'; vs echo "<?php include 'a1701.php'; ?>"
using < instead of < etc.
reloading specific <div>s (I haven't actually tried this because I can't figure out what code I would have to put where to make it work.)
I have tried more than one URL and have checked that each one is correct.
index.php
<script>
function filterQuestions() {
var selectCount = document.getElementsByTagName("select").length;
var str = [];
for (var i = 0; i < selectCount; i++) {
if (document.getElementsByTagName("select")[i].value != "") {
str[i] = document.getElementsByTagName("select")[i].name+"="+document.getElementsByTagName("select")[i].value;
}
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("questionList").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","filter.php?"+str.join("&"),true);
xmlhttp.send();
}
</script>
<select name="branch" onchange="filterQuestions()">
<option value="All">All branches</option>
<option value="Number">Number</option>
<option value="Trigonometry">Trigonometry</option>
</select>
<select name="topic" onchange="filterQuestions()">
<option value="All">All topics</option>
<option value="sinrule">Sine Rule</option>
<option value="cosrule">Cosine Rule</option>
</select>
filter.php
<?php
$branch = $_GET["branch"];
$topic = $_GET["topic"];
if($branch != "All") {
$wherefilter[] = "branch = '".$branch."'";
}
if($topic != "All") {
$wherefilter[] = "topic = '".$topic."'";
}
$where = join(" AND ", $wherefilter);
if($where != NULL) {
$where = " WHERE $where";
}
mysqli_select_db($link,"generator");
$sql="SELECT question_name, url FROM questions".$where;
$result = mysqli_query($link,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['question_name'] . "</td>";
echo "<td>" . $row['url'] . "</td>";
echo "</tr>";
$pagelink = $row['url'] . '.php'; /* URL is correct */
echo"<br>";
echo $pagelink;
echo"<br>";
echo "<?php include '" . $pagelink . "'; ?>";
echo "<br>";
echo "<?php include '" . $pagelink . "'.php; ?>"; /* doesn't work */
include $pagelink; /* doesn't work */
}
echo "</table>";
mysqli_close($link);
?>
a1701.php
contains the content I want included. I have tried including other content too.
Is there a way to achieve what I am after? Am I heading in the right direction?
I can think of 2 ways to accomplish this.
If the PHP file is always on the same server and is part of the web app, just include it. You would have to do some checking and validation to ensure that the file is there etc.
If the URL points to anywhere on the internet, insert it as an iframe.
Solution 1 (everything is local)
Assuming there is some function called getPhpFileName that returns the name of the PHP file. You need the actual name of the php file, not the url pointing to it. The file is read directly from the file system, not through the web server.
$phpFile = getPhpFileName($row['url']);
if ( file_exists($phpFile) ) {
#include $phpFile;
}
example1.php (this is the file to be included)
<div>Hello Example1</div>
Solution 2 (iframe)
In this case, the iframe is returned and the browser will be responsible for getting the output from the url and inserting it on the page.
<iframe src="<?=$row['url']?>"></iframe>

Modify PHP file Using jQuery $.post

I'm trying to add a value from a selected in my html into a PHP file using jQuery. I have 2 php file, chainmenu.php and function.php. function.php contain 2 functions to get some data from my database. chainmenu.php is used to show the result of a function from function.php. It requires a variable, that is a value from selected option in my html. I was able to retrieve the value, but my problem is that my $.post function doesn't work. I dont know where is the error, is it in my chainmenu.php or in my function.php.
This is my code
jQuery CODE
<script type="text/javascript">
$(document).ready(function() {
$("select#trafo").attr("disabled","disabled");
$("select#gi").change(function(){
$("select#trafo").attr("disabled","disabled");
$("select#trafo").html("<option>wait...</option>");
var id = $("select#gi option:selected").attr('value');
$("select#trafo").html("<Option>"+id+"</Option>");
$.post("chainmenu.php", {id:id}, function(data){
$("select#trafo").removeAttr("disabled");
$("select#trafo").html(data);
});
});
});
</script>
Function.php
<?php class SelectList
{
//$this->conn is working fine here
public function ShowGI()
{
$sql = "SELECT * FROM gi";
$res = mysqli_query($this->conn,$sql);
if(mysqli_num_rows($res)>=1){
$category = '<option value="0">Pilih GI</option>';
while($row = mysqli_fetch_array($res))
{
$category .= '<option value="' . $row['idgi'] . '">' . $row['namegi'] . '</option>';
}
}
return $category;
}
public function ShowIt()
{
$sql = "SELECT * FROM It WHERE idgi=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Choose/option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['idIt'] . '">' . $row['name'] . '</option>';
}
return $type;
}
}
$opt = new SelectList();
?>
chainmenu.php
<?php include "/opsi.class.php";
echo $opt->ShowIt(); ?>
HTML Code
<head>
<!-- the script here -->
</head>
<body>
<select id=gi>
<option value="0"> Select </option>
</select>
<select id=It>
<!-- chainmenu.php result should be here -->
</select>
</body>
This explanation a little bit messy, but i hope anyone could help me and give me some good advice.
Thank you.
try like this in chainmenu.php
<?php include "/opsi.class.php";
echo $opt->ShowIt($_POST['id']); ?>
in function.php replace ShowIt() method like below,
public function ShowIt($id)
{
$sql = "SELECT * FROM It WHERE idgi=$id";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Choose/option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['idIt'] . '">' . $row['name'] . '</option>';
}
return $type;
}
There are a few typos in ShowIt() function for e.g $type = '<option value="0">Choose/option>'; the tag isn't closed properly.
In the jquery code you are retrieving the value and adding the html to select tag having id trafo. whereas in html code the id of the select is It.
<select id=It>
<!-- chainmenu.php result should be here -->
</select>

Option on dropdown as anchor

I am pulling out record from the database and inserting them inside a dropdown like this:
echo "<select>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option>" . $drow['id'] . "</option>";
}
echo "</select>";
It works but I need to be able to click on an option on the dropdown and make it link just like:
Record1Here
Record2Here
Record3Here
UPDATE: Latest code:
<script>
function doSomething() {
var currentval = this.options[this.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
</script>
...
echo "<select onchange='doSomething();'>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option value=\"view.php\">" . $drow['id'] . "</option>";
}
echo "</select>";
You can't place anchors on an option within a select list.
What you can do is use JavaScript and then do something on the change event of the select list :
echo "<select onchange='doSomething(this);>';
then in JavaScript do something based on the selected value :
function doSomething(elem) {
var currentval = elem.options[elem.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
Example here
you could update your PHP code to include a value in each option :
echo "<option value=\"urlhere.php\">" . $drow['id'] . "</option>";

String from array not working when passed to JS

The following works well:
var options = '<select><option value ="Unknown">Unknown</option><option value ="Yes">Yes</option><option value ="No">No</option><option value ="Both">Both</option></select>';
alert(options)
However, if that string is produced via a PHP foreach, the variable options is not recognized, hence I cannot use with JS. For example:
<?php foreach($pickListFields as $field_id => $options): ?>
<?php
$options_array = explode("\n", $options);
$options_select = '<select>';
foreach($options_array as $k => $option) {
$options_select .= '<option value ="' . $option . '">' . $option . '</option>';
}
$options_select .= '</select>';
?>
var options = '<?= $options_select ?>';
<?php endforeach; ?>
The above variable options produced, does not work, even though when I see the source code with Firefox I can see that var options is:
var options = '<select><option value ="Unknown">Unknown</option><option value ="Yes">Yes</option><option value ="No">No</option><option value ="Both">Both</option></select>';
Why then it cannot be used, if it is the same as the first example? I cannot alert that, or assign it to a field, but I can with the first example.
You are using php tags inside php instead of javascript tags:
var options = '<?= $options_select ?>';
should be:
echo '<script language="javascript" type="text/javascript">var options="' . $options_select . '";</script>';
try maybe html encode all output options, there can be some special chars hidden somewhere

Write to javascript array within php loop

I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.

Categories