php jquery append - php

does anyone know a way to get php working with jquery append()?
say we have
$('.class0').click(function(){
$('.class1').append('<?=PHPCODE?>');
});
How do we get the php to work after append?
Thanks!

Jquery is javascript and it is executed on the browser while php is a server-side script so in theory a PHP script always run first before any javascript. If you wish to run any php script after the page has finished loading (e.g. when a user click on a button), you need to do an AJAX call. ($.get(), $.load(), etc are examples using jquery)
In more details to your editted question:
With your code, the php script you write inside append will be rendered as plain text. Instead, do the ajax call before the append, and store the result of the ajax call in a variable. Then use: append(variable).
You might also be interested to do some DOM manipulation, which is more efficient if you're loading a huge text from your php script. You can return a JSON object from the php script then use a combinations of appends to create the desired result. This reduces the amount of data that needs to be transfered, but the javascript code could be lengthy.

Try this:
Document HTML(index.php)
<?php
include( 'config.php' ); // Example
$foo = "<span style='color:red;'>WTF</span>" //OR <span style="color:red;">WTF</span>
?>
<html>
<head>
<script type="text/javascript">
$.ready(function()
{
$('.element').click(function()
{
$(this).append('<?php echo str_replace("'","\'",$foo);?>');
return false;
});
});
</script>
</head>
<body>
Element
</body>
</html>
Use <?php echo $foo; ?>, <?=$foo;?> not is recomendated.
Escape especial characters, example : ' (simple quot).
Use Smarty Template PHP Framework
Smarty Template PHP Framework
vista.php( MVC OOP )
<?php
class myClass
{
public function myMethodName()
{
$var = '<span>text</span>';
$this->template->assign( 'foo' , $var );
$this->template->display('myTemplate.html');
}
}
?>
vista.php( NO OOP )
<?php
$var = '<span>text</span>';
$smarty = new Smarty;
$smarty->assign( 'foo' , $var );
$smarty->display( 'myTemplate.html' );
?>
myTemplate.html
<html>
<head>
<title>{$title}</title>
</head>
<body>
{if $text}
{$text}
<ul>
{foreach from=$list item=li}
<li>{$li}</li>
{/foreach}
</ul>
{/if}
</body>
</html>
See and read Smarty Documentation

Related

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.

Interesting output in a simple PHP webpage

Here is a very simple PHP page with one javascript function in it. I am seeing the output differently. I am not able to understand why is it behaving that way.
In the code below, x echoes as 012012, but when I pass it into a javascript function and display it in an innerHTML, it displays differently as 5130 ??!!
Can anyone help ?
<?php
$x= date("mY");
echo $x;
?>
<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body <?php echo "onload='myfunc1(".$x.")'>";?>
<div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output
012012<html>
<head>
<script>
function myfunc1(y)
{
div1 = document.getElementById("mydiv1")
div1.innerHTML = y;
}
</script>
</head>
<body onload='myfunc1(012012)'> <div id="mydiv1" style="background:#efefef;border:1px solid green;height:100px;width:100px;text-align:center">
</div>
</body>
</html>
HTML output (screenshot)
Because a number prefixed with a 0 is treated as octal by javascript.
This is happening because 012012 is being treated as an int. But, since it starts with 0, JavaScript treats it as base 8 (octal), and therefore converts it to 5130.
You need to wrap 012012 in quotes, so JavaScript treats it as a string. Also, I suggest only using PHP to echo the value you need, not the entire function call. Makes it slightly easier to debug.
<body onload="myfunc1('<?php echo $x;?>')">
Use Smarty, is a framework template PHP!
PHP code:
<?php
$foo = date('Y');
?>
Simple Print PHP Code
<body onload="myFunctionJS('<?php echo $foo;?>')">
Simple Tags PHP(It is not recommended)
<body onload="myFunctionJS('<?=$foo;?>')">
USE SMARTY TEMPLATE FRAMEWORK
Smarty Template Framework(PHP Code):
<?php
$smarty = new Smarty;
$var = date('Y');
$smarty->assign( 'foo' , $var );
?>
Smarty Template Framework(Template Code):
<body onload="myFunctionJS('{$foo}')">
<body <?php echo "onload='myfunc1(".$x.")'>";?>
should be
<body <?php echo "onload='myfunc1(".$x.")'>";?>>
The body tag is not closed

