Refresh single page PHP element using button - php

I have a single page quote generator, it works by holding the quotes in a 2D array and generating a random number to pull from the matching value in the array using PHP every time that the page is refreshed, I want to change this and make it so that only the element is changed when you press a button, reducing the http requests to the server.
I have tried various "onClick" methods but they never seem to work, I'm assuming that this is something that I should use Javascript (Or any js libraries) for. The function that I want to run when the button is pressed is this:
<?php
$max = max(array_map('count', $arrCSV));
$num = rand(0,$max);
$quote = $arrCSV[0][$num] . "." ;
echo $quote;
?>
Any help is much, much appreciated.

Like, #Dr.Kameleon, this cannot be done with PHP alone.
Using jQuery, you can reload an element like this
$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");
Attach it to the click event of the button
$("button").click(function() {
$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");
});

JQuery's load method could do miracles there.

Here some working example.
Create html page:
<html>
<head>
<title>JS-ajax-PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// Let's use jQuery library:
$(document).ready(function() {
// get element with id refresh, on click do function...
$('#refresh').click(function(evt){
// get element with id report, load content to element
$('#report').load('/time.php');
evt.preventDefault();
})
});
</script>
</head>
<body>
<button id="refresh">Обновить</button>
<div id="report"> </div>
</body>
</html>
and php file time.php:
<?php
echo date("Y-m-d H:i:s");
Enjoy.

Related

pass variable from input box to php

Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission.
function showHint(str)
{
document.getElementById('TK').innerHTML = str;
var str = str
}
</script>
<html>
<head>Inputbox</head>
<title>TEST PAGE </TITLE>
<body>
<input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/>
<?php
$str = var str ;
echo "<a href = 'newpage.php?S=$str'/>" ; ?>
</body>
</html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" >
function process(){
var field1 = 'whatever';
var field2 = 'more whatever';
$.post("go.php",{field:field1,bext_field:field2},function(result){
alert(result);
});
};
</script>
This will alert out whatever you ECHO from GO.PHP.
You will also need a handler like:
onClick="process();"
on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following:
PHP executes before the user has a chance to see the page.
JS let you control what happens after.
Therefore, your problem is that you are trying to use PHP to do something it simply cannot.
Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS.
Think about it like this:
/*
assumes you already have an <a> on the page. if not, you'll
have to create a new <a> element dynamically. (google "mdn createElement"
for help)
*/
function showHint (str) {
document.getElementById('TK').innerHTML = str;
var link = document.getElementById('your-a-link');
link.setAttribute('href', 'newpage.php?S=' + str);
}

get_file_contents refresh div

I loaded a content into a div using php get_file_contents,
now i want to refresh it using ajax but i can't figure how to do it.
Sample code:
<script>
function refreshmydiv(){
...
}
</script>
<div id="mydiv"> <? echo nl2br(htmlspecialchars($myfile)); ?> <div>
Refresh My Div
So, here is one way of doing it. First, the parts:
myrefreshfunction
This function needs to make an AJAX call to refresh.php or another page. Then, it should replace the contents of mydiv with the html that is sent back.
refresh.php
This page needs to return the HTML for the div. It doesn't need to return the whole page, it only needs to return the contents of the div.
In this case, it would just echo get_file_contents and nothing else.
ex.
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Then, the refresh process looks like this:
Your user presses the button to refresh the div.
Your function requests a page.
The page returns ONLY the contents of the div.
Your function replaces the content of the div with the page it just requested.
There are other ways to do this, put this is a very straightforward way to do it.
If you use jQuery, your myrefreshfunction is basically one line of code:
$('mydiv').load('refresh.php');
If you use the Prototype JavaScript framework you can do it this way:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function refreshmydiv() {
new Ajax.Request('/ajax/getdivcontents.php', {
method: 'post' ,
onSuccess: function(request) {
$('mydiv').update(request.responseText);
}
});
}
</script>
<div id="mydiv"> <? echo nl2br(htmlspecialchars($myfile)); ?> <div>
Refresh My Div
This will make an Ajax call when you click on the "Refresh My Div" link. The getdivcontents.php page will create the HTML you wish to display.

Access a JavaScript variable from PHP

