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.
Related
<div class='wrapper one Stone' id='main'>
<h1>Stone</h1>
<p>Price: $130.00 per Yard</p>
<?php if($_SESSION[id]) {?>
<button class="Stonebutton"> Delete Stone</button>
<script>; $(".Stonebutton").click(function(){$(".Stone").remove();}); </script>
<?php } ?>
</div>
When im logged in i can see the "Remove Stone" button and when i click it, it goes away but when i reload the page it comes back. Any help? Thanks a bunch!Im also loading this into the html page with a seperate php file using this:
fwrite($PlantFile, "\n\n<div class='wrapper one $trimmedname' id='main'>\n<h1>$name</h1>\n<p>Price: $price</p>\n <?php if(\$_SESSION[id]) {?> \n<button class=\"$trimmedbname\"> Delete $name</button>\n<script> \$(\".$trimmedbname\").click(function(){\$(\".$trimmedname\").remove();}); </script> \n <?php } ?> \n</div>\n");
fclose($PlantFile);
Also if anyone has a better solution on what to do, im all ears. Thanks for all your help!
In order to properly understand this, you need to understand the life-cycle of a web page.
The browser makes a request to the server.
The server responds to that request. From the large array of possible responses, we'll assume everything went OK and it responded with a web-page (status code: 200). Most times (and the case we will consider here), the response is HTML.
Excluding all the things that could go wrong, a server will always return the same result for the same request. However, sometimes, that's not enough and that's where we use JavaScript. With JavaScript, we can make changes to the returned HTML, without having to tell the server: create a new page, containing this mod.
.remove() is such a JavaScript method. It changes the HTML after it was returned. It removes an HTML element that was part of the initial response, without going back to server and removing the code that generated the element in the first place, during the request.
This means that the page will contain the element again when you refresh the page, because you're making the same request (you're back to step 1).
If web worked the way you seem to expect it to, anyone could open up the console and delete the entire website with a simple line of code:
document.body.remove();
Luckily, that's not how web works.
I'm really not good at technical terms (because I'm still a beginner) but I am developing a system as a school project. It's a mobile app (I used phonegap). my question is that I wanted to send data (preferably $_get) to a PHP page so that I can run my query with it. But I don't want a button or link to be a trigger. I want my trigger to be when the page reloads (or refreshes. Any idea or help is appreciated!
You can do that with javascript, binding the action of sending data to your php page to the "document loaded" event.
With pure javascript you can do that with
<body onload="yourFunction();">
or
document.onload = function ...
If you are working with PHP, you should create the HTML dynamically so, the information sent to the app will already contain the data when shown.
A dirty example:
<?php
?>
<html>
static html code
<?php
your content including dynamic data shown from your PHP backend
?>
</html>
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.
This is an odd situation and my current thought is that it doesn't work this way, but I need to some other eyes on this.
A different website I don't have control over has a form with a hidden field in it. The form action is a POST and to send it to a url on my website and I need to be able to get the value of that hidden field using javascript.
As a GET that would be included in the url and I think I would just be parsing that apart. But since it's a POST being sent to me I'm not entirely sure how to get the value of that hidden field out.
Is this doable? If so, where should I be looking to do it?
Thank you!
If your server that is receiving the sended form data uses PHP, you can get all form values using:
<?php
print_r($_POST);
?>
If the page in your server is a static html page, then you cannot get the POST data. Or you can, but then you have to make html pages to be executed as php pages (not recommended however).
You talk about that you need this value be accessible by javascript. Simply do something like:
<script>
<?php
echo 'var input_field_value="'.htmlspecialchars($_POST['name_of_input_field']).'";';
?>
</script>
The question doesn't provide information what server software is used, so I assume that is PHP.
EDIT: after Saturnix's comment I added a call to htmlspecialchars() to make it safe to execute in javascript.
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.