variable printing inside javascript - php

I have problem with variable printing inside javascript.
variable htmlString printing not working: document.write(htmlString)
<?php $htmlString= htmlspecialchars(file_get_contents('http://google.com'));?>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
var htmlString="<?php echo $htmlString; ?>";
document.write(htmlString);
</script>
</body>
</html>
Edit:
Webpage source result: - Get all google.com inside htmlString the var not printed on the page(I cut the all content of htmlString because its very long)
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
var htmlString="<!doctype html><html><head><metahttp-equiv="content-type" cotring)";
document.write(htmlString);
</script>
</body>
</html>
Thanks

In order to pull remote pages with file_get_contents it requires fopen_wrappers to be enabled. If your host has this disabled and they allow cURL() I would go that route. cURL is also generally faster then file_get_contents, so that may be a deciding factor as well.
EDIT:
The problem you are having, particularly with google, is that it uses JS Code in the webpage. I just var_dump'ed the htmlString and it all displayed fine. But when putting it back into the JavaScript it went caput. The error that came back was an Unterminated String Literal (via Firefox's Error Console) on Line 8. Probably due to some single quotes etc. In my testing I tried htmlentities(), which worked and displayed the data to the browser. The section to change is:
$htmlString= htmlentities(file_get_contents('http://google.com'));
And it should work like you want it to.

Related

"$ is not defined" jQuery bottom with PHP include

They are good practices put jQuery the bottom of the page, before the </ body>, but when you have an include PHP in the middle of the page and in this include I have that jQuery code like this:
[code of index.php]
[include]
<script>
$(function() {
<?php
echo "$('#".$_SESSION['user']['flags']."').attr('selected', true);";
?>
});
</script>
[/include]
[code of index.php including jQuery.js here before </body>]
Firebug tells me that $ is not defined. I used "defer" but it does not work either. I searched Stackoverflow but do not know how to fix it.
Here my code:
index.php
<!doctype html>
<html class="no-js" lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="robots" content="noodp, noydir">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body id="body">
<?php
include './step1.php';
?>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
step1.php
<script>
$(function() {
<?php
echo "$('#".$_SESSION['user']['flags']."').attr('selected', true);";
?>
});
</script>
If you replace the "$(function(){" section with window.onload you can ensure that all script files have been loaded before attempting to fire your function.
However, be aware that this fires much later that jQuery's document.ready. jQuery's method fires when the dom is loaded whereas window.onload waits until the whole document and it's scripts have been loaded.
More info and example here:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
You included the jQuery.js after the inclusion of that script. Move your jQuery.js include above include statement that contains your js code.
Answer to the problem:
You have included the step1.php before including jQuery.js. This is why it won't work. Include jQuery.js before including step1.php.
Answer regarding jQuery in end of HTML body:
Yes, it's a good practice but that seems to me as a micro-optimization. As it would speed up the loadtime. But you can only do that if you include your written jQuery code after including the actual jQuery.js library. Since you're not able to do that in the current contruction, you need to change the order to make it work.
Otherwise general debugging techniques apply:
Check your browser. Right click. Inspect element. Open tab network. Make sure the jQuery.js file is really included so you'll have a HTTP status 200 code on this request.
Make sure jQuery is really inside jQuery.js and the file is not empty or having other contents.
Make sure jQuery not included twice.
Also checkout:
https://api.jquery.com/jquery.noconflict/
http://www.sitepoint.com/types-document-ready/
or try:
jQuery(document).ready(function(){ /* [code here] */ });

Jquery load() works for html but not for php page

I'm trying to load a php page in a div with Jquery. The following code works perfectly with a html page (Test.html) but not with a php page (Test.php with exactly the same code as Test.html): when I clik on the button nothing occurs. My php page loads correctly outside the Jquery code. I even tried to use a url instead of a relative link without any success.
$(function() {
$('#Button').click(function() {
$('#Div').load('Test.php');
});
});
Thanks in advance for your answers.
Here is the code of Test.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
Test Test
</body>
</html>

Very simple Javascript partial page refresh calling a .php page not working

