Php code to modify a document element - javascript

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.

The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>

Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.

Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Related

Append input field value to url on button click

I'm very new to coding, so please forgive me if this is a dumb question.
I'm working on an assignment where I have to add functionality and styles to an existing bootstrap HTML doc. The purpose is to allow people to enter a dollar amount into an input field either by typing in an amount or by clicking buttons that populate the field with set amounts. One of my instructions was to update the donate submit button so that it appends the chosen donation amount to the "/thank-you" URL.
This is what I have for the input field:
<form id="amountSend">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount"/>
</form>
This is what I have for the button:
<button id="donateBtn" type="submit" action="/thank-you"
method="get">DONATE<span class="metric-amount"></span></button>
And I was thinking that the jQuery would look something like this, though the submit function is not currently giving me any visible results.
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit(function() {
var url = "/thank-you";
$(".metric-amount").appendTo("url");
});
}
})
I also got some decent results using a PHP method:
<form id="amountSend" method="post" action="/thank-you.php">
<input type="text" class="form-control donation-amount-input" placeholder="Other" id="other-amount" name="donation"></input>
</form>
<button id="donateBtn" type="submit">DONATE<span class="metric-amount"></span></button>
<script>
$("#donateBtn").click(function() {
if (!$.isNumeric($("#other-amount").val())) {
$("#dataWarning").show();
$(".metric-amount").hide();
$(".metric-message").hide();
} else {
$("#amountSend").submit();
}
});
</script>
This one will open the PHP file I set up (/thank-you.php, which i have stored just in the same root folder as my main HTML doc), but all the browser gives me is the raw HTML code of the PHP file. Here's the code I have in the PHP file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
Thank you for your donation of
<?php echo $_POST["donation"]; ?><br>
</body>
</html>
Anyway, I guess I'm wondering if I'm on the right track? Should I pursue the jQuery or PHP method? Can I even do this using only jQuery? I've seen a few posts on this subject already, but I thought I'd make a new one since the ones I've seen are all fairly vague, I haven't seen the same answer twice, and I'm not sure I fully understand exactly what I'm trying to accomplish, in terms of a visual confirmation of results.
Thanks!
First of all, you have several issues with your code.
Number one: The formulary you have there is bad coded, the form tag needs to have the action and method attributes, not the submit button.
And in top of that, the submit button needs to be inside the form tag, if is not in there, it will not have and kind of effect.
Number two: If you are gonna submit the formulary to a php file and handle the request there ,you need the file to be running on a server (local or whatever). PHP is a server language, if you open the file directly in a browser, it will show you the code it has inside and will not work.
Hope it helps!

JavaScript code not run when clicking submit button in Wordpress admin page form

