I would like put my code to javascript var like that :
function myFunction(){
var switch = document..(etc..)....style.backgroundcolour;
var somethink2 = 'red'; <----- I tell about it
switch = somethink2;
}
and after that my background colour will be switch after using function.
I can"t do that with PHP code (my code connection with sql database) becouse i have not got a " and '.
"dane" (in getElementByID()) in my code below is and i want put this PHP code inside this div.
Guys please help me :)
Regards!
function swap(){
var zawartosc =
<?php $a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
echo "<br>";
echo "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
echo "<tr>";
foreach ($row as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
document.getElementById("dane").innerHTML = zawartosc;
}
Something like this:
$a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
$html = [];
$html[] = "<br>";
$html[] = "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
$html[] = "<tr>";
foreach ($row as $field => $value) {
$html[] = "<td>" . $value . "</td>";
}
$html[] = "</tr>";
}
$html[] = "</table>";
$html = json_encode($html); //'["<br>","<table border='1'>", ...]'
?>
document.getElementById("dane").innerHTML = <?php echo $html;?>.join("\n"); //no quotes needed
//document.getElementById("dane").innerHTML = ["<br>","<table border='1'>", ...].join("\n");
Or you can just handle it like a normal string, but it's not what I would prefer to do.
$html = implode($html);
?>
document.getElementById("dane").innerHTML = "<?php echo $html;?>"; //careful with quotes here
In other words, don't output from PHP directly, instead build an array. It's much cleaner as you can consolidate that into a single variable and then use it.
For example:
//timeout for demonstration purposes
setTimeout(function(){
document.getElementById("dane").innerHTML = [
"<br>",
"<table border='1'>",
"<tr>",
"<td>foo</td>",
"<td>bar</td>",
"</tr>",
"<tr>",
"<td>biz</td>",
"<td>baz</td>",
"</tr>",
"</table>"
].join("\n");
},500);
table{width:100px;}
<div id="dane"></div>
I like using join (it's like implode) for multi line strings in JS (even in my plugins). In this case it works well with json_encode.
Basically we convert that array of HTML into a JSON string, which becomes a real Array in JS, then we let JS do the imploding with join. Mainly because arrays don't require the use of a quote, so this avoids any issues if we have quotes in our html.
Consider this (using just strings):
<?php
//HEREDOC
$html = <<<HTML
<table border='1' style="color:red;" >
HTML;
?>
document.getElementById("dane").innerHTML = '<?php echo $html;?>';
document.getElementById("dane").innerHTML = "<?php echo $html;?>";
Which becomes this:
document.getElementById("dane").innerHTML = '<table border='1' style="color:red;">'; //syntax error
document.getElementById("dane").innerHTML = "<table border='1' style="color:red;">"; //syntax error
From what I see you can get away with " at the moment, but if you put them in your HTML, you'll probably be in trouble (if your just using strings). Using join avoids this
document.getElementById("dane").innerHTML = ["<table border='1' style=\"color:red;\">"].join("\n"); //json_encode knows how to escape " for json.
Hope it helps!
Related
I am trying to make a SQL server table display pivoted in HTML using PHP.
The columns of the HTML table would be the content of the "CONCEPT" column of the SQL table and the content of the HTML columns would be the result of the "DATA" column of the SQL.
Not all records have the same number of "columns" that is, for example the serial number 12345 has the RAM column but the serial number 67890 does not, so the HTML table cell should appear as blank.
This is the tab delimited file: https://pastebin.com/sFJEHJLm
All the concepts of each article have a record with the same value as "LINE", but I don't know how to take advantage of this data to make the painting of the table.
I have tried to load each of the SQL columns in different PHP arrays and then cycle through the array by painting the HTML table but, at the moment a serial number that has a column arrives, the relationship of the results in the HTML table is lost With the correct column.
if ($_REQUEST['accion'] == "abrir_auditoria") {
$array_titulos = array();
$Total = 0;
$Actual = 0;
try
{
$sql = "SELECT * FROM AUDITORIAS_LIN WHERE AUDITORIA = '" . $_REQUEST['id'] . "'";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
if (!in_array(htmlspecialchars($r['CONCEPTO']), $array_titulos))
{
array_push($array_titulos, htmlspecialchars($r['CONCEPTO']));
}
endwhile;
echo "<table border=1>";
echo "<tr>";
foreach ($array_titulos as $titulo)
{
echo "<th>$titulo</th>";
}
echo "</tr>";
echo "<tr>";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$Total = key(array_slice($array_titulos, -1, 1, true));
while ($r = $q->fetch()):
if ($Total != $Actual)
{
echo "<td>" . htmlspecialchars($r['DATO']) . "</td>";
$Actual++;
} else {
echo "</tr><tr>";
echo "<td>" . htmlspecialchars($r['DATO']) . "</td>";
$Actual = 0;
}
endwhile;
echo "</tr>";
echo "</table>";
}
catch(PDOException $pe)
{
die("database connect error:". $pe->getMessage());
}
}
I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.
php file
<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$jaar .= "\"" . $row[0] . "\"";
$jaar .= ",";
}
$jaar{ strlen($jaar)-1 } = ']';
echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";
?>
<script src="js/calender.js"></script>
js file
//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]
//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want
Some changes required:
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
// create $jaar[]
$jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php
Read more:
json_encode()
I am making a cart-mechanism with jquery, ajax and php. The problem is that the text in the html element aren't getting appended to the session array. This is my ajax code:
$(document).ready(function(){
$("#cart").on("click", function(){
var name = $("#name").text();
var cost = $("#cost").text();
$.ajax({
type:"post",
data:"name="+name+"&cost="+cost,
url:"senddata.php",
success:function(data){
$("#info").html(data);
}
});
});
});
This is my html displayed with php:
function getData()
{
require_once('../config.php');
$query = mysqli_query($conn, "SELECT p_name, p_cost, p_pic, p_desc FROM products");
while($row = mysqli_fetch_assoc($query))
{
echo "<form><tr>";
echo "<td id='name' name='name'>" . $row['p_name'] . "</td>";
echo "<td id='cost' cost='cost'>" . $row['p_cost'] . "</td>";
echo "<td>" . $row['p_pic'] . "</td>";
echo "<td>" . $row['p_desc'] . "</td>";
echo "<td id='cart'><input type='button' id='submit' value='Add To Cart'></td><tr></form>";
}
mysqli_close($conn);
}
And finally, this is where I have stored the ajax variables in a session array:
session_start();
$_SESSION['cart_name'] = array();
array_push($_SESSION['cart_name'], $_POST['name']);
var_dump($_SESSION['cart_name']);
$_SESSION['cart_cost'] = array();
array_push($_SESSION['cart_cost'], $_POST['cost']);
var_dump($_SESSION['cart_cost']);
I am getting no error whatsoever but the items get appended to the array the first time, but after that, the variables don't get appended at all.
Variables does not appended because you initialize every time the
$_SESSION['cart_name'] = array();
$_SESSION['cart_cost'] = array();
That means that every time before you push the new data you empty the SESSION var.
The question might not really be clear because I could not think of something that could suit my problem, anyway, I am importing some mysql values using php and creating a html table using javascript, however I am having problems with the PHP as well as Javascript part, Also if anyone could tell me how I could just import values from MYSQL database and make a html table with it (That's basically what I am trying to do)
1.) PHP is not importing values from MYSQL correctly
2.) On console it says: "Uncaught SyntaxError: Unexpected token ILLEGAL"
The following is my code,
<?php
$con = mysqli_connect("localhost","root","","human_information");
$result = mysqli_query($con,"SELECT * FROM basic_human_info");
$rows = mysqli_num_rows($result);
$columns = mysqli_num_fields($result);
?>
<body>
<script type="text/javascript">
function createTable(){
var tBody = document.getElementsByTagName("body")[0];
var table = document.createElement("table");
table.style.border=1;
table.style.width='50%';
table.setAttribute('border',1);
var rows = "<?php echo $rows; ?>";
var columns = "<?php echo $columns ?>";
for(var i=0;i<columns;i++){
var tr = document.createElement("tr");
for(var j=0;j<rows;j++){
var td = document.createElement("td");
td.appendChild(document.createTextNode("
<?php
$sql = mysqli_query($con,"SELECT 'First Name' FROM basic_human_info");
echo mysqli_fetch_assoc($sql);
?>
"));
tr.appendChild(td);
}
table.appendChild(tr);
}
tBody.appendChild(table);
}
createTable();
</script>
</body>
You are outputting an array with echo (echo mysqli_fetch_assoc($sql);) which will just print Array in the middle of the Javascript. That leads to the Uncaught SyntaxError.
But the question rather is: Why use Javascript? Try it with HTML first until you get the PHP right, then do what ever you are planning to do with Javascript.
Like this you can try in php directly
while ($row = mysqli_fetch_array($stmt)) {
echo "<tr>";
echo "<td>" . $row["aid"] . "</td>";
echo "<td>" . $row["aname"] . "</td>";
echo "</tr>";
}
I have a table that third column of it is checkboxe, and first two columns of it come from database
I want to send the wordID of words that checked:
$result = mysql_query("SELECT * FROM words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
and in my function I have this:
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign=1;
}
else{
assign=0;
}
$.ajax({
url: "assigner.php",
type: "POST",
data: { wordid: wordid, assign: assign}
}).done(function( e ) {
/*alert( "word was saved" + e );*/
});
}
}
I dont know how can I get WordId from the first part and use it in second part that I said
Just put another form element outside of the table, like:
<input type="hidden" value="[id]" name="wordid_name" id="worid_id" class="wordid_class">
You only have to replace [id] with the id of the row, then on Javascript you can call the attribute you prefer:
var wordid= document.getElementsByClassName('worid_class').value;
var wordid= document.getElementsById('worid_id').value;
var wordid= document.getElementsByName('worid_name').value;
Can make it outside for structure, just below var boxex.
I recommend you to create an Javascript object with the values of the checkboxes and then call just 1 time to Ajax.
Hope it helps you.