PHP/Jquery - Echoing jquery in a PHP function [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following function:
function loader($time,$page){
echo "<script type='text/javascript'>
$( document ).ready(function() {
$('.register-container').hide();
$('.top-color').animate({height:'100%'}, 500);
window.setTimeout(
function() {
$('.loading-overlay').show();
},
600
);
//Simulate loading... and then redirect.
window.setTimeout(
function() {
$('.loading-overlay').hide();
$('.top-color').animate({height:'0px'}, 500);
},
2600
);
});
</script>";
echo '<div class="loading-overlay" >
<div class="loading-circles">
<!-- MAINTAINS CONSISTANT COLOR CENTER -->
<div class="circle hold" ></div>
<!-- ITERATION POINT FOR ANIMATION -->
<div class="circle first"></div>
<div class="circle"></div>
<div class="circle"></div>
</div>
<!-- ICON -->
<div class="name"><img src="images/loader/loadertext-green.png" /></div>
</div>';
echo "<meta http-equiv=refresh content=$time;URL='$page'>";
}
Which should add the above jQuery code to the page, and execute it.
Now my problem is, that when the function is called in the page, like below:
<?php
if($checksuccess){ loader("4","/account"); }
?>
I get the following jQuery error:
Uncaught ReferenceError: $ is not defined
What am I doing wrong?

Php is expecting a variable name after the $ sign because you are using double quotes.
Try changes the single quotes with double quotes inside the echo and sorround it with single quotes. The opposite that you have.

Your second echo block starts and ends with a single quote, it should be a double quote. Also, the string inside of an echo must escape double quotes. You can generally use single quotes in html, but it is probably better to escape the double quotes.
echo "<div class=\"loading-overlay\" >
<div class=\"loading-circles\">
Use escape \" on html attributes when echoing from PHP
</div></div>";

Related

How to make PHP echo data in script instead of the script tags? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I am working on a system that displays a product image connected to an entry in a form, to make it update automatically I'm using Javascript but it prints the literal tags instead of the variable set in javascript.
I've tried using this method to turn my Javascript variable into a php variable, but I haven't found a way to do this properly. I also let it output towards regular HTML text and that worked properly, so I'm just stuck on how to read it in the file name.
HTML/PHP:
<div style="position: relative; left: 0; top: 0;">
<img src="elements/<?php echo 'fronten/' . $serie . '-' . $front . '-Front-' . $formaat; ?>.png" id="ladefront"/>
<img src="elements/<?php echo 'kasten/' . $serie . '-' . '<script>document.writeln("kleur");</script>' . '-' . $formaat ?>.png" id="onderkast"/>
<img src="elements/<?php echo 'bladen/' . $product . '-' . $formaat ?>.png" id="wastafelblad"/>
</div>
JS:
var kleur = document.getElementById("color").value;
document.getElementById("demo").innerHTML = kleur;
}
The error it outputs is the following: GET .../kasten/NEXXT-%3Cscript%3Edocument.writeln( 403 (Forbidden) - so it puts the entire content in the file name instead of what the script is supposed to echo. My expected output is supposed to be .../kasten/NEXXT-(kleur)-60.png.
PHP is utterly irrelevant here.
You can't put an element (and that includes a <script> element) inside an attribute value.
You'd need to either generate the entire <img> element with JavaScript, or dynamically change the src attribute with JavaScript after completing the element.

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)

Javascript function inside ahref not working in php echo [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a series of images/links that is calling a javascript function when the image is clicked. The code below works fine in regular html, but when I try to use this inside of a php echo it doesn't work.
echo "<a href='javascript:nfllogin('nflshow');' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Everything appears fine but when I click the image/link it doesn't pull up the div area I am expecting to see. How can I make this work?
You'll need to escape some of the quotes to avoid nested quotes of the same type.
echo "<a href='javascript:nfllogin(\"nflshow\");' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Will actually output:
<a href='javascript:nfllogin("nflshow");' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a>
Which should work better for you.
echo '<img src="images/nfl-button-index.jpg" width="177" height="145" alt=""/>';
a good practice in echoing html in php is use single quote to echo and double quotes thereafter. This save the stress of escaping string. Try the above pls.
if it doesnt respond change this: javascript:nfllogin("nflshow");
The first thing that hits my eyes is that there's a problem with single and double quotes.
echo '<a href="javascript:nfllogin(\'nflshow\');" ';
echo "class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Since the JavaScript contains a single quote, you have to put the href into double quotes. I split the echo in two to avoid to escape quotes with backslashes.
To echo such big chunks of html, the heredoc syntax comes in handy too. This would look like:
echo <<<EOT
<a href="javascript:nfllogin(\'nflshow\');" class="black" style="font-size:12px;">
<img src="images/nfl-button-index.jpg" width="177" height="145" alt=""/>
</a>
EOT;
There are two advantages:
There's no need to escape quotes
As a consequence, you can indent your HTML code and use double quotes for the attributes. It's just a matter of clean code to quote all HTML code consistently with double quotes.

Why is my javascript failing to work?

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.

How to make an onclick div in php [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
<script type="text/javascript">
function Invest()
{
alert("Mechanical /n Electrical /n Computer /n Civil");
}
function create()
{
alert("Graphic /n Interior /n Architecture");
}
function motivate()
{
alert("Business Administration /n Accounting and Finance");
}
</script>
The above code is my javascript code
<form action="main.html" method="post">
<?php
$v2 = $_GET['dropdown'];
if ($v2=="investigative" )
{
echo "<h3>It's recommended that you follow</h3><h2>Engineering School</h2>";
}
else if ($v2=="creative" )
echo "<h3>It's recommended that you follow</h3><h2>Arts School</h2>";
else if ($v2=="motivated" )
echo "<h3>It's recommended that you follow</h3><h2>Business School</h2>";
?>
What i want to do is to change my echo to a div onclick so it will call my function from javascript and show the information i have inside it.
Something like this
echo ""<div onclick=Invest();"<h3>It's recommended that you follow</h3><h2>Engineering School</h2>";
When I do that thought i get an error
Parse error: syntax error, unexpected 'onclick' (T_STRING), expecting ',' or ';' in C:\xampp\htdocs\MyProject\eval.php on line 35
What am I doing wrong and how to make that work? I am new at php :/
Not something like this echo ""<div onclick=Invest();...
You need to do it like this put div tag inside double quotes for onclick attribute open single quotes because double quotes are already opened
echo "<div onclick='Invest()'><h3>It's recommended that you follow</h3><h2>Engineering School</h2></div>";

Categories