Issues with PHP echo into a javascript - javascript

I am using the same line of code to echo a link onto my page in two locations and getting different results. One is inside an < a > tag and the other is inside a < script > tag. Below are the two excerpts of code (from the same tpl file) and the results:
<?php echo $btn['text']; ?>
Results in:
Filter
However in the script tag I have
url = "<?php echo $links['current_path']['href']; ?>"
And my result is
url = "index.php?route=module/jw/list&token=a4c693a4e38916fc03af23ad4fe1"
Notice the '&' after the route parameter. It is displaying the html code when I echo it inside the script tag. I know I can convert it in the second instance, but I am curious as to why I would need to. Why is the same php command making the symbol echo differently in various parts of the source code?

& is a HTML entity - your browser parses and displays it. Some similar questions about decoding here and here. Have you tried html_entity_decode():
html_entity_decode — Convert all HTML entities to their applicable characters
So
url = "<?php echo html_entity_decode($links['current_path']['href']); ?>"

Use the php function html_entity_decode
Example:
<?php echo $btn['text']; ?>

Related

Use PHP to embed JSON for use by Javascript

I'm working on using React (javascript) inside a WordPress plugin but my plugin requires some data retrieved from the database. I could probably retrieve the required data in javascript using jquery or an API call, but since the data will be static, it seemed more efficient to embed the data using php prior to rendering the DOM element with javascript.
I tried the following, but the <script> tag containing the json never appears in the DOM.
<?php
$events = \Civi\Api4\Event::get()
->addSelect('*')
->addOrderBy('start_date', 'ASC')
->setLimit(25)
->execute();
echo "<script type=\"application/json\" id=\"eventList\">";
echo json_encode($events);
echo "</script>";
?>
<div id="civi-react-events">
<h2>Loading...</h2>
</div>
Update
It turns out the code above works. It turned out to be a cache issue. Ctrl-Refresh is your friend.
Thank you to those who took the time to respond.
Sometimes, json_encode returns tags, texts, etc. with a wrong format. It may lead to break the script tag To ensure the json is fine to use, use the json_encode flags. I personally recommend using the following flags:
<?php
$jsonExportConst = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK;
$eventsJson = json_encode($events, $jsonExportConsts);
echo "<script type=\"application/json\" id=\"eventList\">{$eventsJson}</script>"

Jquery if/else statement with dependencies on php session variable [duplicate]

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!
I am trying something like this:
var areaOption=document.getElementById("<?php echo #$_POST['annonsera_name']?>");
areaOption.selected=true;
Also I have tried this, but it only alerts a BLANK alert-box:
alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck
Am I thinking completely wrong here?
UPDATE
Some PHP code:
<?php
$test = "Hello World!";
?>
In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set).
Test this:
alert (<?php echo "'H'";?>);
OR
alert ('<?php echo "H";?>');
PHP runs on the server side and Javascript is running on the client side.
The process is that PHP generates the Javascript that will be executed on the client side.
You should be able to check the JS that is generated just looking at the code. Of course, if the JS relies on some PHP variables, they need to be instanciated before the JS is output.
<?php
$test = 'Hello world';
?>
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
will work but
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
<?php
$test = 'Hello world';
?>
will not
Use json_encode to convert some text (or any other datatype) to a JavaScript literal. Don't just put quotes around the echoed string — what if the string has a quote in it, or a newline, or backslash? Best case your code fails, worst case you've got a big old cross-site-scripting security hole.
So,
<?php
function js($o) {
echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
}
?>
<script type="text/javascript">
var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>);
areaOption.selected= true;
alert (<?php js('Hello World'); ?>);
</script>
Your using #$_POST indicates that you have received (or are expecting) errors - check your generated source to see if the value was output correctly. Otherwise document.getElementById will fail and you'd get no output.
alert("Delete entry <? echo $row['id']; ?> ")
If your extension is js, php will not work in that file.
The reason being, php parses on files that it is supposed to. The file types that php will parse are configured in httpd.conf using AddType commands (or directives, whatever they are called).
So you have 3 options:
add filetype js to the list of files php will parse (BAD, VERY BAD)
make the script inline to some php file
rename the file to script.js.php, and at the beginning of the file, specify the content type, like so:
<?php header( 'content-type: text/javascript' ); ?>
Cheers!

Append html code to file using PHP

I have a Javascript function that takes a string and sends it via ajax to a PHP page. In PHP I would put this string inside the head tag (that already exist) of an html file. This change should be final. How could I do this? I don't know how to manipulate html code via PHP.
<?php
$htmlpage = file_get_contents('http://example.com/index.html');
echo str_replace("<head>", "<head>New text", $htmlpage);
//the result should be from <body></body> to <body>New Text</body>
?>
Also if you have text between body tags you can include it in
str_replace("<body>Old Text", "<body>New Text", $htmlpage)
If you have the string inside a varibale or you are using $_POST then instead of "<head>New text" put "<head>".$_POST['thestring']
Just use if/else statements and echo string from ajax to your tags if you can't use JS for this.
One way around this would be to use file_get_contents, then do a string replace on the tag with the amended code, and then write the changes with the ammended code.
Example
<?php
$file = "myhtmlfile.html";
$original = file_get_contents($file);
$needle = "<head>";
$new_content = "<head>\n".$_POST['header'];
$replacement = str_replace($needle, $new_content, $original);
file_put_contents($replacement, $file);
?>

how to convert this code to insert it in .js file

I'm trying to make my website multilingual, i have the php code also and i have translated files, but my site has also js file where is this words which i want to translate, there is example of this php code and how to insert it to js file?
There is JS code
// Update search list
rsParent.html($('<div>').attr({id: 'relatedSearches', class: 'contentBox'})
.append($('<div>').addClass('cbHead').text('Related Searches'))
.append($('<div>').addClass('cbBody').html(list)));
}
});
and the word "Related Searches" i want to replace with this php code
<?php echo $lang['CHARTS']; ?>
It is not possible to do it directly since PHP is a serverside language which is executed once on a webserver, unlike javascript that is executed in client's browser.
What you can do is encode your PHP array $lang to JSON and then output it as inline javascript and assign it to a variable in javascript.
<?php
echo "<script>";
echo "var lang = " . JSON_encode($lang) . ";";
echo "</script>";
?>
Make sure this php code is placed (executed) before your javascript file because variable lang has to be declared before your javascript is executed.

How to get PHP string value in javascript?

Hi have looking on various questions but none of them seem to help me. I have a php variable in my php code and I am trying to access that in my javascript when I do. . .
var thing = "<?php echo($phpvariable); ?>";
then when I do
alert(thing);
It comes out to be "<?php echo($phpvariable); ?>" in the alert statement
What am I doing wrong?
Your PHP is obviously not being parsed. Are you in a .php file? If you're in a .js file, you'll need the server to parse those (or, more safely, put the PHP part somewhere in the DOM that the JS can access)
However, you're doing it wrong:
var thing = <?php echo json_encode($phpvariable); ?>;
Note: no quotes. json_encode will take care of that for you.
If this code is in a function in javascirpt that executes on click or at a specific event, then:
You are writing PHP Syntax in javascript, there is no way that you load the page then you run the php code. PHP code runs on the server side, so before any other HTML Javascript code executes
Else if you want to dynamically set the variable thing in javascript when the page is first loaded, then most probably you meant to write in the php file:
var thing = <?php echo '"'.$phpvariable.'"'; ?>;

Categories

Resources