I am using a php file to create a page that allows me to manage mysql entries. The page fetches the entries from the database and lists them which I have working fine. I am trying to add a button that allows me to "accept" an entry which changes its status value to 1 from 0.
It is working fine, except when I refresh the page, it automatically is executing the javascript function which should be an onclick event. Am I missing something incredibly simple or something. I have been looking at this for 2 days now and have rewritten it several times without success as well as extensive googling to find an answer.
My button:
<input type='submit' name='acceptbut' id='acceptbut' value='Accept'></input>
I am thinking the problem has something to do with either the location.reload or something else.
<script type="text/javascript">
function setAccept() {
<?php
$query = "UPDATE regiments SET status=1 WHERE memberID=$mid";
mysqli_query($connect, $query);
?>
location.reload(true);
}
document.getElementById('acceptbut').onclick = setAccept;
</script>
I have also tried messing with an inline onclick but it is not working either
My confusion is why is the function running if im not actually calling it.
Your PHP executes on the server every time the page is requested. The fact that the PHP is located inside a Javascript function is not relevant.
The PHP server parses the file, finds any PHP in it, runs the PHP on the server, then sends the result to the browser.
If you want to execute some PHP only when a Javascript function is executed in the browser, then you have to make an Ajax call from the Javascript to your server and have the Ajax call request a PHP page that can then run the desired PHP and return a result (if necessary) back to the browser's Javascript.
Keep in mind that in your setup, PHP executes on the server, then the resulting page (without any PHP in it) is sent to the browser. The browser then executes appropriate Javascript in the web page as events occur. The only way to execute code on the server at that point is to make an Ajax call to the server.
You are confusing Client and Server side. Look at this:
function javascriptFunction()
{
<?php echo date("Y"); ?>
return true;
}
The above block of code gets executed in PHP. How? Each line of the above code is treated as a sequence of characters and is sent to the cout (standard output). The small snippet inside the <?php...?> gets executed by PHP and if there are any output, it also is sent to standard output. Only when the characters are sent from server to the client side (browser), the browser starts interpreting them. Which results in a code inside <script type='text/javascript'>..</script> to be interpreted as a JS snippet. Now, bear in mind: EVERY PHP CODE GETS EXECUTED BEFORE THERE ANY THING AS JS, CSS or HTML. PHP SEES EVERYTHING AS EITHER String, Integer/Double or Boolean (etc.).
What you should do?
Learn what is AJAX, and try to learn its best practices. You'll amaze at its excellence.
Related
I am new to web development and I am trying to build my first website.
I am having some troubles because web development is dependant on several programming languages like PHP and JS, and the most difficult part for me is to communicate between these languages.
For example, I am trying to create a function that compresses a folder and generate a download link to that new archive, this can be easily done by PHP. However, when the user clicks the zip button, I also wish to display a pop-up window that tells the user to wait while the folder is being compressed, and when the compression is done I want to change the text on that pop-up and display the download link, and this, of course, requires JS.
I've tried many solutions but none of them seemed perfect for me, and I feel like that these solutions are quick and dirty, which I don't want.
If there is a secret I do not know, please tell me about so I can finally work with these languages as if they are a single language.
Also, if you can help me with my current problem, I would be extra grateful.
I just want to know how to construct a form that can call the JS function that displays the pop-up, then calls the PHP Zip_Folder function, and once the PHP function is done, I want to display the download link on the pop-up window.
This is my form code: (It only calls the javascript function that displays the pop-up)
<input type = 'button' onclick = 'Show_PopUP(\"Folder_to_zip\")' value = 'Download Folder'>
And this is the Show_PopUP function code:
function Show_PopUP(folder) {
var e = document.getElementById('Folder_Download_PopUp');
if(e.style.display == 'block')
e.style.display = 'none';
else {
e.style.display = 'block';}}
I already have the PHP function that compresses and generate a download link for the archive, so what I need now is a way to call it after the pop-up is displayed, and a way to print the download link on the pop-up once the function is done.
This might not be the best approach since I am a beginner, so if you have suggestions on how to get my task done without this complexity, I would be very happy.
Sorry if my question is too long, and thanks in advance for your help.
What you need to do is use these things called XHRs, or XMLHttpRequest (Google it), from within JavaScript to php, which basically is kind of like an invisible browser going to the php page behind the scenes and "loading" whatever the php page gives back, only this is all happening within JavaScript itself, so you can read that this "invisible page" loaded, which is from php, and do stuff with that, without actually refreshing the page. This process is known as AJAX (look it up)
What you can do is, when you set up this "invisible page", you can also send certain kinds of information along with it that the php page can read, and when it's done the php page can echo something back to the invisible page, which can then be read with JavaScript. This easy you can communicate between php and JavaScript, by sending certain values, in JavaScript, along with this invisible page, and waiting for php to echo something back to it, then reading that with JavaScript
So how do we actually do this?
First on the JavaScript side, we need to make this "invisible page", which is really not technically a page, it just does the sane thing as what is done to display any other web page, which is technically called a "request" since it's like asking the server for some data, it's basically "requesting" it, then when the server echoes something back, that's called he "response" to what was requested
So to make this new request in JavaScript we can do the following
var asking= new XMLHttpRequest ()
now that it as if an invisible page was created, but not yet navigated to anything, but we have to now metaphorically "enter in the URL" to this invisible page (without actually "navigating" to it yet) to do that we do
asking.open("GET", "pathToPHPpage.php?hi=there")
So the first part is called "GET" because we want to simply get a response back, without actually sending anything (if we were sending a file though, we would instead use "POST" then put the file date in the next step), then we enter in the URL to the php page that you want to get. If it's the same as the JavaScript page just put location.href instead, but it's important to add at least something to the end of the URL, notice the "?hi=there", you can call it anything, but it's important to have a question mark immediately following the .php page, then the name of something (in this case"hi") followed by it's value (in this case "there"), because the php page is able to read that, and give a different response back depending on what it says
Ok so now we have to actually "send" that request to the server, which is like metaphorically "navigating" to the URL on the invisible page, to do that
asking.send()
(And if you put "POST" before, you can add the date you want to send in between the parenthesis, usually in the form of a string but it can be different depending on the data, look it up for more reference)
Now, before we continue in the JS side, let's quickly switch over to PHP (doesn't have to be in this order though) to see what happened
We need to listen for any "requests" on the php page, that contain the name "hi" (since that's what we at the end of the URL before), to do that, around the top of PHP (technically anywhere in php though) we do
$isHi = $_GET["hi"];
if(isset ($isHi)) {
//Do some php code
echo "hi back!".$isHi;
}
Basically we just looked for the *hi" name in our "GET" request that was sent to PHP, we checked if it is "set", meaning not nulll, then we echoed some message back to JS, now let's listen for that message on the JavaScript side
Back to JS, after the .send line (or before), we need to listen for when the page echoes back.
To do that we check if it successfully loaded, because sometimes there can be errors, so let's do
asking.onreadstatechange= function () {
if(asking.readyState == 4 && asking.status==200) {
alert(asking.responseText)
} else alert("ooh something happened")
}
Now we have access to the response the php code gave us
You can extend this to other forms of communication, let me know if you have any questions
I am running a php code that handles a form and sends you to another page. I am currently using this code as an example once my handling has been done:
echo "Success, redirecting to index.html";
//I then do some stuff with the session here
echo "<script>window.open('index.html', '_self')</script>";
I feel like this is not the most efficient way of running things. Is it possible to open the new page with plain php? (header location whatever doesn’t work because the first echo line defines the page). Or, is there a way to do the same thing with header location whatever and displaying the earlier echo line differently, but still having the same effect?
You can't do it with PHP after data has been sent back to the browser.
I would personally just add a setTimeout() in JavaScript and then run the window.open() after 5000ms.
I've to run a python script from my HTML page button. When I click on the button, it should run the command "python filename.py". But I'm not getting any solutions, please help!
Thank You
Sorry to say but this is not possible unless your 'filename.py' is on a server e.g. flask, or else this will not work. If setup a flask server, and with a certain route it runs your code, then you can have your HTML code make a POST or GET request to this flask server, and the code should run.
Attach a listener to the button and have that listener call your endpoint:
document.querySelector('button')
.addEventListener(() => fetch('runMyScript.php', { method: 'POST' }));
Then have that endpoint run your desired program. In PHP, for example:
<?php
// if you want the page to be able to do something with the result:
$output = `python /home/username/filename.py 2>&1`;
echo $output;
?>
Of course, a real setup better have something to validate
You can’t.
Python runs in the server. HTML isn’t a programming language, it’s content, and it sits in the browser. About the best you can do is use AJAX to call a function in the server (which you’d have written in Python) and, if it returns a value, return it via AJAX.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I'm trying to include JavaScript variables into PHP code as PHP variables, but I'm having problems doing so. When a button is clicked, the following function is called:
<script type="text/javascript">
function addTraining(leve, name, date)
{
var level_var = document.getElementById(leve);
var training_name_var = document.getElementById(name);
var training_date_var = document.getElementById(date);
<?php
$result = "INSERT INTO training(level, school_name, training_date) VALUES('level_var', 'training_name_var', 'training_date_var')" or die("Query not possible.");
?>
</script>
Is it possible?
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo 'php_'.$abc;?>
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data.
-don
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
Setting location (GET only)
Submitting a form (with the FormElement.submit() method)
Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.
Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.
I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:
Create a hidden form on a HTML page
Create a Textbox or Textarea in that hidden form
After all of your code written in the script, store the final value of your variable in that textbox
Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.
I hope this trick works for you.
You can take all values like this:
$abc = "<script>document.getElementByID('yourid').value</script>";
You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.
I am trying to write a Perl script that will take a user parameter from command line and with his parameter, Perl script will call a JavaScript function in a HTML page. How can I go ahead to with this?
Not that I've seen. Perl is strictly server side, and JS functions you're talking about are on the client.
The closest you would get is have the Perl script write a block into the HTML page so that the page fires it on load to perform the action. But that's a little shaky at best to do.
It depends on whether the browser or server will be taking the first step.
If the server needs to run code first and then execute some JS, then #skyburner's solution would work. Essentially you would already have some functions defined on the page, but then you would dynamically add a block of JS to call whichever function you need to.
However, if the Perl is being run due to a user's action on the current page (such as clicking something or submitting a form), then AJAX would be the way to go. You would use JS to submit an HTTP request to the Perl script. The Perl would then return some value back to the JavaScript and execute some function based on this result. This would all happen "behind-the-scenes" without the user leaving the page.
If I understand correctly about what you want, since not all the browsers support socket, this is what you can do:
Have an ajax service call periodically sending requests to the server for update
Once the the parameters from the command line are taken, you can send the result along with an ajax response back to the page, and call the function in the ajax request callback function.
Also, another option, you can use reverse ajax to accomplish this. See Wikipedia about reverse ajax (comet), especially Ajax with long polling.