I want to change the content in javascript of a textbox while using PHP.
If I change it with plain Text as:
echo "<script> var test = 0; simplemde.value('test');
test+= 5; alert(test);</script>";
it works. But with a php-Variable it isn't working any longer:
echo "<script> var test = 0; simplemde.value('$markdown');
test+= 5; alert(test);</script>";
Not sure what I'm doing wrong. If I open the site and watching the source-text it stands in the correct form there but It isn't in the box.
Here is my full code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./css/markdown.css">
<script src="./js/markdown.js"></script>
</head>
<body>
<textarea id="myID">
</textarea>
<script>
var simplemde = new SimpleMDE({
element: document.getElementById("myID"),
spellChecker: false,
});
</script>
<?php
require_once './Michelf/Markdown.inc.php';
use \Michelf\Markdown;
require_once 'loader.php';
$json_a = load();
if(count($json_a) > 0)
{
$text = $json_a[0]['blog'];
echo "found";
}
else
echo "not found";
$markdown = Markdown::defaultTransform($text);
echo $markdown;
echo "<script> var test = 0; simplemde.value('test'); test+= 5;
alert(test);</script>";
echo "<script> var test = 0; simplemde.value('$markdown');
test+= 5; alert(test);</script>";
?>
</body>
</html>
Things your question is missing:
The value of $markdown
The resulting JS you get for running the PHP
The error messages displayed on your browser's Developer Tools console.
That said, we can make some assumptions.
Markdown is a text markup language designed to write documents in something that looks a lot like plain text. One of its key features are new lines (used to delimit paragraphs).
Literal new line characters are not allowed in JavaScript string literals.
(Even without those assumptions, it is reasonable to say (for any answer to a question about replacing a string literal with some unspecified text):)
You need to escape or otherwise encode characters in $markdown that have special meaning.
The easiest way to do this is to take advantage of JSON being more-or-less the same as JS literal syntax.
$js_string = json_encode($markdown);
echo "<script> var test = 0; simplemde.value($js_string);
test+= 5; alert(test);</script>";
Note that $js_string gets quotes of its own, so you don't need to manually include them when outputting the variable.
Related
When I run this code, the alerts fail to display the values and instead an empty alert box pops up.
<?php
$x = 20;
$y = "Hello World!";
$list = array();
$list[0] = "January";
$list[1] = "February";
$list[2] = "March";
$list[3] = "April";
$list[4] = "May";
?>
<script type="text/javascript">
alert("JS code executed");
alert(<?php $x ;?>);
alert(<?php echo $list[3];?>);
</script>
First, you aren't echoing $x.
Second, you need to quote the string for JavaScript, so:
alert("<?php echo $list[3]; ?>");
would work.
You should use your Browser's Development tools to see what is happening with you javascript.
If you look at Console, you will see something like:
Uncaught ReferenceError: April is not defined
This is because you forgot putting Quotes on your script, also you forgot to echo the $x. The right code is:
<script type="text/javascript">
alert("JS code executed");
alert("<?php echo $x ;?>");
alert("<?php echo $list[3];?>");
</script>
#Slaks said that this code have an XSS vulnerability, but this depends on if the origin of your $x and $list variable is safe or not.
With scandinavian letters and when encoding them, I have a problem. With code below, javascript add some extra encoding to variable
<script>
function doit(params) {
var url = "/linkto/code.php" + params;
window.open(url,"Doit","width=750, height=600");
}
</script>
<?php
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
echo 'Do it!'; // link to page
?>
When changing code above to php, changed does not happened and problem go away.
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
// link to page
echo '<a href="/linkto/code.php"'.$param.'>Do it!</a>';
Hi all again,
I cannot make it work, no difference between utf-8 or iso-8859-1.
Result is something else, when using javascript-function or direct link.
You can try it here:
http://www.ajl.fi/tmp/test.php
Here is codes:
test.php:
<script type="text/javascript">
function doIt(params) {
var url = "doit.php" + params;
window.open(url,"doit");
}
</script>
<?php
$var1 = 'pähkinä';
$var1 = urlencode($var1);
echo sprintf("Do it - call",$var1)."<br>";
echo sprintf("Do it - link",$var1);
?>
and here is doit.php:
<?php
var_dump($_GET);
?>
In ist code, you have two issues in this code
1) Short tag will not work inside the <?php ?> here:
echo 'Do it!'; // link to page
2) You forgot to add quotes here:
window.open(url,"Doit",width=750, height=600"); //missing quote here
Modified Code:
<?php
$var1 = 'p%E4hkin%E4';
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
?>
Do it!
<script type="text/javascript">
function doit(params) {
var url = "/linkto/code.php" + params;
console.log(url);
window.open(url,"Doit","width=750, height=600");
}
</script>
I answer to myself - Solved.
IE, Edge and Chrome, all working ok on both cases. Firefox has a problem. When using
Do it!
result is not correct, but when using
Do it!
seems to work on all browsers
I have php inside javascript, and I made a query inside php, but the query cannot be fetched even in php area itself, why?
I have tried that query in PHPmyAdmin manually and it works fine. The "ca" field value is 1 not 0, but after i apply on code the result of "ca" is 0. What is wrong exactly? And there's no error message shows in console log.
image:
simple code:
<?php
include('ckcon.php');
include('logincheckmember.php');
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
</style>
<script>
function kampret(){
var ssloginmember = document.getElementById('id1').textContent;
var ambilun = document.getElementById('id2').textContent;
<?php
$ssloginmember=ssloginmember;
$ambilun=ambilun;
$q=mysql_query("SELECT COUNT(ai) AS ca,unnum FROM t_follow WHERE username='$ssloginmember' AND username2='$ambilun'");
$f=mysql_fetch_object($q);
$unnum2=$f->unnum;
$ca=$f->ca;
if($ca==0){
$status='follow';
$unnum=0;
}else{
$status='unfollow';
$unnum=$unnum2;
}
?>
var status='status = '+<?php echo json_encode($status);?>;
var unnum='unnum = '+<?php echo json_encode($unnum);?>;
var output1='output1 = '+<?php echo $ssloginmember;?>;
var output2='output2 = '+<?php echo $ambilun;?>;
document.getElementById('status').innerHTML = status;
document.getElementById('unnum').innerHTML = unnum;
document.getElementById('output1').innerHTML = output1;
document.getElementById('output2').innerHTML = output2;
}
</script>
</head>
<body>
<div id="status">status</div>
<div id="unnum">unnum</div>
<div id="output1">output1</div>
<div id="output2">output2</div>
<br>
<button onClick="kampret()" >button</button><br>
<br>
<div id="id1">melisavirgi</div>
<div id="id2">ririnputrian</div>
<br>
<?php
echo "ssloginmember=$_SESSION[ssloginmember]";
?>
</body>
</html>
result:
The problem seems to be that you are trying to get a javascript value in the PHP, ie $ssloginmember=ssloginmember;.
The PHP code is run before the page is loaded in the browser and generates parts of your javascript code. Your script seems to be acting as if it is run every time the javascript function is called, and as if both languages are the same.
AJAX is probably going to be your best solution - post the data to a PHP script that returns the values you need.
I suspect you may need to brush up on the difference between client side and server side code, too.
I know this topic was already discussed a few times but I can't seem to find what I'm doing wrong.
What I'm trying to do:
The user types in a number and by clicking on the button creates a table with that number of columns.
Heres the php:
<?php
$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password = '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
echo $twig->render('index.html', array());
$numOfRows = 1;
if(isset($_POST['button'])){
$numOfRows = $_POST['num_input'];
}
html/javascript:
<html>
<head>
<script>
function insertRows(){
var numOfRows = <?php echo json_encode($numOfRows) ?>;
var out = "<table><tr><th>test</th>";
for (i = 0; i < numOfRows; i++){
out += "<th>test</th>";
}
out += "</tr></table>";
document.getElementById("table").innerHTML = out;
}
</script>
</head>
<body>
<form action="index.php" method="post">
<textarea id="num_input" name ="num_input"></textarea>
<button type="button" name="button" onclick="insertRows()"> Go </button>
</form>
<p id="table"></p>
</body>
</html>
Theres no error or anything since I'm not using a IDE, just doing it in vim but the error is that is just doesn't happen. If i change "numOfRows" in the for loop to a number it works, so I'm pretty sure the json_encode is the problem.
Thanks!
EDIT:
Just to test it, I used a string variable $str = "test"; the php file, and instead of using the for loop, I just edited javascript to
var str = <?php echo json_encode($str); ?>;
alert(str);
and I also tried
var str = <?php echo $str; ?>;
alert(str);
but nothing works.
json_encode is not necessary in this case.
Simply replace
var numOfRows = <?php echo json_encode($numOfRows); ?>;
with
var numOfRows = <?php echo (int)$numOfRows; ?>;
Edit: You are missing a ; on the
<?php echo json_encode($numOfRows) ?>
Should be
<?php echo json_encode($numOfRows);?>
And in these cases, if would be good to check the server log, this will automaticly make you better at finding these mistakes yourself.
You are mixing up ints and strings. The database will in PHP always return strings and the way you are using the variable as an int in a for loop.
The following change i believe would achieve the right result.
$numOfRows = intval($_POST['num_input']);
Where you use PHP's conversion to integer function there is at a global level.
You did not forget any $. JS does not need $ for variables.
As far as your json_encode is concerned, if you are just passing an integer from PHP to JS, there is no need to json_encode. Just pass the variable to JS as <?=$numOfRows?> in the JS source.
I am currently trying to pass in PHP array to a javascript Function through onload();
In my SimilarDomains.php:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
I do this to pass it as a string object in order to later process the string using JSON.parse(). In the javascript i have
var obj = JSON.parse(domainsJS);
for string processing. But it seems like I have a SyntaxError: syntax error # line 1. This is the HTML Doctype. If I remove the doctype, it just goes to the next first line. it only appears when I have the body onload calling php as I did.
How can I process this php array in order to be used in JavaScript. After all this is said and done, I then have to input the processed values into a JS array.
Here is what the body onload turns out to be in the HTML
<body onload="init("{"0":"estatelawyer.com","1":"reaestatelawyer.com","2":"estately.com","3":"thestate.com","4":"estaterescue.com","5":"boisestate.edu","10":"99acres.com","11":"1point3acres.com","14":"green-acres.com","22":"backcountry.com","24":"baby-kingdom.com","25":"landattorney.com","27":"siteground.com","28":"247realmedia.com","30":"siteground.biz","31":"arealme.com","32":"farming-simulator.com","33":"amkingdom.com","34":"searchengineland.com","35":"shoretelsky.com","36":"grantland.com","38":"amsoil.com","40":"lostrealm.ca","41":"kingdomofloathing.com","42":"shorewest.com","44":"domaintools.com","45":"domain.com.au","46":"realmadridstream.net","47":"farming2015mods.com","48":"travelandleisure.com","49":"landofnod.com","51":"bringmesports.com","52":"cricketcountry.com","53":"bringthebaconhome.com\/user\/dashboard","54":"ollando.com","55":"domain.com","57":"travelandlearntrips.com","58":"scarffruit.country","59":"78land.com","92":"propertylawyer.com","93":"propertylawyergroup.com","94":"propertyattorney.com","95":"rocketlawyer.com"}");">
You should just need to echo it straight up without any extra quotes because it's a JSON object
<body onload="init(<?php echo $domainsJS ?>);">
Add the json to a var in the JS
echo <<<EOT
<script type="text/javascript">//<![CDATA[
var jsn = " . json_encode($similarDomainsUnique);
var obj = JSON.parse(domainsJS);
//]]>
</script>
EOT;
This is poor coding:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
There is no reason to be jumping back and forth from PHP mode to HTML mode.
There is PHP overhead to each time you change modes.
Below is the basic proper way to create an HTML page.
I like to get the HTML on its way to the Browser ASAP. That is why I flush the output buffer somewhere just after the <body> tag and the Browser will have a few things to do preparing for Start Render.
To accomplish your passing json to <javascript> I assign the value to $js then embed $js in the `
And PHP is never switched to HTML mode.
<?php ob_start("ob_gzhandler");
header('Content-Type: text/html; charset=utf-8');
header('Connection: Keep-Alive');
header('Keep-Alive: timeout=50, max=100');
header('Cache-Control: max-age=3600');
echo <<<EOT
<!DOCTYPE html>
<html lang="en">
<head><title>Sample</title>
<style>
body{font:400 1emArial,sans-serif;color: #f00 ;}
#page{width:100%;background:#ff0;border:solid .5em #000;padding:2em;}
#contents{max-width:50em;background:#00f;margin:0 auto 0;height:10em;color:#ff0;padding:1em;}
h1{color:#000;text-align:center;}
</style></head><body><div id="page">
EOT;
ob_flush();
$js = "\nvar jsn = '" . json_encode($similarDomainsUnique) . "';\n" ;
echo <<<EOT
<h1>Headline</h1>
<p>Paragraph</p>
</div></div></body>
</html>
<script type="text/javascript">//<![CDATA[
function init(){
$js
var obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>
If you need obj to be use by other functions:
<script type="text/javascript">//<![CDATA[
var obj = '';
function init(){
$js
obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>