This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
Inside a PHP/HTML page i'm trying to start a session in php and then set a value to a session variable, and i'm trying that inside a Javascript function, and in this function there is a if statement, but the php code inside the if statement runs automatically when i go to the page immediately, when i want the code to run only when the user accept the terms...
Here is my code :
HTML :
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
</label>
Javascript :
if(document.getElementById("terms-checkbox").checked){
<?php session_start(); $_SESSION["ITA"] = "Yes"; ?>
window.open('DL.php?App=STOPit');
}
So when i open the php page that contains that previous Javascript code, the $_SESSION["ITA"] variable will be equals to "Yes" even that the condition is not met yet.
Hope someone can help me with that.
That's not how PHP and Javascript work.
PHP runs on the server before anything else. JS runs on the client side.
Without further information:
I suppose your JS code is not a file, but a inline script on the same HTML/PHP page. When your user requests the HTML page, PHP parses it, including the tags inside your JS code.
If you want PHP to do something based on a user action on the browser (document.getElementById) you have to take other routes. Maybe using Ajax, for example -- so your PHP code can do something.
For your better understanding php runs on the server side and javascript runs on the client side.
What you are trying to do is possible if you submit the data using a form or you have to make an ajax call using javascript.
Below is one way of doing something similar.
<?php
session_start();
if(isset($_POST['terms'])) {
$_SESSION["ITA"] = "Yes";
header('Location: DL.php?App=STOPit');
}
?>
<form action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
<input type="submit" value="Submit">
</label>
</form>
Always start your PHP session_start() on the top of your PHP script file.
<?php
session_start();
?>
Here you can continue with your HTML/CSS/JavaScript codes
but the above is mandatory in order to start a session within
your PHP project.
Otherwise you'll be sending header information after the output buffering happend, and you'll end up with an error like this:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
When you have properly initialized a session handler as I described, you can use or do:
$_SESSION['item-name'] = 'value'; // to set a value of a specific session item
echo $_SESSION['item-name']; // retrieve it's value and output it
unset($_SESSION['item-name']); // to delete it from the $_SESSION container
Related
So I have a piece of javascript code in an html document that responds to a button click. I want a new url to open, and if I specify the link in javascript as I've done below, everything works fine.
<input type="submit" id="submitbtn" value="Purchase Module"/>
<script type="text/javascript">
document.getElementById("submitbtn").addEventListener("click",handle_click);
function handle_click() {
var link;
link="http://www.google.com";
window.location.href=link;
}
</script>
Problem is I want to hide the real link on the server side as it includes a username:password. The php script below calls a function (not shown) that generates the link (a string). This also works fine.
<?php
$link=get_page_link();
?>
I want to pass the link string to the javascript and have tried various iterations of
link=<?php echo $link ;?> to no avail. As I understand it you can't pass strings this way and you need to use ajax. That's where I'm stuck. Seems like I need a $_POST on the php side and a $_GET on the java side, but not sure on the specifics. Any help would be appreciated. Thanks.
I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!
Hello I have an option list in html that is created dynamically by php. I want to take the value of the option list withought subbmiting everything and then call another php function to fill another option list. To be more specific I want the user to first pick a University from a database and then to pick a department of that Universe. I 've created dynamicaly the option list for the Uni's by fetching all Uni's from the database and then find the value by javascript. So in the javascript function I want to write php code in order to fetch all the departments from the university. Eveything works fine until I try to call the php function from the javascript.
signup.php
<form>
<table>
.
.
.
<tr>
<td> Ίδρυμα:</td>
<td><select id="selection" name="selection" onchange="selectDep()" >
<?php include './selectUni.php'; ?>
</select> </td>
<td><span id="orgError" style="display: none;"></span> <td>
</tr>
<tr>
<td> Τμήμα:</td>
<td id="dep" name="dep" ></td>
<td><span id="depError" style="display: none;"></span><td>
</tr>
.
.
</table>
</form>
generateDep.js
function selectDep(){
if(document.getElementById('selection').value === "---")
return;
var value=document.getElementById('selection').value;
alert(value);
document.getElementById('dep').innerHTML=" <?php include './selectDep.php'; selectDep("+value+"); ?> ";
return true;
}
the value at the alert is correct
selectDep.php
<?php
//just trying to make this work for now
function selectDep($value){
echo $value;
}
?>
I cannot understand what I am doing wrong. Everything look fine to me. Can you help me?
First You have to understand that the javascript code executes in web browser but the php code executes in web server.
You can use AJAX to fix your problem.
PHP is a server-side scripting language. It is executed on the server, which means the page has to submit values to the server as a trigger. Javascript and HTML are client-side, which means it's all done in the browser without communicating with the server.
To see this in action, right-click on a PHP page in the browser and select to view source. All you will see is the HTML, you will not be able to view any of the PHP code that generates the page. When PHP executes on the server, the result is client-side code (javascript, HTML and maybe CSS) which is sent to the browser.
The browser wouldn't know what to do with PHP code. If you set the inner HTML of an element to some PHP code in client-side script, it won't get executed and all you will achieve is having the browser render the PHP script exactly as you entered it.
In short, the javascript has to submit the selected value back to the server, before the server-side PHP can work out which departments to send back to the browser.
I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I just want to ask. How can I pass a textfield values in a PHP variable within the same page? What I want is to get the variable and I will query this number to get the product's information.
Here's my code:
This is the link that
<td style='text-align: left'>
<?php echo $itemname; ?>
</td>
Below is my modal dialog:
<div id="w" class="easyui-window" title="Price History" data-options="modal:true,closed:true,iconCls:'icon-search'" style="width:500px;height:200px;padding:10px;">
<input type="text" value="" name="prod_id" value=""/> <!-- this will get the values -->
And below again is my jquery:
<script>
$(".id_prod").click(function(){
var id = $(this).attr('data-value');
$('input[name="prod_id"]').val(id) //this will pass the value to my textbox
});
</script>
You need to do this using Ajax.
The reason is that your code PHP is resolved in the server, so when it arrives to the client side it is not gonna be executed any more. What is executed client side is JavaScript.
So, via Ajax you can connect with your server to retrieve the data that you want to get to update the field, and add this product information manipulating the DOM with JavaScript.
UPDATE:
Or if it is not too much information and you don't want to use Ajax, you can print your PHP values into a JavaScript object, and use it then to manipulate the DOM.
That would be something like this:
PHP:
echo "<script type=\"text/javascript\">\n";
echo "items = [";
//this sould be a for with your data and attributes
items+= "{itemname:'"+itemname+"', itemvalue:'"+itemvalue+"'},";
items+= "{itemname:'"+itemname2+"', itemvalue:'"+itemvalue2+"'}"
items+= "]";
echo "</script>\n";
JavaScript:
function clickLink (index){
$("#container").append("NAME:"+ items[index].itemname);
}