I have created an HTML form in the admin pages of a Wordpress installation. When I press the submit button I want the inserted data to be validated using a JavaScript function so that alerts are displayed when the data is not correctly inserted. I have tried all the things I have come across, but I have not been able to make it work. It should be something small, but I am not able to see it at this point.
The only thing I do is to echo out an HTML form to be shown using PHP and include some JavaScript function to be run. What is wrong in the code below? The {$this->form} part is just a string variable containing the HTML form. This works as expected.
public function __toString()
{
return "
<script>
function validateForm()
{
alert(\"FOOOOO\");
return false;
}
</script>
<h1>Heading</h1><br>
<form method=\"post\" onsubmit=\"return validateForm()\">
{$this->form}<br>
<input type=\"submit\" name=\"submit\" value=\"Submit me!\" /><br>
</form>
";
}
In this case, the error turned out to be naming the JavaScript function validateForm(), as this is an internal function in the Wordpress core. Changing it to validate_form() or whatever fixes the issue.

Upload file in PHP error - goes to PHP file without allowing me to select?

I understand that SO advocates that we do our research before asking, but I'm not sure how to put it another way, so I thought I'd ask directly -
I'm actually trying to do something simple - upload a file, but when I select "choose" in the file browser, it just redirects to the PHP page, which shows the corresponding error message (since nothing has been uploaded).
Would really appreciate if you can explain the process flow of uploading a file. Here's my code:
HTML
Simple form
<form action = "./php/upload_avatar.php" method = "POST" enctype = "multipart/form-data">
<div class = "change-avatar-text">
改变头像
</div>
<!-- hidden button trick -->
<input type = "file" name = "file" id = "change-avatar-input"/>
<button type = "submit" class = "change-avatar" onclick = "fake_photo('change-avatar-input')"></button>
</form>
http://i.stack.imgur.com/6d2U4.png
The onclick is just a way to use a photo as the file button instead of a traditional button. I don't think it's relevant, so I omitted it here.
PHP
The upload file code
if (file_exists("../avatars/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "../upload/" . $_FILES["file"]["name"]);
}
Two things happened: when I tried clicking the upload button on the HTML page, it returned "already exists", but there's nothing in the ../avatars/ folder.
http://i.stack.imgur.com/DG8Vm.png
I then tried commenting out everything except for move_uploaded_file, and nothing happened.
Would appreciate your advice on this, thanks!
UPDATE
JS
Here's the fake photo function:
function fake_photo(element_id) {
document.getElementById(element_id).click();
}
You do not prevent the default action of the form from happening within your onclick method. But that will not be the only problem, since you are using the submit button as the trigger to start the file chose process you will need to resubmit the form after the image has been picked.
HTML
<form id="myform" action="./php/upload_avatar.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="change-avatar-input" onchange="onFileChanged()"/>
<button type="submit" id="submitBtn" class="change-avatar" onclick="fake_photo('change-avatar-input',event)"></button>
</form>
Javascript
var hasChosenFile = false;
function fake_photo(element_id,event){
//If hasChosenFile is false then we want
//to prevent the default action of the form
if(!hasChosenFile){
event.preventDefault();
document.getElementById(element_id).click();
}
//Else let the form submit.
}
function onFileChanged(){
hasChosenFile = true;
document.getElementById('myform').submit()
}

How do I process forms (front and back end) on the same page?

I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.

disable submit button when javascript is disabled

I have a form which needs javascript to be enabled for validation, is there a way to disable submit button when javascript is disabled and warn user to enable it first ?
Disable it by default and use JavaScript to enable it.
<input type="submit" value="Submit" id="submitBtn" disabled />
<script type="text/javascript">
var _onload = window.onload || function()
{
document.getElementById('submitBtn').disabled = false;
}
_onload();
</script>
That way, if JavaScript is disabled then the button will also remain disabled.
jQuery version:
<script type="text/javascript">
$(function(){
$('#submitBtn').attr('disabled', false);
});
</script>
Have it disabled by default and if there is javascript, then enable it.
Don't define an HTML form action, but rather define only an onSubmit javascript event handler. If javascript is not enabled, the onSubmit will not fire, but since there is no form action, the submit button won't do anything either.
You could also opt to have the HTML form action go to an error page explaining that javascript must be enabled, so that the user has some sort of feedback.
Alternatively you can start with the button disabled (as other posters suggested). If you do that, you should also consider a message on the form indicating why the button is disabled. Remove that message with javascript if it is enabled at the same time you re-enable the button.
Because disabling a button programmatically depending on the environment and alerting him are both tasks depending on some kind of a scripting language ( like JavaScript ), the answer is no :-/
You got solution for enabling part. For Alerting part you can use good old tag. (-:
<noscript>
<H1> It Wont work w/o javascript. Please Enable</h1>
</noscript>
Excuse the late reply but this got me thinking on how to tackle this as I have a similar issue and it led me here. You should always program your site without javascript and add it after to enhance it, but in my case using things like lightbox are being used as input, which if javascript is disabled, doesn't work right (especially since mine passes values to its parent).
My suggestion is that hopefully you have PHP enabled, so you can simply put at the top of your document
<?php if (isset($_POST)) {
//redirect to page, or set a message variable saying "no results saved"
header('some_page');
$message = "We've detected you do not have " .
"javascript enabled. No results saved";
} ?>
From there, you will have to set all buttons on your page to say
<input name="button" id="button" type="submit" onclick="return false;" />
or you could more simply go
<form name="my_form" id="my_form" method="post" action="" onclick="return false;" />
Hope this helps!

Categories

Resources