Why is my javascript failing to work? - javascript

I've been working on this code for a while. The idea is to get javascript to make a div visible based on the results of a HTML form (not on this page). However, my javascript function never works. I've isolated the problem to the script not being called in the first place. Here's my code:
<!DOCTYPE HTML>
<html>
<body>
<?php
While ($result=mysql_fetch_array($data)){ //I have mySQL code before this
$equipment= $result['safety equipment'];
$equipment2= str_replace(' ', '_', $equipment); //modified equipment name without spaces so that post can read it
$problem = $_POST[$equipment2];
?>
<div style="display:none;" id="<?php echo $equipment?>"> <!--Code that creates a div for each equipment -->
<h1>Report a problem</h1> <br>
You reported that there is a problem with the <?php echo $equipment." in ".$name;?>.<br>
Please describe the problem.
<form>
<textarea row="5" column="300" name="Issue">
</textarea>
</form>
</div>
<?php
if ($problem=="working"){
inspectRoom($UID,$equipment,null);
}else {
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
}
}
?>
<script type="text/javascript">
function Appear(equipment){
alert("hi"); //error trapping
document.getElementById(equipment).style.display='block';
}
</script>
</body>
</html>
$equipment is a string with the name of the equipment (ex: Fume Hood)
$problem is a string retrieved from the previous page. It too has the name of some equipments.
In my console I get the following error:
"SyntaxError: missing ; before statement"
What am I doing wrong?

You're dumping PHP-based text directly into a Javascript context, which is highly dangerous. Any JS metacharacters (especially ') will cause syntax errors and kill the entire JS code block.
echo'var test ='.$equipment.';';
Should be
echo 'var test = ', json_encode($equipment), This will produce syntactically valid JS code, no matter what's in `$equipment`.
Plus, you have MANY other syntax errors. Your php while is NOT contained in a <?php ... ?> code block, so it'll appear directly in your output as raw text. The html inside your while loop is now considered part of the PHP code, so that'll be yet another syntax error. etc... etc... etc.. In other words this code is utterly broken.

Talking solely about javascript since that's what your question is about, your Appear function would never been defined yet since the PHP code would have echoed out the JS that calls Appear before the function is defined.

It is not working because you are forgetting the space after echo. There are other errors also such as your while is not within tags.

For this part of the code
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Replace it with
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo"var test ='$equipment';";
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Th variable isn't surrounded by quotes when the value will be a string;

To start with you are missing a > on line 6.

Related

What is the functional difference between these two snippets of code?

What is the functional difference between these two snippets of code
<!--?php include('json-ld.php'); ?--><script type="application/ld+json">// <![CDATA[
<?php echo json_encode($payload); ?>
// ]]></script>
and
<?php include('json-ld.php'); ?><script type="application/ld+json">
<?php echo json_encode($payload); ?>
</script>
My objective is to apply a JSON-LD file (containing schema.org structured data) to my WordPress site. The first code is taken from this page, and purports to do what I need. But I can't understand why the author would post a snippet with so many comments. From what I understand about HTML and JS comments, the code appears to be functionally equivalent to the bottom code. I am posting here to assure myself that I am not misunderstanding something about this syntax.
Perhaps there is a security purpose for using the commented code? If so, I would be interested in practicing best practices in terms of security.
Thanks.
CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be. This is so that html tags and such can be used without it breaking the xml code - each html tag would be represented as a child-node to the xml. By using the CDATA "comment" you are telling the xml to consider the html tags as a string value, not a child-node.
Regarding the first line: <!--?php include('json-ld.php'); ?--> This isn't including the file - this may be a typo on the original authors' part. If your code works without it, it is probably safe to remove; otherwise, fix it ;)
From what I see, it's purely so that potential output of <?php include('json-ld.php'); ?> are not treated as HTML.
Since most of the time there is no output in <?php include('json-ld.php'); ?> , <!-- <?php include('json-ld.php'); ?> --> just do <!----> . But potential PHP notices or errors that randomly pop will end commented and not breaking the DOM.

Using jQuery/JavaScript for modifying a HTML table

