Jquery Remove php code from string - javascript

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.)

Related

PHP Unserialize Javascript serialized string

Good day,
I got a new script (for me it is) that allows you to create a draggable tree view.
The order of the tree structure can be changed and also stored.
I managed to send and fetch the updated structure.
However I have not yet succeeded in unserializing the string.
Before I am going to write my own logic to decode the array I would like to know if PHP knows some functionality by default to solve this issue?
Example
The String that I have :
spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null
The code that generates this string :
serialized[0].hash
I hope anyone could tell me what I have done wrong. OR IF this even a usable structure.
Thanks in advance
Note
The results are bing written by PHP to a file called test.txt
When I try to get the results I try it like this:
<?php
$cont = file_get_contents('test.txt');
$Str = parse_str($cont);
echo '->'.$Str.'<-';
?>
This produces : ><
Hence an empty string.
The following is a working solution:
<?php
$cont = file_get_contents('test.txt');
parse_str($cont, $Str);
echo print_r($Str);
?>
(* the array that comes out of it is pretty useless actually *) but THANKS
This is all you need:
$arr = [];
$string = "spans-divs[0][id]=null&spans-divs[1][id]=null&spans-divs[1][children][0][id]=null&spans-divs[1][children][0][children][0][id]=null&spans-divs[2][id]=null&spans-divs[3][id]=null";
parse_str($string, $arr);
var_dump($arr);
Source: http://php.net/manual/en/function.parse-str.php

div innerhtml not taking html

I want to update innerhtml of div with id NotifyDiv
I want to change it with following html code.
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
I am using following code to change it.
echo "<script>document.getElementById('NotifyDiv').innerHTML='$html'</script>";
But no changes occur.
However it I remove id = 'js-news' from the above ul tag it works.But I'll need the id.
If you check the source code of your browser you will see this:
<script>document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>
So we can see that in the JavaScript string you are using apotrophes, but the string is already encloded with apostrophes, so it attempts to end the string early: (before the letter j in js-news)
'<ul id='js-news'><li>HELLO WORLD!</li></ul>'
This can be solved by using escaped quotation marks for the JS string:
echo "<script>document.getElementById('NotifyDiv').innerHTML=\"$html\"</script>";
Basically, the code you have causes a syntax error in JS:
echo "...innerHTML='$html'</script>";
expands to:
// opening ' closing ' => js-news === syntax error!
// \/ \/
echo "...innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>";
Resulting JS code:
document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'
The syntax highlighting shows the problem
Note the single quotes around $html and the single quotes inside the $html string. The best way to echo PHP values in JS would be to use json_encode:
echo "...document.getElementById('NotifyDiv').innerHTML=", json_encode($html), "</script>";
The output should be something like:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!<\/li><\/ul>"</script>
Now, those slashes are escaped, and you probably don't want that. Thankfully, there's a second parameter you can pass to json_encode: cf the docs. Passing JSON_UNESCAPED_SLASHES is what you need to do here:
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
echo "<script>document.getElementById('NotifyDiv').innerHTML=".json_encode($html, JSON_UNESCAPED_SLASHES)."</script>";
The output:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!</li></ul>"</script>
DEMO
Perfect ans to your query is as under (just copy n paste and check it)
<?php
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
?>
<script type="text/javascript">
document.getElementById('NotifyDiv').innerHTML="<?php echo $html; ?>";
</script>";
You need to pass PHP variable with PHP syntax that is <?php ?>
Even if we can mix PHP, JavaScript and HTML together, we need to initialize proper languages before using their variables in case of JavaScript and PHP.
So, final code should be:
echo "<script>document.getElementById('NotifyDiv').innerHTML = '<?php echo $html;?>'</script>";
Otherwise, everything looks correct.

Trying to append html string fail with jQuery

I'm trying to append the following string to head with jQuery :
"<script type='text/javascript'> window['adrum-app-key'] = 'dummy';</script>"
But it always fails. Trying to do the same with 'Hello' string for example works as expected.
Following the code snippet I use to append the string :
var integrationScriptTag = handlebars.partials.integration(integrationData);
$(document).ready(function() {
$('head').append(integrationScriptTag.trim());
});
First string is the result of parsing integrationData.
Any help will really be appreciated.
Edit: I realize I misguided some of you with the first string. It is just a representation of what is produced by the first line of the second code snippet. So it doesn't really matter if it is some quote marks or not. The fact is I don't use a literal but rather a variable which is equal to the first string. I corrected the syntax so that there is no more confusion.
Here is the jsFiddle reproducing the problem.
jsFiddle
This should fix it:
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] = \'dummy\';</script>'
or this would too:
'<script type="text/javascript"> window["adrum-app-key"] = "dummy";</script>'
Essentially you have quotes mismatch.
Use this, it will fix the issue
'<script type=\'text/javascript\'> window[\'adrum-app-key\'] =\'dummy\';<\/script>'
I finally found that you cannot append script tags to head with jQuery this way.
I found some solutions here and there (look at the first code snippet of the selected answer for the second link).
The head is parsed prior to the execution of javascript. So you probably have to perform the append outside the $(document).ready function.

Storing php value in javascript variable

I am trying to store php value in my javascript variable. But this code is giving me syntax error. Is the code correct ?
var b = <?php echo $tagValue;?>;
alert("B is " +b);
You have to make sure that your webserver interprets that file as a php file. then you have to adapt your code, because it looks like you could have an error in your js code in the end:
var b = "<?php echo $tagValue;?>";
alert("B is " +b);
(I have added quotes). Does not apply, if you are sure that $tagValue is only numeric.
In case you don't really know what kind of value your $tagValue is or you simply want to make sure you won't fail you should use json_encode($tagValue):
var b = <?php echo json_encode($tagValue);?>;
alert("B is " +b);
Please note that in case $tagValue is an array/object your js-alert won't be very usefull :)
Easiest way i've found to do it without worrying about character escaping or XSS is to convert the contents of the variable to JSON. All it takes is to echo json_encode($tagValue); instead of echo $tagValue;
make a function maybe can help u.
this is an example
// your php code
$tagValue = 'value';
getValue($tagValue);

Storing HTML in a Javascript Variable

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";

Categories