Need to pass a variable from JS to php [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I want to create a title description for a chess eco code:
This is the lookup array in php named eco_codes:
<?php
$eco_tmp = array(
"A00" => "Uncommon Opening 1.g4, a3, h3, etc.",
"A01" => "Nimzovich-Larsen Attack 1.b3",
"A02" => "Bird's Opening 1.f4",
"A03" => "Bird's Opening 1.f4 d5")
?>
I have the lookup code (ex. GameECO = "A02") like this:
<span id="GameECO"></span>
What I want is this:
<?php $key = array_search($val['GameECO'], $eco_codes);?>
<span id="GameECO" title = "<?php echo $key.$val['ECO']></span>
How can I proceed? Is php even required for this? Maybe js alone would do it?
my page is http://communitychessclub.com/basic.php?game=5312

Assuming you have the code in some variable, have a js file (ecocodes.js) containing
var ecoCodes = {
"A00":"Uncommon Opening 1.g4, a3, h3, etc.",
"A01":"Nimzovich-Larsen Attack 1.b3",
"A02":"Bird's Opening 1.f4",
"A03":"Bird's Opening 1.f4 d5"
} // no comma after the last one
then you can use
<!DOCTYPE html>
<html>
<head>
<title>Chess</title>
<script src="ecocodes.js"></script>
<script>
window.onload=function() {
var eco = "A02";
document.getElementById("GameECO").innerHTML=eco + ":"+ecoCodes[eco];
}
</script>
</head>
<body>
ECO: <span id="GameECO"></span>
</body>
</html>
It works like this:
var ecoCodes = {
"A00":"Uncommon Opening 1.g4, a3, h3, etc.",
"A01":"Nimzovich-Larsen Attack 1.b3",
"A02":"Bird's Opening 1.f4",
"A03":"Bird's Opening 1.f4 d5"
} // no comma after the last one
window.onload=function() {
var eco = "A02";
document.getElementById("GameECO").innerHTML=eco + ":"+ecoCodes[eco];
}
ECO: <span id="GameECO"></span>

Related

Take line from .txt file and display in html page

I want to make a small project for my girlfriend and what I had in mind was to have an HTML page that says "I Love". On the press of a button the website would display under the text a random line from a text document I have made with all the things I love about her. Example:
What I managed
So I have managed to make a page with only the "I LOVE" and adding the text under it when I click the button. But I would like it to be able to take a random line from a .txt file where each line would be one line of text it would randomly choose and display on the html.
Thanks
You cant load from files on server from client side cuz that would be a huge no-no when it comes to security. Just imagine that. You need some back-end (server side) language like PHP.
Here is the most basic PHP code ( with comments ) that does what you want:
<?php
// you put your filename here ( obviously )
$fileName = "girl.txt";
// opening and reading file
$fileH = fopen( $fileName, "r") or die("Unable to open file!");
$fileCont = fread( $fileH,filesize( $fileName));
fclose($fileH);
// split text into lines
$lines = explode( "\r\n", $fileCont);
$numOfLines = count($lines);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- import math module -->
<script src=https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js></script>
</head>
<body>
<!-- prints random choice to html code -->
<h1>I Love</h1>
<button>Click Me!</button>
<script>
// print php array into js
<?php echo "lines = ['".join("', '", $lines)."'];\n"; ?>
maxLineNum = <?php echo $numOfLines; ?>;
// on button click you get random msg in h1
document.querySelector("button").addEventListener( "click", ()=>{
randNum = math.floor( math.random()*maxLineNum );
document.querySelector("h1").textContent = "I love " + lines[randNum];
} );
</script>
</body>
</html>
I am new to JavaScript, but I would try storing the snippets in an array in the JS itself rather than putting them in a separate text file than then needs to be accessed and processed before it can be used.
JS:
const niceSnippets = [
‘your smile’,
‘your sense of humour’, // repeat for as many snippets as you can think of
‘you’
];
const chooseSnippet = () => { niceSnippets[Math.floor(Math.random()*niceSnippets.length)]; }
const changeSnippet = () => { document.getElementById('snippetDisplay').innerText = chooseSnippet(); }
with the relevant elements in the HTML updated with id and onclick:
<p id=“snippetDisplay”></p>
<button onclick=“changeSnippet()”>Click Me!</button>

Data from mysql to php to javascript and html for use with chartist

I have a little project going to log temperatures and such to a MySQL database, and I'd like to provide for accessing that info from anywhere.
My initial crude attempt worked pretty well (simply a PHP file getting the MySQL data into an HTML table)
Now I'd like to use some pretty graphs in this project and I've failed despite many many many hours of googling.
Here's the PHP and js/HTML files.
(edit: removed all the mysql stuff to focus on the php->js connection)
this is the php file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php
$phpvar = ( {labels: ['One', 'Two', 'Three'], series: [[8, 13, 21]] });
$jsvar = json_encode($phpvar);
?>
</body>
</html>
Next, the js/HTML page where I'm trying to pull the data from the PHP script in so that it can be displayed using chartist...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
var sample= {
labels: ['One', 'Two', 'Three'],
series: [
[8, 13, 21],
[1, 2, 3]
]
}
var chart = new Chartist.Bar('.ct-chart', sample);
</script>
</body>
</html>
#T.Shah... Interestingly, this code does display a sample graph sucessfully...IF if remove the three lines 1 $.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);`
Leaveing those three line in however, breaks the whole page... even thought the jsvar variable isn't used in the chartist function. Not sure why that is.
This project is making it clear to me how little I've actually dabbled in web code before. If I can get a fingertip's worth of grip on what I'm missing, I'll pound away at this as much as needed.
Many thanks.
so this project has taught me just tons about javasript, php, and the rest of the webstack.
I’ll try to outline the answer to my original question in case someone else finds this via google.
First, getting data out of mysql using php was pretty easy. Here’s that code…
Setting up a convenient set of variables…
<?php
$hostname = "localhost";
$username = “mysqladminusername”;
$password = “mysqladminpass”;
$db = “tablename”;
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
?>
then pulling the data….
<?php
set_time_limit (60); //needed to prevent timeout error mysql reports the unlimited script takes ~30sec
$query = mysqli_query($dbconnect, "SELECT * FROM tablename ORDER by idcolumnname DESC limit 2000")
or die (mysqli_error($dbconnect));
?>
Then reading the data and putting into an html table…. and creating php arrays with the contents of each mysql column.
<?php
while ($row = mysqli_fetch_assoc($query)) {
echo
"<tr>
<td>{$row[‘col1name’]}</td>
<td>{$row[‘col2name’]}</td>
<td>{$row['col3name’]}</td>
<td>{$row[‘col4name’]}</td>
</tr>\n";
$phpcol1[] = $row[‘col1name’];
$phpcol2[] = $row[‘col2name’];
$phpcol3[] = $row[‘col3name’];
$phpcol4[] = $row[‘col4name’];
}
?>
At this point the php arrays are formatted as normal php “associative arrays”… something like this….
array(10) { [0]=> array(1) { [“col1name”]=> string(3) "658" } [1]=> array(1) { [“col1name”]=> string(3) "657" } [2]=> array(1) { [“col1name”]=> string(3) "658" }
….which is not very useful since chartist doesn’t understand it.
So we need to convert it to the format chartist expects, e.g. [232,345,4545,343,235,32]
(keep in mind that this array is one of two that chartist requires, it needs an array of “labels” and an array of “series”… and then the chartist demo code puts those together and uses them in the final bit of code that actually creates the chartist graph.)
We do this conversion using json encoding.
This can be done in stages, using variables to separate the code for readability, or as a oneliner for compactness.
The compact version is the method I chose in the end.
e.g….
<script type=“text/javascript”>
var jsonlabelsdatavariable = <?php echo json_encode($phpcol1) ?>;
var jsonseriesdatavariable = <?php echo json_encode($phpcol2) ?>;
//comment…here I found it useful to print the formatted array data to the screen so I could see the change with my eyes. To do this, I created an html dviv element like this….
<div class="container" id=“showmethedata”></div>….
in the body of the html page then I put the array data in with the following code…
document.getElementById(“showmethedata”).innerHTML
//comment… while I was testing this, I used placeholder data in the chartist demo code so that I could switch back and forth between the working demo code, and the broken custom code, and use developer tools to see the problems. so below you’ll see that the chartist demo code starts out filled with my placeholder data, then gets emptied out, and then overwritten with the real data from the json variable.
//This is the chartist demo code…..(notice the line feed, I was testing for characters that would break the chartist display, since a problem I had at that time was all the label data being shown in one point of the graph. Turns out this problem was not from bad characters, but that I was pushing my label data into a single label array element.
var data = {
labels: ['2222-02-13_09:12:00','2018-02-13_09:11:00','2018-02-13_09:10:00','2018-02-
13_09:09:00','2018-02-13_09:08:00'],
series: [
[5,2,4,2,0]
]
};
//Now I blank the placeholder arrays…
data.labels.length = 0;
data.series.length = 0;
//now I fill the arrays with the real data…note that two methods are used. this is due to the formatting that chartist expects… the labels array is a single array with elements… while the series array contains an inner array, and that inner array contains the elements. using the push method on the labels array resulted in the labels array being shows as a label for a single data point on the graph.
data.labels = data.labels.concat(jsonlabelsdatavariable);
data.series.push(jsonlight);
//finally we can build the chartist graph…
new Chartist.Line('.ct-chart', data, { width:10000, showArea:true, reverseData: true, });
//and lastly, we close the javascript tag.
</script>
I’ll also note i woulnd up using a few custom functions that edited the contents of my php array elements to do things like remove spaces, add or remove quote marks around each element, etc… but i don’t think any of that was actually necessary.
e.g.
function addquotes ($element){
return "'{$element}'";
}
$withquotes = array_map("addquotes", $sourcearray);
function killspace ($anothersourcearray){
return str_replace(' ' , '_', $anothersourcearray);
}
$phpkillspace = array_map("killspace", $anothersourcearray);
$unspecial = preg_replace("/[^a-zA-Z 0-9]+/", "", $finalsourcearray );
What an adventure.
Cheers!
I was flowing #David 's code and had problems in few spots, so for reference, here is my complete code:
<?php
//here is connection information
require "cont.php";
$db = db_connect();
$upit = "SELECT * FROM (
SELECT * FROM meteo LIMIT 1000
) sub
ORDER BY id ASC";
$rezultat = mysqli_query ($db, $upit);
db_disconnect($db);
$label = array();
$series = array();
if ($rezultat != null)
{
$i = 0;
$j = 0; //vairable for sciping few database enteries.
while($red = mysqli_fetch_assoc($rezultat))
{
$j++;
if ($j == 1)
{
$t = date_create($red['at']);
$label[$i] = date_format($t, 'H:i');
$series[$i] = array($red['dht_temp'], $red['bmx_temp']);
//$series[$i] = array($red['id'], $red['dht_temp'], $red['bmx_temp'], $red['hum'], $red['press'], $red['w_speed'], WindDirectionToString($red['w_dir']));
$i++;
}
// how meny entries to scip
if($j == 10) {
$j = 0;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script type="text/javascript">
var data = {
labels: <?php echo json_encode($label) ?>,
series: <?php echo json_encode($series); ?>
};
var options = {
width: 1000,
height: 500
};
new Chartist.Line('.ct-chart', data, options);
</script>
</body>
</html>
You need to make sure that '100.php' file return data in the format that chartist expects. If you can make sure of that, then your html file could be like this. Then remove the random data part.
<!DOCTYPE html>
<html>
<head>
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('100.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
// jsvar = {
// // random test data just to build a visible chart
// labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
// // random test data just to build a visible chart
// series: [
// [5, 2, 4, 2, 0]
// ]
// };
// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
new Chartist.Bar('.ct-chart', jsvar);
});
</script>
</body>
</html>

I want to check if parameter exist as an id in the body. how can I do that without hardcoding and using jquery? Javascript [duplicate]

This question already has answers here:
How to append text to a div element?
(12 answers)
Closed 5 years ago.
<a id="Param">This is an html element</a>
<script>
function Append(param1,text)
{
if(document.getElementById(param1))
{
return document.getElementById(param1)+text;
}
else
{
console.error("the element was not found");
}
}
var app1=Append("Anything",". yes"); //i called the append twice first is to see the output when false
var app2=Append("Param",". hi")//second is to see the output when true. I want the output to be "This is an html element. hi"
this is the code that I have. I wanted to have a function that uses two parameters. The first one is to for an html element id and the second one is for the text that will be appended to the first parameter. How can the function check if "Param" is an id without hard coding or using jquery?
A string-query might be your best bet by making the PARAM dynamic and you can change it based on what the url passes to the script. index.php?param1=myvalue
Here is a reference article I used last time I had to do it myself: https://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/
Respectfully,
SFR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab Test 1</title>
</head>
<body>
<a id="Param">This is an html element</a>
<script>
function appendToElement(p1,p2)
{
var el=document.getElementById(p1);
if(el)
{
el.innerHTML+=p2;
return true;
}
else
{
console.error("Element with ID: "+p1+" not found");
return false;
}
}
var app1=appendToElement("Anything",". yes");
var app2=appendToElement("Param",". hi")
</script>
</body>
</html>
This is the code that I got from my professor.

Scrape html with js

I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.

How to remove <script> tags from an HTML page using C#?

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
</head>
</html>
Is there a way in C# to modify the above HTML file and convert it into this format:
<html>
<head>
</head>
</html>
Basically my goal is to remove all the JavaScript from the HTML page. I don't know what is be the best way to modify the HTML files. I want to do it programmatically as there are hundreds of files which need to be modified.
It can be done using regex:
Regex rRemScript = new Regex(#"<script[^>]*>[\s\S]*?</script>");
output = rRemScript.Replace(input, "");
May be worth a look: HTML Agility Pack
Edit: specific working code
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string sampleHtml =
"<html>" +
"<head>" +
"<script type=\"text/javascript\" src=\"jquery.js\"></script>" +
"<script type=\"text/javascript\">" +
"if (window.self === window.top) { $.getScript(\"Wing.js\"); }" +
"</script>" +
"</head>" +
"</html>";
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(sampleHtml));
doc.Load(ms);
List<HtmlNode> nodes = new List<HtmlNode>(doc.DocumentNode.Descendants("head"));
int childNodeCount = nodes[0].ChildNodes.Count;
for (int i = 0; i < childNodeCount; i++)
nodes[0].ChildNodes.Remove(0);
Console.WriteLine(doc.DocumentNode.OuterHtml);
I think as others have said, HtmlAgility pack is the best route. I've used this to scrape and remove loads of hard to corner cases. However, if a simple regex is your goal, then maybe you could try <script(.+?)*</script>. This will remove nasty nested javascript as well as normal stuff, i.e the type referred to in the link (Regular Expression for Extracting Script Tags):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
<script> // nested horror
var s = "<script></script>";
</script>
</head>
</html>
usage:
Regex regxScriptRemoval = new Regex(#"<script(.+?)*</script>");
var newHtml = regxScriptRemoval.Replace(oldHtml, "");
return newHtml; // etc etc
This may seem like a strange solution.
If you don't want to use any third party library to do it and don't need to actually remove the script code, just kind of disable it, you could do this:
html = Regex.Replace(html , #"<script[^>]*>", "<!--");
html = Regex.Replace(html , #"<\/script>", "-->");
This creates an HTML comment out of script tags.
using regex:
string result = Regex.Replace(
input,
#"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|\n|\s)*?>",
string.Empty,
RegexOptions.Singleline | RegexOptions.IgnoreCase
);

Categories