I have a HTML page which has one div and table. Then I have a PHP script which sould print the HTML for a table. Anyway, the table will not be modified. Does my print command include some kind of special charasters or is there something else which could be the reason?
I have a file index.html with the following jQuery code:
$(document).ready(function(){
setInterval(function() {
var kaavio = 106;
jQuery.post("search.php", {
kaavio: kaavio
}).done(function(data) {
$('#check').html(data);
});
}, 6000);
});
Here is the HTML of the file index.html:
<div id="check"></div>
<table id="paikka59"></table>
I also have a PHP file search.php and here is the code of it:
print "<script>document.getElementById('paikka59').innerHTML = '<tr><td class=\"pisteet\" style=\"border-top:2px solid #16B2B4;padding:0\"></td><td class=\"nimi\" style=\"border-top:2px solid #16B2B4;padding:0\">2888 Salmi Risto</td><td class=\"tasoitus\" style=\"border-top:2px solid #16B2B4;padding:0\"></td></tr> <tr><td class=\"pisteet\" style=\"padding:0\"></td><td class=\"nimi\" style=\"padding:0\">2893 Rantanen Mikko</td><td class=\"tasoitus\" style=\"padding:0\"></td></tr> <tr><td class=\"pelimuoto\"><!-- a --></td><td class=\"ajankohta\"><!-- b -->Pöytä -Ei aikataulutettu</td><td class=\"toiminnot\"><!-- c --></td></tr>');</script>";
1st, I didn't go further than the first mistake (in comments)
print "<script>alert('<tr><td class="pisteet" style="border-top:2px solid #16B2B4;padding:0">
-> just this line should throw an error
You really need to use a decent IDE :)
your code shows :
print "<script>document.getElementById('paikka59').innerHTML = '<tr>
<td class=\"pisteet\" style=\"border-top:2px solid #16B2B4;padding:0\"><!-- a --></td></tr>');</script>";
you should get rid of the extra ) at the end
when testing, throws a warning/error
See Element.innerHTML for different Syntax
EDIT: always check all of the stuff, especially looooong ones :)
double quotes are creating a problem here.
Your print string is getting terminated at
print "<script>alert('<tr><td class=" // rest all code will be skipped
Use \" in such situation. Your print statemnet will become like
print "<script>alert('<tr><td class=\"pisteet\" ... </tr>');</script>";
One more thing, you can not add html tags inside alert(). You can only insert plaintext to alert(), confirm() and prompt() boxes.
Have a look at below thread :
HTML Tags in Javascript Alert() method

php/html - triple nesting quotes

