Search code examples
phpjavascripthtmlajaxprepend

how to store html and php code inside a php variable to be echoed to a html page


I'm trying to echo a whole html string with some php code in it to a html page, the problem is, i can't store the string to a php variable;

prependapp.php

 <?php
include("db.php");
include("tolink.php");

$result=mysql_query("select * from messages order by msg_id desc");
$row=mysql_fetch_array($result);
$id=$row['msg_id'];
$msg=$row['message'];
$date=$row['date_sent'];

$msg= nl2br($msg);
$msg="<br>{$msg}<br>{$date}";


$app = <<<EOD

<li class="bar<?php echo $id; ?>">
<div align="left" class="post_box">
<span style="padding:10px"><?php echo $msg; ?> </span>
<span class="delete_button"><a href="#" id="<?php echo $id; ?>" class="delete_update">X</a></span>
<span class='feed_link'><a href="#" class="comment" id="<?php echo $id; ?>">comment</a></span>
</div>
<div id='expand_box'>
<div id='expand_url'></div>
</div>
<div id="fullbox" class="fullbox<?php echo $id; ?>">
<div id="commentload<?php echo $id; ?>" >

</div>
<div class="comment_box" id="c<?php echo $id; ?>">
<form method="post" action="" name="<?php echo $id; ?>">
<textarea class="text_area" name="comment_value" id="textarea<?php echo $id; ?>">
</textarea><br />
<input type="submit" value=" Comment " class="comment_submit" id="<?php echo $id; ?>"/>
</form>
</div>
</div>


</li> 

EOD;


echo $app;
?>

javascript inside the html page

    <script>
    $(document).ready(function() {
        $("#formID").validationEngine({
            ajaxSubmit: true,
            ajaxSubmitFile: "update_ajax.php",
            success : function() { 
            alert("success exe!");
            $("ol#update").load("prependapp.php");
            $("ol#update li:first").slideDown("slow");
            document.getElementById('content').value='';
            $('#content').value='';
            $('#content').focus();
            alert("success exe");
            }, 
            failure : function() { alert("success fail"); }
        })

    });
    </script>

the "test" on my prepend always shows the problem is the $app doesn't, is there any way for me to prepend large html code w/ some php code inside it to my html page?


Solution

  • You can't use PHP code in javascript part. Please note PHP would be rendered in server side and javascript would be executed in client browser. So, browser does not have access to any PHP variables and objects.

    However, you could use AJAX. For example:

    $.ajax({
        url : "/server/prepend.php",
        success : function(response)
        {
            $("ol#update").prepend(response);
        },
    });
    

    Would execute php code in server side and prepends the result in ol#update tag.