<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.
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 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.
What would be the better/best solution? previously all my markup were all initialized in an html file,
index.php:
//login block
<div id="login">
form ...
</div>
so whenever I logged in, I have to remove/hide these login block by using $.ajax to check if there's an existing session then hide the whole login markup ( .hide() ) and show a different markup for logged in users.
The problem with this is that, it waits for the whole document to load before it executes the script, so the unintended/hidden markup will show and then vanished quickly upon page load.
I also tried putting the markup inline inside javascript, but I think it violates the "Unobtrusive" idea in js.
e.g.
var markup_arr = [
'<h4>Login</h4>',
'<form></form>'
];
var markup = markup_arr.join('');
So I end up with this
Current solution: separate html file and loading it using jQuery's $.load()
What are you using, which are the best practices and which one loads fast? Or are there any better solution out there that you can suggest? Thanks.
EDIT:
These are all javascript/ajax processes, so I'm not looking for a server side solution(include,require_once)
There's no correct answer to this. My view is you want to deliver the minimum amount of data to your users, in the minimum number of requests. It's all about finding the right balance. Depending on your users the balance will change to.
For me, I'd prefer sending two files that are 5kB each, rather than four that are 2kB. You're sending more data, but as there are less requests it should be just as quick. I'd think that delivering it as part of the Javascript might be best. Note it doesn't necessarily need to be the same file, although I'd deliver it as one - have a simple (PHP etc) script which joins the code file and the data file into one, then passes it out
The other thing I'd make sure is that you're caching everything as best you can. Having a slightly bigger file isn't generally an issue if you only have to download it once and it caches for a year. If your users are downloading a larger file every day, or worse, every page view it becomes an issue.
What I would do is check server side if the session exists, and include your separate "html" (php/rb/py/asp/whatever really) file if the session exist, and the login form if not. When the user logs, ajax would answer the same "html" file. (if I understand your problem correctly, and the login form is a single line in the page header).