I know that similar questions have been asked on Stack Overflow many times, but I am having problems with triple nested quotes in html/php. I have looked at numerous questions, but none of the solutions that I have found are working for me. Here is what I am trying to do (this is found in a php file):
echo"<div id = 'feed-element'>
<button class='username-button' type='button'>#".$currentUsername."</button>
<button class='hashtag-one-button' type='button'>".$hashtag_one."</button>
<button class='hashtag-two-button' type='button'>".$hashtag_two."</button>
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\'".$track_url."\')'></button>
<button class='email-button' type='button'>Contact: ".$email."</button>
</div>";
The specific line that is causing me problems is the third to last line:
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\'".$track_url."\')'></button>
Anyways, when I run this code I get an Uncaught Syntax: invalid or unexpected token error. What am I doing wrong?
Why not use php heredoc and skip the hassle of escaping quotes? i.e.:
echo <<< EOF
<div id = 'feed-element'>
<button class='username-button' type='button'>#{$currentUsername}</button>
<button class='hashtag-one-button' type='button'>{$hashtag_one}</button>
<button class='hashtag-two-button' type='button'>{$hashtag_two}</button>
<button class='play-button' id='play-button{$i}' type='button' onclick='changeImage(this.id,{$track_url})'></button>
<button class='email-button' type='button'>Contact: {$email}</button>
</div>
EOF;
Note:
The curly braces are optional but may help code readability.
For your error-causing code, you need to escape double quotes, not single:
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\"".$track_url."\")'></button>
Because you are using double quotes, you don't need to concatenate. Just insert the variable and away you go!
echo"<div id='feed-element'>
<button class='username-button' type='button'>#$currentUsername</button>
<button class='hashtag-one-button' type='button'>$hashtag_one</button>
<button class='hashtag-two-button' type='button'>$hashtag_two</button>
<button class='play-button' id='play-button$i' type='button' onclick='changeImage(this.id,\' $track_url\ ')'></button>
<button class='email-button' type='button'>Contact: $email</button>
</div>";
For using quotes to any level in PHP/HTML, use forst level as either single or double quote. After that you have two options. 1. Use double quotes 2. Use single quotes with backslash before the quote. For example, echo "This is 'In quotes'"; or echo "This is \"In quotes\"";
In order to have multiple type of quotes on a line of code use .
Example :
echo 'It\'s me, hey';
You'e all crazy. Just end the php block and write whatever then start it up again.
Example
I want to dynamically create 3 different div elements, each one with two parameters: $ID and $TEXT which represent the dom element ID and the innerHTML.
Now to make it truely complex, I want to dynamically insert these elements into a Javascript Function, so that they will load when I call the JS function.
Here's how to do that: You simply end the PHP tag and then enter your desired content as if the PHP tag never existed, and it will parse it as if it was specified within PHP without having to escape anything
<?php
/* define regular function to generate dynamic element with PHP */
function create_my_div($ID, $TEXT) {
/* end the PHP tag and start just regularly entering code
?>
<div id='<?=$ID;?>'>
<?php print_r(htmlspecialchars($TEXT)); ?>
</div>
<?php
/* we started up the PHP tag again, followed by a } to end the function
}
?>
Now anytime we call create_my_div("someID", "some text"); with PHP it will create our DIV element.
Lets say we wanted to populate a javascript function's DIV elements server-side and put them into the Javascript Function create_my_divs()
We first would need to have a way to ensure that our DIV elements are properly escaped as mentioned in the other answers, which can be done with this PHP code:
<?php
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>
And then finally, all we have to do is this on our web page:
<script type="text/javascript">
/* target element is where the DIVS will be created in */
function create_my_divs(target_element) {
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV1", "THIS IS DIV1"));?>";
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV2", "THIS IS DIV2"));?>";
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV3", "THIS IS DIV3"));?>";
}
</script>
This method will allow you to include javascript code or whatever without worrying about triple nesting
Here's another use case for this method:
Dynamically adding Javascript code:
<?php
function loop_start($varName) {
?>
for (var i=0; i<<?php print_r($varName);?>.length; i++) {
<?php
}
?>
Now your Javascript code could look like this:
<script>
<?php
loop_start("myArray");
?>
console.log(myArray[i]);
}
</script>
Which would result in the following to be rendered:
<script>
for (var i=0; i<myArray.length; i++) {
console.log(myArray[i]);
}
</script>
Conclusion
Stop worrying about trying to triple escape or double escape, or even escape at all.
With the tricks outlined in this answer, you can avoid escaping all together.
(Escape the confusion if you will)

jQuery add variable to selector not working

I am passing an ID to a selector, but somehow it doesn't work. When I hardcode it, then it works. Below is my script and the various ways I have tried. :
jQuery("li.<?php echo slugify($catId); ?>").closest("ul").closest("li").addClass("active");
When I view in console, the script above echoes out the $catId correctly but it just doesn't work.
Then I tried this :-
var catId='<?php echo $catId; ?>';
jQuery("li."+catId).closest("ul").closest("li").addClass("active");
In the console, the variable catId wasn't printed out at all. It shows ("li."+catId) in the console.
Then I tried converting it to string and pass it to the selector like this :
var catString = catId.toString();
It doesn't work either. I hardcode the catId directly to the line and it works just fine.
Anyone can help? Thanks in advance.
If you are trying the above snippets your HTML should look like this
<li class="<?php echo slugify($catId); ?>"> ....
And you shouldn't be associating them to id attribute
I have managed to solve it!!!
It's just moving the whole <script></script> to after the <li> </li>
Basically the placement of the script causes the issue. :)

Issue on Replacing Special Characters in a <pre> Element

I am trying to use a jQuery Plugin for highlighting my Snippet at This Demo but the browser assumes that
<pre class="php">
<?php
echo "My first PHP script!";
?>
</pre>
is a originally PHP code which it is! now the solution is replacing all < with < and > with >
inside the <pre class="php"></pre>
Now can you please let me know how can I use the jQuery to replace all < and > characters inside the with < and > before loading the page?
Thanks
So you got the data with <? tags, it better for you is to replace output of your code serverside with < and > but if you looking for dirty js solution it is would be:
$('.php').each(function() {
var $this=$(this);
$this.text($this.html().replace(/\<\!--\?([\s\S]*?)-->/g,'<?$1>'));
});
http://jsfiddle.net/oceog/x974w2d9/
I not remember if any browser do the replacing of the <? with <!--? but chrome does. The js solution will not work if you have some random examples like: http://jsfiddle.net/oceog/x974w2d9/2/.
Now can you please let me know how can I use the jQuery to replace all < and > characters inside the with < and > before loading the page?
The problem lies in the assumption behind this question. You cannot use jQuery to make this manipulation before the page loads, as jQuery executes after the page loads up in the browser. So your PHP is getting executed and all jQuery will see is:
<pre class="php">
My first PHP script!
</pre>
You need to make sure the string makes it into the output instead of being executed. Something like this should work:
<pre class="php">
<?php
$snippet = <<<EOT
<?php
echo "My first PHP script!";
?>
EOT;
echo $snippet;
?>
</pre>

Categories