mix javascript and php

I have a file called: file.php
contained in this file is the following code:
<script type="text/javascript">
//....
var sumJS = 10;
<?php $sumPHP = sumJS ?>
</script>
<?php echo "Sum = " . $sumPHP ?>
How can I assign sumJS for $sumPHP?
If I would like to make this conversely then I would write:
$sumPHP = 10;
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
But how can I re-make this for my problem?
Javascript can change the variables of PHP and vice versa.
Here is an example of that.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php $aphp=1 ?>
<script "text/javascript">document.write("<?php $aphp=2 ?>")
var ajava=1;</script>
<?php echo "aphp= $aphp"; echo "<br>";
echo "<script \"text/javascript\">ajava=2;</script>"
?>
<script "text/javascript">document.write("ajava= "); document.write(ajava)</script>
</body>
</html>
What if I want to assign a php variable to a java variable and vice versa
The above showed that you can assign values to java in php and vice versa by simply writing out an assignment using echo in php and document.write in java. That is how you assign a value.
Mixing actual variables between php and java is not much more complicated. What you do is write an assignment in the language you need to get the value of a variable from and assign it to a variable in the other language. Here is an example of that.
Assign php to java
<?php echo "<script type='text/javascript'>javasum=$phpsum</script>" ?>
assign java to php can be done in two ways
<script type='text/javascript'>var str="<?php $phpsum=";
str=str+javasum; str=str+" ?>";
document.write(str);
</script>
or more conveniently
javasum=<?php echo $phpsum ?>;
Mixing php and javascript to do things other than variable assignments
Javascript can also be mixed in the phpcode to do a javascript function in the phpcode. Say you wanted to use javascript to highlight text only if a condition is met in the php code. But to do this you need to echo the javascript code section. Also use the escape character, \' to include quotes in a echo command. Here is an example of this
Before you get started be sure php content type is in html. In dreamweaver site editor software, a header to do this is automatically included.
<p><span id="htext">htext</span></p>
<?php
$a=5;
echo "<h3> hello world</h3>";
if ($a==5) {
echo "<script type=\"text/javascript\">";
echo "document.getElementById(\"htext\").style=\"background-color:yellow\"";
echo "</script>";
}
?>
<p>is a=5</p>
<p><?php echo $a ?> </p>
$sumPHP is a server-side value, which will be evaluated on the server. Then the server generates page content and sent it to the client. Then browsers receive the page content and evaluate client-side value sumJS.
So you can never assign sumJS for $sumPHP because $sumPHP is calculated before sumJS.
But can do this to show the page:
<?php echo "Sum = "?><script type="text/javascript">document.write(sumJS);</script>
or rather
<script type="text/javascript">document.write('Sum = ' + sumJS);</script>
You're just missing tags
<?php
$sumPHP = 10;
?>
<script type="text/javascript">
var sumJS;
sumJS = <?php echo $sumPHP ?>;
alert(sumJS);
</script>
demo
Sorry that at the moment I do not have the time to write an example. But I believe that this idea will work. Maybe someone here can do a quick test.
Just create a hidden element with a unique id, say a
span with id="uniqueBufferForCommunicatingBetweenPHPandJS" and style="display:none".
Then, with the JS part of the code, write the result into this span by using
document.getElementById("uniqueBufferForCommunicationBetweenPHPandJS").innerHTML = XXX;
You can even write XXX in the form of JSON.
Afterwards, you can use something in PHP like
$bufferspan = $dom->getElementById('uniqueBufferForCommunicationBetweenPHPandJS');
to get the span, and read its content, probably by using
$avariable = $dom->ownerDocument->saveHTML($avariable);
and then interpret the result stored in $avariable. I am not totally sure about the last PHP code.

Best practice: where to put the PHP code?