I've combed the internet for a few hours and still cannot make this simple example work. I hope somebody can assist me. I'm trying to use Javascript to display the contents of a php file. The display should be refreshed often as ultimately it will be used to display text matches from a MySql db that match the characters entered in a search bar (similar to Google's search bar). I'll use setinterval for that but I am not there yet. My issue is that I have minial javascript/AJAX experience and just cannot make it work. I've dumbed it down to a bare bones request and still cannot make it work. Please suggest what isn't working:
The index.html where the content should be viewable is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$().ready(function() {
$("#dynamic").load("blasty.php");
});
</script>
<div id="dynamic"></div>
</div>
</body>
</html>
And blasty.php contains:
<?php
echo "hello cruel world!";
?>
Thanks in advance!
Make sure your blasty.php file is on the same domain.
Also, to help debug javascript, right click in Chrome or Firefox and go Inspect Element. Then go to the Console window and it will display most errors.
I also recommend this youtube video about javascript. I it helped me bridge the gap on some javasrcipt gotchas. http://www.youtube.com/watch?v=ljNi8nS5TtQ
Here is a link about debuggers: https://developers.google.com/chrome-developer-tools/
As #Explosion Pills said, FireFox's Firebug is another great option. I will use both to help debug javascript. Firebug is nice because under the Net tab it will display the acutal http requests as they happen in the background, with the params, response, header info, etc.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#dynamic").load("blasty.php");
});
</script>
<div id="dynamic"></div>
</div>
</body>
</html>
You are missing the document variable in the $().
<script type="text/javascript">
$(document).ready(function() {
$("#dynamic").load("blasty.php");
});
</script>
Visually that's the only issue I see.
I use $.get instead of $.load.
Try something like this:
$.get("blasty.php",
{ nbRandom: Math.random() },
function(data){
$("#dynamic").html(data);
});
nbRandom is to prevent caching in IE.
Use Firebug to make sure there is a response from the AJAX and go from there.

Display a GIF while loading a Facebook app

