innerHTML and PHP - php

I want to do some innerHTML replacements, but using PHP includes, I dont get how. I have done innerHTML replacements before, just not with PHP.
I have:
var xmlHttp
function DisplayAerialProductListing()
{
var strStartCode="<p></p>";
document.getElementById("txtData").innerHTML= strStartCode;
var code="";
code = code + "<?php include 'newpage.inc'; ?>";
document.getElementById("txtData").innerHTML= code;
}
I have the 'txtData' Div as:
initially and I want to replace with code from the .inc I mention. I use .inc to separate out pieces of the site and to make like easier for the designer so they dont go breaking stuff!
In the .inc I just have HELLO for now.
It doesn't work. What is the trick?

PHP is processed server-side; Javascript is processed client-side. You can't insert PHP code via Javascript because you've already left the server. Normally what you'd do is use AJAX to run the PHP code on the server and then insert the results dynamically into the page.

Using jQuery, you can nail that almost effortlessly:
<p id="myParagraph"></p>
<script>
//when the DOM is ready
$(document).ready(function() {
//replace contents of p id="myParagraph" with output of specified script
$('#myParagraph').load('myPage.php');
});
</script>
Still, make sure you understand the difference between client and server as per #Dav's answer.
See http://docs.jquery.com/Ajax

<script style="text/javascript" language="javascript">
<!--
function check_country()
{
var sel_country = document.getElementById("country");
if(sel_country.value == "US")
{
<?php
$query = "SELECT stateName, stateAbbrev
FROM states
WHERE stateEnabled = '1'
ORDER BY stateName ASC";
$result = mysql_query($query);
$prov = "<select name=\"state\" id=\"state\" class=\"widthed\">";
while($row = mysql_fetch_row($result))
{
$prov .= "<option value=\"$row[1]\">$row[0]</option>";
}
$prov .= "</select>";
?>
document.getElementById("tab1").rows[2].cells[3].innerHTML = "*State:";
document.getElementById("tab1").rows[3].cells[0].innerHTML = "*Zip Code:";
document.getElementById("tab1").rows[2].cells[4].innerHTML = <?php echo $prov; ?>;
}
}
-->
</script>

That will work as long as your JavaScript file is parsed by PHP, ie. with an .htaccess that says SetHandler application/x-httpd-php .js. You'll want to escape the text inside the include, so it may be better to use PHP's file_get_contents() and addslashes(). Here's an example of how to super sanitize a string in PHP that is destined for JavaScript: http://sixohthree.com/241/escaping
An alternate solution would be to load the page content via XMLHttpRequest.

Related

PHP + MySQL + Tooltip

I wanna show tooltip with query data in php.
My php code is,
echo "<div class='tooltip' id='".$row['id']."' title='title1'>".$row['name']."</div>";
My Script is,
$(function() {
$('.tooltip').tooltip({
content:function()
{
var id =$(this)[0].id;
<?php
$qry3 = "SELECT phone_no FROM history WHERE id='?>id<?php' GROUP BY name";
$exc3 = mysql_query ($qry3,$con);
$num3 = mysql_num_rows($exc3);
while($rows3 = mysql_fetch_array($exc3))
{
array_push($name,'"'.$rows3[0].'"');
}
echo "return ".$name;
?>
}});
});
Where is my problem?
I think you are mixing up Javascript and PHP here. Your current PHP code get's executed only once when the server sends the Javascript to your browser. This cannot work.
You can either store the tooltip for each HTML element e.g. in the title tag or you should load it dynamically whenever the tooltip should be shown. You would do this via an AJAX call to a PHP file (and not by putting the PHP code in the JS file).

How to execute PHP code within JavaScript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>

How do I embed PHP code in JavaScript?

How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

translate rss-feed that was grabbed by cURL

my most trusted programmers and thank for all the help!
I grab rss-feed by jquery-ajax using php curl. It's loading very nicely directly on the page. However, I would like to translate the text, that is now html, title within h2 and text within p, wrapped by a div-container.
Google's api-script for translation doesn't seem to run after the content was put into the div. Really nothing happens. I tried both putting the script in the ajax-url-file and the file that the content is displayed on.
I used .live(), but no result.
Any idea?
Thanks!
--
In one of the methods I create a table i mysql and put in title, link and text. After that I echo the table.
$query3 = mysql_query("SELECT * FROM temp_rss_$id") or die("$error_msg");
while ($row3 = mysql_fetch_array($query3)) {
$title = htmlentities($row3['title']);
$text = htmlentities($row3['text']);
$link = $row3['link'];
echo "
$titel
$text
";
}
The title is within in a h2 and an anchor, and the text is within a p.
Using simple jquery, this method without ajax, to grab this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file);
});
Works like a charm. Then there's the google-api-script:
function initialize() {
var text = document.getElementById('media').innerHTML;
google.language.detect(text, function(result) {
if (!result.error && result.language) {
google.language.translate(text, result.language, "en", function(result) {
var translated = document.getElementById("media");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
});
}
google.setOnLoadCallback(initialize);
It doesn't load the google-script. What can be done? Of course it does work if I put the text directly on the page, without loading another file. Using ajax and append(result) instead of .load doesn't make a difference. Any idea?
Thanks!
You can call that function after the .load() runs, as it's callback, like this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file, initialize);
});
This will call the initialize function once the .load() has completed and the new content in the #media element is there and ready to translate.

Is there a way to include PHP value inside a javascript function?

I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script.
for eg:
<?
$divtohide = "adiv";
?>
<script language="javascript">
function hidediv($divtohide) {
................
}
</script>
Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal:
function hidediv(divtohide) {
// Your code may differ here, mine's just for example
document.getElementById(divtohide).style.display = 'none';
}
And print out the PHP variable only when you're calling it, within a pair of quotes:
hidediv("<?php echo addslashes($divtohide); ?>");
addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break.
as BoltClock wrote, use php to pass the variable.
but you can do it by most simple way, just write hidediv("<?=$divtohide?>")
<script type="text/javascript">
function hidediv() {
divobj = document.getElementById('<?= $divtohide ?>');
divobj.style.display = 'none';
}
</script>

Categories