I need to access a JavaScript variable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.
UPDATE: OK, I guess I simplified that too much. What I'm trying to do is create a form that will update a Twitter status when submitted. I've got the form working OK, but I want to also add geolocation data. Since I'm using Javascript (specifically, the Google Geolocation API) to get the location, how do I access that information with PHP when I'm submitting the form?
The short answer is you can't.
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
You're doing a $_GET, which is used to retrieve form values:
The built-in $_GET function is used to collect values in a form with method="get".
In other words, if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
If showing data to the user, do a redirect:
<script language="JavaScript">
var tester = "foobar";
document.location="http://www.host.org/myphp.php?test=" + tester;
</script>
or an iframe:
<script language="JavaScript">
var tester = "foobar";
document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>
If you don't need user output, create an iframe with width=0 and height=0.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!.
This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:
// -- index.php
<?php
if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">
var d = new Date();
var timezoneOffset = d.getTimezoneOffset() / 60;
// the cookie expired in 3 hours
d.setTime(d.getTime()+(3*60*60*1000));
var expires = "; expires="+d.toGMTString();
document.cookie = "timezone=" + timezoneOffset + expires + "; path=/";
document.location.href="index.php"
</script>
</html>
<?php
} else {
?>
<html>
<head>
<body>
<?php
if(isset($_COOKIE['timezone'])){
dump_var($_COOKIE['timezone']);
}
}
?>
JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
<script type="text/javascript">
function gotzpl(){
var query = window.location.search.substring(1);
if(query){
}else{
var timez = Intl.DateTimeFormat().resolvedOptions().timeZone;
if(timez != 'undefined'){
window.location = "https://sks.com/searches.php?tzi="+timez;
}
}
}
</script>
<?php
// now retrieve value from URL and use it in PHP;
// This way you can get script value in PHP
$istzg = $_GET['tzi'];
?>
<body onload="gotzpl()">

back button scroll position

After I submit a form the position will return to the top of the window. Instead of going to the previous position.
Looking at using scrolltop to rememeber the positon or do you have a better idea?
I'm using stuff like PHP5, jQuery and MySQL.
First create an anchor in your page where you want the visitor to get to when they submit the form.
Then in your form action or redirect point to file with the anchor
e.g.
<div id="view_from_here" >.....
then
<form action="myfile.php#view_from_here" ....
Check this out:
<script type="text/javascript" src="der/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="der/jquery.cookie.js"></script>
<script type="text/javascript">
function get_position(){
var top_position = document.documentElement.scrollTop;
$.cookie('pos', top_position);
};
function set_position(){
var top_position = $.cookie('pos');
window.scrollTo(0,top_position)
$.cookie('pos', null);
};
</script>
</head>
<body onload="set_position();">
.
.
.
<form method="post" action="" onsubmit="return get_position();">
</form>
If you submit you Form via Ajax it won't change anything (maybe that is an option, if you redirect to the same page anyway). You can also save the position in a Cookie via JavaScript before submitting and retrieve and set the value when the new page is loaded (e.g. with jQuery scrollTo). Or you just set an anchor on your Form field (which is very likely to be the last position the user scrolled to) and scroll back to the form after submit.

print another page from the current page passing a value

hi i need to validate the next page before printing it ...
what i did is i used i frame in the first page and called the page i needed to print
but it fired the query in the first page which should have been fire in the second page after the submission or click of the button ...
so i need to fire the php function after the button click which calls a function in javascript how should i do this?
could anybody help me...
Okay, I am not familiar with your level of PHP knowledge, so I will start with some basics:
PHP is a server-side scripting language. It compiles in real-time when a page is requested. The server processes the HTML and PHP and serves an HTML only page to the browser. You cannot execute PHP code on the client side. There is no way to get PHP code running at the time of a button press without the use of AJAX. You could use AJAZ to make a request to the server at the press of the button and fill the iFrame with the output.
Hope that helps.
so i need to fire the php function after the button click which calls a
function in javascript how should i do
this?
I am not quite clear on why you would need to do this but here it goes...
In the button click handler you want to make an AJAX call. I use jQuery but you can use whatever framework or XMLHttpRequest function you wish.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function ButtonClickHanlder( e ) {
// Prevent the button from doing something it's normal functions(ie submit form if it is a submit)
e.preventDefault();
// Make AJAX Call
$.post("test.php", { call: "callMe" },
function(data){
alert("Data Loaded: " + data);
}
);
}
$(function(){
$('#clicker').click(ButtonClickHanlder);
});
</script>
</head>
<body>
<a id="clicker" href="#">test</a>
</body>
</html>
Reference: http://docs.jquery.com/Ajax
The test.php page
<?php
if(isset($_POST['call']) && $_POST['call'] == 'callMe') {
callMe();
}
function callMe() {
echo "I am a php function. You rang?";
}
?>

Categories