JQuery function not executing inside a PHP loop - php

I have a php array of result $bank_r. I want to perform some results in all of the results. For that I wrote :
$(function(){
//alert('<?php echo count($bank_r); ?> ');
<?php
for($i=0;$i<count($bank_r);$i++)
{
$bank_name = strtolower (str_replace(" ","",$bank_r[$i]['bank_name']));
?>
alert('<?php echo $bank_name; ?>');
<?php } ?>
-------------
----------
//Some other jquery functions
//
//
});
I was expecting to alert the $bank_name, but it is not. Even the top alert('<?php echo count($bank_r); ?> '); also not alerting anything. But If I remove the php for loop, the top alert alerts the number of results. Whats wrong ?
EDIT:
Generated javascript code:
<script>
$(function(){
//alert('5 ');
alert('ucobank
');
alert('pnb');
alert('bob');
alert('sbi');
alert('hdfc');
//Other javascripts
});

Try this,
<?php
for($i=0;$i<count($bank_r);$i++)
{
$bank_name = strtolower (str_replace(" ","",$bank_r[$i]['bank_name']));
echo '<script> alert("'.$bank_name.'");</script>';
// if you are outside the javascript then use script tag, otherwise remove the tags
}
?>

New line in first alert is problem. It causes JS parse error and because of that alerts will not appear. You have to replace newline to eg. spaces by str_replace("\n", ' ', $string);.

Related

How to echo javascript code which contains php tags inside?

I usually echo script alert by simply
echo '<script type="text/javascript">alert("'.$my_message.'");</script>';
but how to echo the script when the script contains php tags? (see my example code)
Because of my php obfuscator script, I have to use only one <?php ?> tag. so in this case I need to echo the javascript without having <?php tags. What are the possible solutions in this case?
<?php
...some php code...
<script type="text/javascript">
jQuery(document).ready(function($){
$i = 0;
$('.wrapper_vertical_menu .megamenu_menu').append('<div class="more-wrap"><span class="more"><?php echo $this->__("More"); ?></span></div>');
$('.wrapper_vertical_menu .megamenu_menu > li.megamenu_lv1').each(function(){
$i ++;
if($i>13){
$(this).css('display', 'none');
}
});
... more js code ...
JavaScript doesn't "contain PHP tags". All your PHP code needs to do is build the resulting output string (which happens to be JavaScript code, but that doesn't matter to PHP) and echo it.
So where you have something like this:
echo "some javascript code <?php echo some_php_value; ?> more javascript code";
What you really want, quite simply, is this:
echo "some javascript code " . some_php_value . " more javascript code";
Don't try to nest <?php ?> tags within each other. Just concatenate the actual output you want and echo that output.

Javascript inside php not working properly

<div class="interactionLinksDiv">
REPLY
</div>
I have call the javascript function toggleReplyBox with five parameters. This code is written inside the php tags. But this code is not executing properly and the parameters are not being passed properly. If I call the function toggleReplyBox here with no parameters it works fine but thats not what I want.
<div class="interactionLinksDiv">
REPLY
</div>
When I copied this code to the html part of my php file It works fine and the parameters are passed and the function executes properly.
But I want to know why the function is not able to work inside of the php tags when everything is the same.
function toggleReplyBox(sendername,senderid,recName,recID,replyWipit) {
$("#recipientShow").text(recName);
document.replyForm.pm_sender_name.value = sendername;
document.replyForm.pmWipit.value = replyWipit;
document.replyForm.pm_sender_id.value = senderid;
document.replyForm.pm_rec_name.value = recName;
document.replyForm.pm_rec_id.value = recID;
document.replyForm.replyBtn.value = "Send";
if ($('#replyBox').is(":hidden")) {
$('#replyBox').fadeIn(1000);
} else {
$('#replyBox').hide();
}
}
Inside the php tags I changed the code :
print <<<HTML
<div class="interactionLinksDiv">
REPLY
</div>
HTML;
And it is still showing the error
Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\Fluid Solution\fluid-solution-website-template\interact\profile1.php on line 130
Line 130 is the <a href... line.
The first version of your code is neither PHP (javascript/HTML tags are "naked") nor Javascript: the "." string concatenation operator won't work in Javascript, nor will the $variable expansion.
You can get it to work in PHP like this:
<?php
$fullname = "Test";
$current_id = 15;
$id = 9;
$thisRandNum = 42;
// All lines beyond this point, and...
print <<<HTML
<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('$fullname','$current_id',
'$current_id','$id','$thisRandNum')">REPLY</a>
</div>
HTML;
// ...up to here, start at the first column (i.e. they are not indented).
?>
Note that within the here-document (area between <<<HTML and HTML), you can't use the string concatenation operator "." (or any other).
Or you can do as you did in the second version of your code, replacing only the variables with <?php echo $variablename; ?> and leaving all the rest as HTML.
As a simpler example let's consider an alert() box with message sent from PHP. This means that:
1) the script is executed server side; anything between <?php ?> tags is executed, and its output replaces the tags themselves.
After this phase, we no longer have PHP but a mix of HTML and Javascript, which can be executed by the client it's sent to. So we want to have a HTML like
<script type="text/javascript">
alert('Hello, world');
</script>
To do this we can generate all the HTML in PHP:
echo '<script type="text/javascript">';
echo "alert('$message');"; // or also: echo 'alert("' . $message . '");';
echo '</script>';
Or we can do it with a here-document, where operators do not work, but $variables do:
echo <<<HEREDOCUMENT
<script type="text/javascript">
alert('$message');
</script>
HEREDOCUMENT;
Or we can run it all in HTML, and only rely on PHP to generate the lone variable:
<script type="text/javascript">
alert('<?php echo $message; ?>');
</script>
But always you need to keep separated what it's being done in PHP, what in Javascript, and what is in the HTML markup.

How can I can write javascript between two tags in HTML?

I have a PHP file that inserts code into an HTML5 file. Something like this:
// this works fine
echo '<li>...something</li>';
// this doesn't work
echo '<script type="text/javascript">document.write(\'<li>...something...</li>\');</script>';
If I "echo" these lines to the screen they both work OK (Of course, this is plain code!).
BUT this code above is "echo":ed into an HTML5 file and executed THERE. The first option works, while the second one doesn't (producing sometimes error 1561).
Example: http://www.w3schools.com/PHP/php_ajax_database.asp
Another example: http://www.modilo.net/dump.html
Can anyone tell me how I can wrie javascript between two tags in HTML code??
The Javascript BOO isn't set, so you need to either set it in your echo like:
echo '<script type="text/javascript"> var BOO = '. $BOO .'; // blah</script>';
Or, just put the value in, so it gets printed out to the user's browser:
... if( '. $BOO .' ) ...
For Javascript to work, write down it in the appropriated tags.
Try the code below.
<html>
<head>
<?php // dump
// Lets say $BOO in PHP and BOO in javascript have the same value.
$BOO = true;
// Option 1 works fine:
if ( $BOO ) { echo '<li> PHP ... something ... </li>'; } else echo '<li> PHP ... something else ... </li>';
// Option 2 doesn't work (and I need this!):
echo '<script type="text/javascript">
var BOO = '.$BOO.';
if (BOO)
document.write(\'<li> JS... something ... </li>\')
else
document.write(\'<li> JS ... something else ... </li>\');';
echo '</script>';
?>
</head>
</html>
This code has the optput
PHP ... something ...
JS... something ...

Jquery to parse HTML in a string

I tried searching the related posts, and having a hard time figuring out how to fix my query - I'm pretty close, any help is much appreciated (new to Jquery).
I program in PHP, and trying to pull either the HREF value from a tag, or the text. Either will work.
I basically have my HTML code in a string, might contain multiple tags, and would like to load the text of the tags into either a PHP array or variable (right now just trying to ALERT the results, I can dump it later).
My PHP Code:
<?php
$info = '<li><strong>I want this text</strong>';
echo '<script type="text/javascript">';
echo '$("document").ready( function () {';
echo 'alert($("a", $("' . $info . '")).html());';
echo '});';
echo '</script>';
?>
The above doesn't alert anything. Putting in
echo 'alert("yes")';
does work, so I'm guessing there's something basic wrong with my syntax, but 4 hours later still unable to find it! :)
Thanks in advance.
You aren't Javascript-escaping the quotes in your string.
Your code creates Javascript that looks like
$("<li>...<a href="http..."...")
The quotes in the attribute end the Javascript string, creating a syntax error.
You need to call json_encode.
SLaks has the rest of your problem. But also, it's not:
$("document").ready();
It's:
$(document).ready();
The former is a selector for a tag named <document>.
This should work the way you want it to:
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready( function () {
alert($("a", $("<?php echo $info; ?>")).html());
});
</script>
You are not closing your li Tag
$info = '<li><strong>I want this text</strong>';
should be
$info = '<li><strong>I want this text</strong></li>';
You should escape info. It's breaking because you've got double quotes inside of double quotes:
$info = addslashes($info);
or
$info = json_encode($info);
or just
$info = str_replace('"', '\\"');
Try to save the HTML is a JS variable first, then use it. Also, heredocs are your friend.
<?php
$info = '<li><strong>I want this text</strong></li>';
echo <<<END
<script type="text/javascript">
$(function(){
var HTML = '$info';
alert($('a', $(HTML)).html());
});
</script>
END;
?>
echo '<script type="text/javascript">
$(document).ready( function () {
var info = \''.$info.'\';
$("a").html(info);
alert(info);
});
</script>';

PHP echo out jQuery in IF statement

EDIT: What a TW*T. Sorry everyone for wasting your time. Just missed a Google jQuery link on one F'in page. Whoops.
Hi, i have a div containing 3 forms. These should be the only thing on the screen on page load. When any of them are submitted, a graph gets shown below. What i'm trying to do is within the PHP IF statement is make the div disappear that contains the forms. Sound simple?
This is my code:
if($_GET['submit1']){
echo "<script type='text/javascript'>$('#options').css('display','none');</script>";
However, when i do submit one of the forms (therefore a $_GET has occurred) the div is still there??
EDIT:
If i try people answer on one line i get this:
Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$'
But if i put in people's multiline answers, no error, but div still shows!
Why do you want to hide the forms with JavaScript?
Simply do it with PHP:
<?php
if(!isset($_GET['submit1'])) {
?>
//<form> your form HTML here
<?php
} else {
?>
<p>Your submitted data: <?php print_r($_GET); ?></p>
<?php
}
?>
So your forms are only shown if you have NOT submitted one of them. You might have to adjust the parameters if you have multiple forms, for example
if(!isset($_GET['submit1']) && !isset($_GET['submit2'])) {
Edit: If you want to keep your forms after submitting but only hide it, you could do it that way:
<?php
$formsVisible = !isset($_GET['submit1']));
$formsDisplay = $formsVisible ? 'block' : 'none';
?>
<form style="display:<?php echo $formsDisplay; ?>">
<!-- ... --->
</form>
You need to add a DOM ready event:
if($_GET['submit1']) {
echo '<script type="text/javascript">' . "\n";
echo ' $(function() {' . "\n";
echo ' $("#options").hide();' . "\n";
echo ' });' . "\n";
echo '</script>' . "\n";
}
edit
You are getting a parse error because you're using double quotes, so the php parser is reading the dollar sign as a php variable. I would switch to a single quote php syntax to make your life easier:
if($_GET['submit1']){
echo '<script type="text/javascript">
$(function(){
$("#options").css("display","none");
});
</script>';
}
Be sure to wrap your jquery code in the onLoad function $(function(){};

Categories