Change page dynamically - php

<?php
$go = $_GET['go'];
if(!empty($go)) {
if(is_file("page/$go.html")) include "page/$go.html";
else echo "<h1>Error 404</h1><p>Strona nie odnaleziona</p><p>Warunek ?go jest niepoprawny</p>";
}
else include "page/start.html";
?>
<script>
$.get('go', function(change) {
$('#center').load('page/<?php echo $go ?>.html');
});
</script>
I have somethng like this but it doesn't work. I just want that the page which is loaded (?go=name) won't refresh whole page

Firstly, that's vulnerable to an LFI vulnerability (Local File Inclusion). Consider what happens when someone enters: http://site.com/file.php?go=../../../../../../../../etc/passwd%00
Also, you can't just echo your filename and expect it to print it out...if you want to include the contents of the page in $go and print out $go, then use:
$go = urldecode([$_GET['go']);
$go = str_replace("/", "", $go);
$go = "page/$go.html";
EDIT: Actually, if you use my above code, they could still access files in the local directory, such as .htpasswd and .htaccess, so just don't let your users include any local files. There are better ways to solve the problem you have.
As for the AJAX, follow jeroen's advice.

You are mixing two ajax functions, $.get and .load and you are missing an event handler.
You will need something like this:
$('#go').live('change', function() {
$('#center').load('page/' + $(this).val() + '.html');
});
I have used live instead of change in case the go button is located in the refreshed section of the page.
Note that I am guessing that you want to refresh a section of your page based on a selection, the question / code isnĀ“t exactly clear about that...

Is this what you want to achieve?
<script type="text/javascript">
$(document).ready(function() {
var getgo = '<?php echo $_GET['go']; ?>';
if(getgo.length) {
$('#center').load('page/'+getgo+'.html');
}
});
</script>
<div id="center"></div>
It will load the contents of page/[your go param].html into #center.

Related

Dynamic div swapping using php/jquery resulting in a page recursion

I am working on making a dynamically loaded website using some php code to swap out content from various other files. While on top of that I am using jquery to beautify this swap out.
Relevant PHP:
<?php
// Set the default name
$page = 'home';
// Specify some disallowed paths
$disallowed_paths = array('js.php','css.php','index.php');
if (!empty($_GET['page'])){
$tmp_page = basename($_GET['page']);
// If it's not a disallowed path, and if the file exists, update $page
if (!in_array($tmp_page, $disallowed_paths) && file_exists("{$tmp_page}.php"))
$page = $tmp_page;
}
// Include $page
if(!file_exists("$page.php")){
$page = 'home';
}
else{
include("$page.php");}
?>
Relevant jquery:
$(function (a) {
var $body = $('body'),
$dynamo = $('.dynamo'),
$guts = $('.guts');
$body.fadeIn('slow');
if (history.pushState) {
var everPushed = false;
$dynamo.on('click', 'a', function (b) {
var toLoad = $(this).attr('href');
history.pushState(null,'',toLoad);
everPushed = true;
loadContent(toLoad);
b.preventDefault();
});
$(window).bind('popstate', function () {
if (everPushed) {
$.getScript(location.href);
}
everPushed = true;
});
} // otherwise, history is not supported, so nothing fancy here.
function loadContent(href) {
$guts.hide('slow', function () {
$guts.load(href, function () {
$guts.show('slow');
});
});
}
a.preventDefault();
});
What is happening is when I link to a page using ?page=about it will work but it will instead of just swapping out the content it will load the entire page including the content inside the dynamically loaded div.
If I were to link straight to about.php it would work beautifully with no fault whatsoever, but anybody who wanted to share that link http://example.com/about.php would get just the content with no css styling.
If I were to change the jquery in "loadContent" to:
$guts.load(href + ' .guts', function () {
EDIT 1:
, ' .guts'
to
+ ' .guts'
It would then work but any script, java, jquery, or the like would not work because it gets stripped out upon content load.
check out http://kazenracing.com/st3
EDIT 2:
It also seems to be that the site does not work properly in the wild either.
No background and none of the icons show up, but it still gets the general problem across.
I can fix that myself, it will just take some time. For now my focus is on the recursion problem.
EDIT 3: Site no longer needs to be worked on, problem never solved but we are letting that project go. So the link no longer is a valid URL.

Load page while PHP is executing

What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".

How can I pass a variable from PHP to javascript

I have a php page with
<?php echo $_SERVER['DOCUMENT_ROOT']?>
Then my javascript is
var data = "Not Set";
$.get("test.php",function(returnData,requestStatus,requestObject){
data = returnData;
alert(data);
});
If I navigate directly to the php page on the site, it displays the data that I need.
I just can't seem to get the data into my javascript.
Am I on the right track and if so where am I going wrong?
Or is there an easier way to get the full filepath when working with a server?
Currently if I run document.location.href in my javascript it returns .
http ://127.0.0.1/etc
The code below will work on ".php" file. NOT ON ".html" file.
You can use the php variable with echo in javascript. For example
alert('<?=$phpvariable?>');
or
alert('<?php echo $phpvariable ?>');
It seems you are overthinking this. There is hardly any need to use ajax, but of course you can and just append() the data from the ajax call to your $('body') and jquery will automatically execute things inside a <script> tag.
var serverRoot = '<?php echo $_SERVER['DOCUMENT_ROOT']?>';
Try following
Instead of GET send $.post request and file don't return any thing just write
$.post("Requestedfile.php",
{
data :data
},
function(data) {
if(data == false)
{
//do something
}
else
{
//do somthing
}
}
);

Add Redirect URL link to JS Function

How can I add redirect URL link to JS function (example form action to : session.php) in below code.
I've tried with another way code, but it still can't function.
$(document).ready(function() {
$("#submit_butt").click(function() {
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Invalid username or password!</p>');
// clear the fields to discourage brute forcing :)
$("#password").val("");
document.forms['login_form'].elements['username'].focus();
});
});
You can try this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
https://developer.mozilla.org/en-US/docs/DOM/window.location
Ref: How to redirect to another webpage in JavaScript/jQuery?
you can use this..
window.location.href = "http://www.google.com";
you can try
<script>
function name(){
window.location ='abc.php';
}
</script>
you can by breaking into php code inside your javascript
$(document).ready(function()
{
<?php
someFunction();
?>
});
but only if your javascript is in a php file so it can be processed by php. So if your linking to a .js file that needs to be changed to .php

PHP publishing JavaScript

I have a PHP script that publishes customised JavaScript based on the parameter, with header type as text/javascript. This PHP URL is included in the src of a <script> tag. However, there seem to be an issue, because the script seems to be nonfunctional. As in, I have an alert inside the script, which should be executed immediately after inclusion, but it's not happening. Where am I going wrong?
Server Side PHP
<?php
//Exploding the path after the file widget to get user details
$expl = explode("/",$_SERVER['PATH_INFO']);
$c=count($expl);
//Handling the cases as widget/a widget//a etc
switch($c) {
case 2:
if(empty($expl[0]) && !(empty($expl[1]))) pumpValid();
else pumpInvalid();
break;
case 3:
if(empty($expl[2]) && !(empty($expl[1])) && empty($expl[0])) pumpValid();
else pumpInvalid();
break;
default:
pumpInvalid();
break;
}
function pumpValid() {
global $expl;
//Checking for a matching account in the urllist
include('embedUrl/urllist.php');
if(isset($customerList[$expl[1]])) {
header("Content-Type: text/javascript");
//Setting the host path for fetching the JS files later. As in stage or vidteq.com
echo "alert('h');";
echo 'var _serverHostUrl="http://'.$_SERVER["SERVER_NAME"].eregi_replace('widget.*','',$_SERVER["REQUEST_URI"]).'";';
}
else
pumpInvalid();
}
function pumpInvalid() {
//Should redirect to error/home page
echo "Are You Nuts";
}
?>
function init() {
alert('hi');
addJSinHead('jquery-1.3.2.min.js');
addJSinHead('OpenLayers.js');
addJSinHead('json2.js');
addJSinHead('dom-drag.js');
addJSinHead('globals.js');
}
function addJSinHead(fileName) {
var head=document.getElementsByTagName('head');
var new=document.createElement('scrpit');
new.src=_serverHostUrl+'/js'+fileName;
new.type='text/javascript';
head.appendChild(new);
}
init();
Inclusion in client side HTML
<script src='http://rak/cvs/widget/cis/' type='text/javascript'></script>
Is the alert that should be executed inside of a function block? If so then you first need to execute the actual function.
Also try copying and pasting the javascript src url directly into the browser's url bar.
If the above didn't help, some code to analyze would be useful.
You can check with Firebug to see if the output of the script is what you expect and that the headers are being sent as you expect.
You'll need to provide some code for further help.
EDIT:
I don't see anywhere that you output a header in php:
header('Content-Type: text/javascript');
EDIT2:
It looks like you're calling the pumpValid function before it's defined.

Categories