I do admit this question is going to be a bit vague, but I will try to explain what I'm trying to accomplish by a few examples. I have some PHP code that loads a bunch of variables from the MySQL database, contains some declarations, some functions to quickly output HTML code etc. However I would love to do all that stuff before anything is sent to the client.
So I do:
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
...
</body>
</html>
This is all fine and ok, until I get an error. The echo will not show in the browser because it's before all HTML... So I modified:
<!DOCTYPE>
<html>
<head>
<script>
...
<?php echo $someString; ?>
...
</script>
</head>
<body>
<div class="error_block">
<?php
include("somefile.inc");
function bla()
{
...
}
if (fails)
echo "Error: ...<br />";
?>
</div>
...
</body>
</html>
Now I can actually see errors, which is good. But now the problem arises that in the header, or scrips, I cannot access variables that will be loaded later on in the newly created error_block.
I really don't like splitting the code in the error_clock to some above the HTML document and some in the error_block. And I also don't want to use PHP's die() function which abrubtly ends the execution.
Anyone can give their 2 cents on this issue? Thanks.
If you're looking for an alternate solution, I have one for you. What I like doing is having the logic in before the DOCTYPE
if(error) { $error = "Please do something" }
Than, down in the document I have a div just for the error (Thanks #Dave for the input)
<?php echo $error != '' ? '<div id="error">' . $error . '</div>' : ''; ?>
This div will not appear if there isn't an error (meaning $error is empty) and it makes it easier for you to style the error message the way you would like
#error { color:red; }
If you want to get fancy, you can use some jQuery to hide/show the div so that the error doesn't have to persist.
$('#error').show().delay(7000).fadeOut();
You should look into using try-catch blocks and generating exceptions if you want to do some post-processing with the error message, which includes display.
What is often forgotten is that PHP is an INLINE programming language in essence, this means it is designed to be processed by the server as the server reads down the page, and with this it is designed to be split up into chunks. Recently OOP (Object Oriented Programming) has been introduced to PHP making it more flexible.
So with this information in hand I would take the OOP path in this case and do something like:
<!DOCTYPE>
<?php
include("somefile.inc");
function bla()
{
...
}
function failureError($code){
if(!empty($code)) ...
}
if ($a = $b) {
code goes here
} else {
$code = 'error123';
}
?>
<html>
<head>
<script>
...
<?php failed($code); ?>
...
</script>
</head>
<body>
...
</body>
</html>
By writing using functions you can cut down your development time and group the majority of your code just calling what you need when you need it.
Another way of declaring your error class(es)/functions to help with server response time is to do something like:
if ($a = $b) {
code goes here
} else {
include("errorStuff.php");
}
This will only include the error class(es)/functions when an error is encountered.
Just remember when you're writing PHP with OOP techniques like this that the server will take longer to process the script than if you write inline. The biggest advantage to an OOP basis is it will cut down your development time and if done correctly it will make it easier to administer future updates to your script.

It is possible to include Php variables or URL in Javascript in an If-statement?

I want to make some thing like this
my-php-file.php
$lang = 'es';
my-js-file.js
if ($lang == es)
{
something-magical-happens;
}
or like this:
if (URL == www.mydomain.com/index.php?lang=es)
{
something-magical-happens;
}
you could generate js on-the-fly
my.js.php:
<?php echo "//Yes." ?>
var i = "<?php echo $_GET['lang']; ?>";
function doSomethingWithI(){
alert(i);
}
Now, try to include
<script type="text/javascript" src="my.js.php?lang=es"></script>
in your html and you'll see :)
Edit: Check it in action here: http://h.kissyour.net/so/phpjs/
Edit: Edited example on my server to closer resemble what I wrote here.
Edit: Oh yes. Don't forget to clean your code!
In this specific case, why not simply properly set the document language and then look at that using JavaScript?
<html lang="es">
And in the script:
if (document.documentElement.getAttribute('lang') === 'es') { alert('Spanish'); }
You can – as the accepted answer indicates – generate entire javascript files with PHP. But if you are just trying to access some limited dynamic content, this is often overkill. If you are just trying to access a few variables that need to be PHP generated, inline javascript works fine. Add this to your HTML's head:
<script type="text/javascript">
<?php if( $condition == true ) : ?>
var variable1 = <?php $var1 ?>,
variable2 = <?php $var2 ?>;
<?php else: ?>
var variable1 = <?php $var1Alt ?>,
variable2 = <?php $var2Alt ?>;
<?php endif; ?>
</script>
Just make sure you add this before any linked scripts depend on these variables.

Categories