I have a lot of server code (PHP) going on in my first page of the Facebook app.
I wan't the users to see a loading animation while waiting for the page.
I've seen many examples here of how to preload a page (using ajax or simply jQuery) but this is different, as I said, the page itself is generated on the server, and while that goes on, the user only sees a white blank page.
I tried to wrap my main page with another php page:
<?php
include_once 'functions.php';
session_start();
$_SESSION['fb'] = new fb();
function phponload(){
echo
'<script>
$(function(){
$("#mwrapper").load("main.php");
});
</script>';
}
?>
<html>
<head>
<script type="text/javascript">
function delayer(){
document.write("<?php phponload();?>");
}
</script>
<link href='styles/default.css' rel='stylesheet' type='text/css' />
<img class='mainload' src='images/loading.gif'></img>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js'></script>
<link rel='stylesheet' type='text/css' href='plugins/clock/clock.css' />
</head>
<body onload='setTimeout("delayer()",1000);'>
<div id='mwrapper'>
</div>
</body>
</html>
now the main php page (main.php) has something like:
<!DOCTYPE html>
<html xmlns:fb="http://ogp.me/ns/fb#">
<meta name="google-site-verification" content="Hyqgg60NTPNA7Q9Z5y9TtezUmwhiEomwZLJDt43Ki2g" />
<!--<img class='mainload' src='images/loading.gif'></img>-->
<?php
include_once 'functions.php';
include 'res/views/getTables.php';
define('TXT_QUESTIONS_NUM', 43);
session_start();
{... more PHP code ... }
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"> </script>
<script src='scripts/menuItems.js'></script>
<script src='scripts/main.js'></script>
<link href='styles/jquery.ui.smooth.theme.css' rel='stylesheet' type='text/css'/>
<script type="text/javascript" src="plugins/clock/clock.js"></script>
<link rel="icon" href="images/favicon.ico">
</head>
<div class='container' id='main'>
...
</div>
</body>
</html>
Right now, all the code does is loop the GIF - but does not load main.php :(
Thank you!
Is there any error on the Chrome/Firebug console?
I don't understand why you generate the loader JS code in the PHP function (you could put it directly in HTML), but by doing so you are putting a multiline block between the quotes on document.write function, which causes an error.
However, I think the issue is that the browser is interpreting the inserted </script> as the end of the HTML tag, so what's after (the end of the document.write call and the delayer function) are treated as HTML and not as Javascript.
EDIT: Complementing the answer, here's the code I'd use to load another page:
function delayer(){
$("#mwrapper").load("main.php", function(){
$('.mainload').remove();
});
}
Didn't need any PHP generation. Also, the second argument to the load function is a callback called when the load is finish, in this case I used to remove the loading GIF.

PHP + JQuery - How to use these two together? Please see my example

I have a php based website. As in, all of the pages html is output via php.
Here is a simple example:
<?php
ob_start();
$pageStart = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MY WEBSITE PAGE</title>
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
What i would like to do is make use of some jquery in this page.
So naturally my first attempt was to include the script inside of the php variable like so:
<?php
ob_start();
$pageStart = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script type="text/javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
Now, I use dreamweavers code editor, which due to the syntax highlighting feature, will point out the masses of syntax errors produced in this.
So i at first attempted to slash out these errors. This failed.
So i tried changing the "s to 's, and visa versa, until the errors were gone. This failed too as it seems the script will not validate in this manner.
So i read a few tutorials, and found this one:
JavaScript and PHP may each bring great potential to any Web development effort, but they don't always play nice together. Read about the problems.
And the way I understand it, is that you'd need to include the js rather than have it as part of your php directly.
So have a file called page.php and another called jquery.php. So I decided to try and modify this idea to suite my problem.
So i started with something like this - index.php:
<?php
ob_start();
$pageStart = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MY WEBSITE PAGE</title>
'. include $_SERVER['DOCUMENT_ROOT'] . '/../../path/to/include/datepicker.php'.'
</head>
<body>
<p>CONTENT</p>
</body>
</html>
';
echo $pageStart;
exit;
?>
And - datepicker.php:
<script language="Javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
<script language="Javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#birthday').datepicker();
})
}
</script>
Now there are no syntax errors in either page, great... So I try it, half expecting things to finally just work...
Nope... Fatal Error: failed to open stream: No such file or directory blah blah. This error relates to the include that i added. So okay, even though the file is there, it is not being validated as php because there are no opening and closing php tags.
So I add them... Annnd... A page full of syntax errors again!
So my question is this:
Could some please share some knowledge and explain to me roughly how this process actually works. Whats the deal with all the syntax errors, and how are you supposed to go about a task like this?
I believe it is possible, and yes it would ceratinly be easier if i was not outputting the entire html via php. But this is a simple example and my actual design is alot more complex. It requires for the different parts of the page to be broken up into variables, in order to place those bits and peices when needed, dynamically.
Any input, suggestions, or insight would be greatly appreciated; and any links to pages or tutorials that cover this would also be greatly appreciated.
Thank You!!
All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag. I actually use PHP along with jQuery all the time. And this is how I do it. In your code above, it looks like you have some escaping issues with your code. And it also looks like you want to hold the header of the page in a PHP variable then print it out. You don't have to do all that. Just put the plain text in your PHP file without any php tags and it will work. Also, you are using an old version of jQuery. Should probably use the latest version. But, if you need it stored in a PHP variable so that you can print it out, do this:
SO, here is some code to get you started.
<?php
$pageStart = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>MY WEBSITE PAGE</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#date").datepicker();
});
</script>
</head>
<body>
<input type="text" id="date" name="date" />
</body>
</html>';
print $pageStart;
?>
<head>
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// javascript & jquery code
// even better would be if you would put client code in separate file!!!
});
</script>
</head>
<body>
<?php
echo "bla bla bla";
?>
</body>
and +1111 to # Heera's comment
You're missing the basics's.
Use Heredoc. Thousands of syntax errors will be gone.
See the heredoc version of your pages,
http://pastie.org/3412925
http://pastie.org/3412929
http://pastie.org/3412935 // Here you have used include to contact. include does not return anything. It just includes. So Its changed differently.
I think it should be
. (include ($_SERVER['DOCUMENT_ROOT'] . '/../../path/to/include/datepicker.php')) .
otherwise php will try to include all the stuff after until the l is reached (tags will be interpreted as part of the file name).
also, in terms of the php code, after the file is included (on success), the include statement translates into 1 as a number, instead of the content of the file.
use
<? $abc <<<qwerty
...
...
...
qwerty;
return qwerty;
?>
for all the files that you want to include

Categories