I am making a web page which will allow users to input and view data for different dates, and to change the date, there are two buttons, one of which will display the previous day, and one which will show the next day. I know that I can do this by submitting forms and reloading the page every time they press one of these buttons, but I would rather use javascript and not have to submit a form, but I am having troubles getting it to work. Currently, I have the two buttons, and the date stored in a PHP variable, as shown in my code below:
<script>
function init() {
<? $nutrDate = $this->parseDate(date('m/d/Y')); ?>
}
function nutrPrevDay() {
<? $nutrDate = mktime(0, 0, 0, date('m',$nutrDate), date('d',$nutrDate)-1, date('Y',$nutrDate)); ?>
alert("<? echo(date("m/d/y", $nutrDate)) ?>");
}
function nutrNextDay() {
<? $nutrDate = mktime(0, 0, 0, date('m',$nutrDate), date('d',$nutrDate)+1, date('Y',$nutrDate)); ?>
}
window.onload = init;
</script>
<p style="text-align:center; font-size:14px; color:#03F">
<button onclick="nutrPrevDay()" style="width:200px" >< Show Previous Day</button>
<? echo(date('m/d/Y', $nutrDate)) ?>
<button onclick="nutrNextDay()" style="width:200px">Show Next Day ></button>
</p>
I have the alert in the nutrPrevDay() only as debugging. What happens is when I click on the button, the alert shows that the day is correctly decreased (for example from May 17 to May 16), but only decreases one day, and not one day for every click. Also, I do not know how to make the text on the page (created by the line ) change to display the new date after a button is clicked.
So here are my questions:
1) Is it possible to dynamically change data (such as text, and in the future, SQL queries) on a page using javascript without having to reload a page when clicking on a button?
2) If possible, how can I make those changes?
3) How can I fix this so that it will increment and decrement through dates every time a button is clicked?
Q1:
Yes, it is possible, AJAX is probably what you're looking for.
Q2:
Well, first of all you have to learn that JavaScript works at client side while PHP works at server side. With that in mind, you can't expect that php scripts are executed when you click a button just because you wrote them inside javascript functions.
The most you can do is print something from a PHP script into a JavaScript script. And your script fails in that, except for the alert part. Example:
<script>
function javascriptFunction(){
// This php script, will be executed when you call your page, however $nutrDate is an assigned php variable, javascript will never know about it;
<?php $foo = 'bar'; ?>
// This will give you a javascript error because $foo is a string
var foo = <?php echo $foo; ?>;
// This is the code which will do the expected, notice the quotes.
var foo = '<?php echo $foo; ?>';
// If you have a single quote inside $foo, it will break javascript
<?php $foo = "ba'r";
var foo = '<?php echo $foo; ?>';
}
</script>
Q3:
The idea is to make an AJAX request every time your buttons click event is triggered... This is the same as saying, when you click a button, you call a javascript function which will make a request to some other page and get something from it if the request is successful. Here the example:
<script>
var current = <? echo time(); ?>;
function requestSomething(action){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
// readyState info: http://www.devguru.com/technologies/xmldom/quickref/httpRequest_readyState.html
if (xmlhttp.readyState==4 && xmlhttp.status==200){
// this is where we tell where the result will appear
document.getElementById("current").innerHTML=xmlhttp.responseText;
current = xmlhttp.responseText;
}
}
xmlhttp.open("GET","somescript.php?action="+action+'&curday='+current,true);
xmlhttp.send();
}
</script>
<p style="text-align:center; font-size:14px; color:#03F">
<button onclick="requestSomething('decrease')" style="width:200px" >< Show Previous Day</button>
<!-- this is where the result will appear -->
<span id="current"></span>
<button onclick="requestSomething('increase')" style="width:200px">Show Next Day ></button>
</p>
Now, at your somescript.php file,
<?php
if(isset($_GET['action'])){
if($_GET['action'] == 'increase'){
// your increasing day logic here
} elseif ($_GET['action'] == 'decrease'){
// decreasing logic here
} else {
// whatever...
}
}
?>
Note: This is almost written from scratch and with some copy/past from here and there, and didn't check if the code actually works... It is just a guideline...
Hope it helps.
You don't need Ajax for this. There is very little you can do with PHP that you can't do with Javascript - you should only use Ajax when you absolutely need to communicate with the server (ex: need something from the database, etc.). Even if you may be using Ajax a later point you shouldn't use it everywhere, especially when a simple script may be able to solve your problems.
As it so happens Javascript has a number of built-in date functions that are every bit as powerful as PHP's.... and if they don't do what you need out of the box you can easily write your own.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Keep it simple.
Related
I have a button that runs a PHP function after the user onClicks. This is achieved using the POST method (as illustrated below). The user clicks on the button and the PHP function runs correctly, however, I want the user to be able to click the button multiple times and for the function to run multiple time. The function cannot over-ride its last result/outcome (so basically the result is echoed/printed each time the user clicks the button and the previous results are not overwritten).
Here is a section of my code, as follows:
<?php
function onClickArchive($detail_locator){
for ($x = 0; $x <= 34; $x++) {
echo "<li><br />";
kal_generator($detail_locator);
echo "</li>";
}
}
if(isset($_POST['load_more'])){
onClickArchive($detail_locator);
}
?>
</ul>
<div id="reload_section">
<center><br />
<form method="post">
<input type="submit" value="Load More" name="load_more" class="load_more_content" />
</form>
</center>
</div>
There are multiple methods to potentially solve this. One option would be to make the client send the existing data back when the button is pressed so you can append the new data to it without overwriting it.
The other option is to use AJAX to call the method and append to the existing data client side.
Use/Try this PHP Function:
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Usage:
setInterval(function(){
echo "I will echo many times!";
}, 1000);
It is like in setInterval in JavaScript
setInterval(Function(), seconds);
you need to make use of Jquery.
firstly use .load() method which will loads the data from server then use
.append() method which will add the resulting data to the selected element.
$('.load_more_content').click({
$('#reload_section').append($('<div />').load('sample.php'));
});
I am building an application. The main purpose of my work is to change an object in the php page according to the database entries.
I have one php file ajax.php. It will query the database table and return the value to my other file main.php
The main page uses ajax to query the database. And depending on the database return it will show some images to some positions in the php page.
Example: if the return value from the database query is 2: it will show image at (x1,y1) position and it will blink, and open one small window.
If the return value from the database query is 3: it will show image at (x2,y2) position and it will blink and open one window2
I am not being able to pass the ajax query value to my php portion. Only if I want to ptint the value in then it is possible.
But I want to do something like
if ($returnvalue == 1)
window.open("window1");
blink_image1();
if ($returnvalue == 2)
window.open("window2");
blink_image2();
Please help me.
Following are the code snippet:
ajax.php
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','user','password','database');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql='SELECT id FROM table_name order by timedate asc' ;
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$value = $row['id'];
}
echo $value;
mysqli_close($con);
?>
main.php
<html>
<head>
<IMG STYLE="position:absolute; TOP:135px; LEFT:350px; WIDTH:900px; HEIGHT:500px"SRC="testrect1.php"/>
<script>
var refreshtime=10000;
function showUser(str)
{
setTimeout(showUser,refreshtime);
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
var msg=document.getElementById("txtHint");
}
}
xmlhttp.open("GET","ajax.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body onload="showUser(this.value)">
<div id="txtHint"></p> </div>
<?php
/*
I need the return value here.. So that I can do
if ($return_val == 1)
Blink_image1();
open_window1();
.
if ($return_val == 2)
Blink_image2();
open_window2();
*/
?>
</body>
</html>
Please help me..
It looks like you're trying to pass back the AJAX request to the PHP file as the page is still loading. That will not work. PHP executes on the server, but javascript executes in the user's browser. That means you can't have javascript generated by a file send back information to the file that's generating it, because there is no way for the result to get there.
Think of it like sending a boat across a river: if you get to the other side, you may notice that you don't have a rope to tie the boat up with. However, you can't then add the rope to the boat, because it's already there with you; you need to either plan ahead ("I should really bring a rope with me") or send for another boat to bring you a rope.
What you can do instead is one of three things, in the order in which I would recommend them:
Since you want the information displayed at pageload anyway, you can simply put the code in the same page as you want it to appear. So in your code, where you put your comment about "here's where I need this to happen," put your database call and logic there, rather than in a separate ajax.php file.
Put the logic for what to display inside ajax.php, so that instead of sending the number to the browser, you're sending what it is you want to display.
Put the logic for what to display inside your javascript function.
<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>
Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance
You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this
In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.
I have a column that has a button that when pressed, links to a URL set in PHP. I want to add a checkbox next to that button so that if it's checked when a user presses the button, it will take them to an alternate url. The PHP code setting the url:
<?php
$link = 'http://www.example.com';
?>
I realize that the code needs to be in javascript, which I don't know. I know only a tiny bit of php, so any help would be apprciated.
To clarify: (and of course I know this code will never work)
What I want to do is this:
<?php
If (checkbox is checked) {
$link = 'http://www.google.com';
} else {
$link = 'http://www.example.com';
}
?>
There is probably another way to do what you want to achieve. The value of the checkbox should be sent to a single php script on the server with the rest of the form's fields' values. Then you can use the checkbox's value (boolean) in php and do what you need to do accordingly, possibly requiring external scripts.
Checkbox value is not sent to server with form submit if it is not checked.
So, you can use something like this:
<?php
if (isset($_POST['checkbox_name'])) {
$link = 'http://www.google.com';
}else{
$link = 'http://www.example.com';
}
?>
Include the jQuery from Google:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
Then write the redirect function which you call after clicking the button;
<script>
function foo() {
if ($('#checkbox').is(':checked')) {
//redirect to google.com
window.location = "http://www.google.com/";
} else {
window.location = "http://www.example.com/"
}
}
</script>
And finaly your button should look like this:
<button onclick="foo();" >Your button</button>
This code assumes your checkbox has an id "checkbox".
Also, I don't think that what you're trying to do should be done with PHP - so you should learn Javascript/jQuery straight away instead of writing code the way it shouldn't be written.
Example: http://jsfiddle.net/5bdae/
Using jQuery this is fairly simple. You bind a function to the link, this function works out whether the checkbox is checked, if it is it links to one place, otherwise it links to another.
For an HTML structure like this:
<input id='myCheckbox' type="checkbox" name="box" value="box" />
<a href='#' id='myLink'>My Link</a>
The jQuery would be:
$('#myLink').click(function(event){
event.preventDefault();
if ($('#myCheckbox').is(':checked')){
window.location.href='http://www.example.com';
} else {
window.location.href='http://www.ask.com';
}
});
This could would go outside of the PHP tags, and you would need to include jQuery in your code.