I have a javascript function that I am calling in my code:
<script type="text/javascript">
opener.postConditionPostCure(
"<?php echo get_field('cure_description'); ?>"
);
</script>
The issue is that I do not know what will be echoed by the php. I just ran into an issue where the javascript is failing because the php is echoing an illegal token, in this case the "(". How can this issue be dealt with. Thanks.
A desirable thing to do would be to ensure that php returns normalized data, JSON string perhaps.
I hate having php intermingled with my js makes it hard to read the js
I prefer to declare it as variables at the top of my js code if possible (and it usually is)
<script type="text/javascript">
var description = <?php echo json_encode(get_field('cure_description')); ?>;
opener.postConditionPostCure(description);
</script>
Related
Please tell me why this code tells me
SyntaxError: unterminated string literal
My code:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo $geladen; ?> ");
</script>
That's a JavaScript error message, which strongly implies one of two things:
the JavaScript that reaches the browser still includes the <?php etc., meaning the PHP didn't get parsed on the server (and thus the browser flipped out on "./testtext"), or
the file testtext (and therefore your variable $geladen) contains quotation marks. Either is possible from the very little information you have posted.
You can figure out which it is by looking at the HTML in your browser.
If it's the former (if you see <?php in the HTML), then you need to fix your server configuration.
If it's the latter (if testtext contains any " marks), then you need to encode it properly before echoing, using json_encode() like this:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo json_encode($geladen); ?> ");
</script>
All that said, mixing PHP and HTML (not to mention PHP, HTML, and JavaScript) this way is not a great practice. You'd be much better off using a templating engine of some sort (Twig, Blade, etc.).
If the contents of 'testtext' contains a quote mark, it will break the javascript. Try addslashes().
<script>
console.log(" <?php $geladen = addslashes(file_get_contents("./testtext")); echo $geladen; ?> ");
</script>
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I am developing a web application in php, and I've used javascript many times. Now I need to use a php variable in javascript.
For example, a variable generated from a SQL query return, or a session variable, which are needed in the javascript section.
What is the best way to use a php variable in javascript?
Maybe you could do something like:
<script>
var a = <?php echo $a; ?>; //for numbers
</script>
That's one basic way of accomplishing what you want.
EDIT: As JiteshNK also pointed out, you could also do:
<script>
var a = <?php echo json_encode($a); ?>; //safest solution
</script>
You can do something like this :
If a normal variable:
<script type= "text/javascript">
var a = <?php echo $var; ?>;
</script>
OR
If you have json :
<script type= "text/javascript">
var a = <?php echo $json_encode($var); ?>;
</script>
If its simple string variable then use.
<script>
var a = "<?php echo $var; ?>";
</script>
If php variable is array then
var resultArray = <?php echo json_encode($varArr); ?>
// Use resultArray values in javascript
$.each(resultArray, function(index, value) {
}
I don't fully understand what you are trying to do.
Basically, I don't thing what you would like to do is possible.
Reason: JavaScript is running in the browser. At the time when your JavaScript code is executed, the page has already been loaded. At that time, there is no such thing as PHP available anymore. Your browser only knows about HTML.
PHP is running on the server and is used to "construct" or "build" or "compile" your HTML page.
What you definitely can do is: You can use PHP to create your JS code dynamically (like you already do that with your HTML file) and there use PHP to populate a JS variable with the contents of a PHP variable.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 months ago.
I have a PHP file that creates a randomized string stored in a variable. I want to access this variable with JavaScript but the methods I've found online doesn't seem to be working. This is the code I have so far:
var test = "<?php echo json_encode($myVariable); ?>";
alert(test);
$myVariable is just a string: "testing".
I thought "testing" would be alerted but instead the code itself is (<?php echo json_encode($myVariable); ?>). When I take away the quotations, nothing happens. I'm very new to JavaScript so I'm not sure what's wrong. Is there another way I can access a PHP variable with JavaScript?
you can transfer variable contents by this
var test = "<?php echo $myVariable; ?>";
alert(test);
There are few way of accessing variables from php with javascript AJAX/Cookies/_SESSION or echo directly to javascript.
AJAX
Is more readable with better separations between layers it also allows for async transfer. BUT it can be very slow adding HTTPrequest can lead the website to slow down alot if there is alot of variable to request from php.
Cookies
I dont recommend it as there will be alot of necessary data store on the client side.
_SESSION
I recommend you using _SESSION as new developer will find it easier to use. it works similar to cookies but the only difference is once the page is closed the data is erase.
Echo directly to javascript
Easy to implement but horrible code practise.
All the above answers I explain quite vague do your research on topics, look for _SESSION to start with then move on to AJAX if appropriate.
Code example
PHP
if you are getting data from mysql
$_SESSION["AnyVariable"] = my_sql_query ("SELECT someData FROM someTable")
Or if its just a variable in PHP
$SESSION["aVariable"] = whateverValue;
JavaScript
<script type="text/javascript">
function someFunction()
{
var someVariable = '<%= Session["phpVariableSessionName"] %>';
alert(someVariable);
}
</script>
json_encode produces output ready for javascript, you must not put it into quotes:
var test = <?php echo json_encode($myVariable); ?>;
Try it the other way around ...
<?php echo "var test = '" . json_encode($myVariable) . "';"; ?>
I have a string that contains php code I am trying to find a way to remove the php code from the string.
text = '<?php // This is a test sample ?> This is a description';
text.replace(/\<\?.*\?\?\>/, "");
I am not the best with regex. Any help is greatly appreciated.
A very naive approach (assuming php code will have no ternary operator, and inner comments will have no question symbol, ;)):
var s = '<?php // This is a test sample ?> This is a description'
s.replace(/<\?php\s*[^\?]+\s*\?>/g, '')
// output: " This is a description"
the php will execute before the javascript ever gets a chance to do it's thing on the php code. You can't use javascript to change php code. (Although it does work the other way around.)
I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.
Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.
Since you're using PHP:
<script>
var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>
The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.
"Safefy" your code, like this
str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));
The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.
and inline it in javascript,
//<![CDATA[
var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>
keep in mind the '"' part so that it appears like this var myHtml = "test";