Getting response from sending form in textbox - javascript

I'm trying to make a website that automatically uses this script to get amount of bitcoin in an wallet :
<?php
$address = $_GET["address"];
$satbalance = file_get_contents('https://blockchain.info/q/addressbalance/'.$address.'');
$btcbal = ($satbalance) / 100000000;
echo $btcbal;
?>
and I'm trying to make page that has my clients username and password in textarea box and when I enter the bitcoin wallet address from my user to check the balance from multiple input boxes and show the value in the box in front of address box.
Image of the page that needs this job done
How can I get the response from the form and display in another box or variable.
Thanks.

Wrap the fields in a form tag and submit to the same page.
Using your code example, this example show a simple form and handling the POST with PHP. This hasn't been tested but is an example of how to handle a post using the $_POST super global.
<?php
$btcbal = null;
// Check if there is POST data
if (!empty($_POST)) {
$address = $_POST['address'];
$satbalance = file_get_contents('https://blockchain.info/q/addressbalance/'.$address.'');
$btcbal = ($satbalance) / 100000000;
}
?>
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="text" name="btc_address">
<button type="submit">Submit</button>
</form>
<p>Balance: <?php echo $btcbal ? $btcbal : 'N/A'; ?></p>

Related

How to refresh contact form on the same page HTML PHP JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Really struggling with this one, didn't think a simple form would be this complicated. I'm a newbie when it comes to the back-end.
I have 3 fields; name, email, and message. On submit, I just want a simple "thank you" message inside the form box. I do not want to send to another page or refresh to the top of the current page. I want the form to refresh with the 'thank you' message, ideally with the message disappearing after a few seconds.
After trying a few different methods I am almost there with JS, using an event listener to show the "thank you" message after clicking submit.
However, now the contact form doesn't refresh on submit and the data that was inputted still shows on the form along with the thank you message. How do you get the form to refresh on submit?
I have always used WordPress, and contact forms seemed so simple. I have spent hours on this so far.
HTML
<div class="form-box">
<p id="thank-you-message">
Thank you for your message. We will be in touch with you very soon.
</p>
<form method="POST" action="contact-form.php" >
<div class="form-control">
<input class="text-box" id="name" name="name" type="text" placeholder="Your Name*" required>
<input class="text-box" id="email" name="email" type="email" placeholder="Your Email Adress*" required>
</div>
<div>
<textarea id="message" name="message" placeholder="Project Details" required></textarea>
<button class="send" name="submit" type="submit">SEND</button>
</div>
</form>
PHP
<?php
if(isset($_POST['email']) && $_POST['email'] !='') {
$name = $_POST['name'];
$visitor_email = $_POST ['email'];
$message = $_POST ['message'];
$email_from = 'website.com';
$email_subject = "New Form Submission";
$email_body = "User Name: $name.\n".
"User Email: $visitor_email.\n".
"User Message: $message.\n";
$to = "contact#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to,$email_subject,$email_body,$headers);
header("Location: index.html");
}
?>
JS
const form = document.querySelector('form');
const thankYouMessage = document.querySelector('#thank-you-message');
form.addEventListener('submit', (e) => {
e.preventDefault();
thankYouMessage.classList.add('show');
setTimeout(() => form.submit(), 2000);
});
#James Bakker
HTML
<form method="POST" action="contact-form.php" >
<?php echo $successMessage ?>
<div class="form-control">
<input type="hidden" name="valid" value="false">
<input class="text-box" id="name" name="name" type="text" placeholder="Your Name*" required>
<input class="text-box" id="email" name="email" type="email" placeholder="Your Email Adress*" required>
</div>
<div>
<textarea id="message" name="message" placeholder="Project Details" required></textarea>
<button class="send" name="button" type="submit">SEND</button>
</div>
</form>
JS
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
form.valid.value = 'true';
consultForm.submit();
});
PHP
<?php
$successMessage == '';
if($_POST['valid'] == 'true'){
$name = $_POST['name'];
$visitor_email = $_POST ['email'];
$message = $_POST ['message'];
$email_from = 'website.com';
$email_subject = "New Form Submission";
$email_body = "User Name: $name.\n".
"User Email: $visitor_email.\n".
"User Message: $message.\n";
$to = "contact#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
$header("Location: index.html");
$success = mail($to,$email_subject,$email_body,$headers);
if ($success){
$successMessage = 'Your Message was sent!';
} else {
$successMessage = 'There was a problem, message was not sent';
}
}
?>
If you were to use fetch or regular XMLHttpRequest you can use the callback to manipulate the DOM after the data has been sent to the backend PHP script.
The PHP script that handles the request will no longer require the header('Location: index.html'); - instead you could echo/return a message to be used by the ajax callback.
The below is not tested as such
document.addEventListener('DOMContentLoaded',()=>{
let form=document.querySelector('form');
form.querySelector('button[type="submit"]').addEventListener('click',e=>{
e.preventDefault();
fetch( 'contact-form.php' , { method:'post', body:( new FormData( e.target.parentNode.parentNode ) ) } )
.then( r=>r.text() )
.then( data=>{
//show the message
document.querySelector('#thank-you-message').classList.add('show');
//iterate through form elements and set the value to empty string if it is not a button
for( i=0; i<form.elements.length; i++ ){
let el=form.elements[i]
if( el.type!='button' )el.value='';
}
// remove the button
e.target.parentNode.removeChild(e.target);
})
})
});
<div class="form-box">
<p id="thank-you-message">
Thank you for your message. We will be in touch with you very soon.
</p>
<form method="POST" action="contact-form.php" >
<div class="form-control">
<input class="text-box" id="name" name="name" type="text" placeholder="Your Name*" required>
<input class="text-box" id="email" name="email" type="email" placeholder="Your Email Adress*" required>
</div>
<div>
<textarea id="message" name="message" placeholder="Project Details" required></textarea>
<button class="send" name="submit" type="submit">SEND</button>
</div>
</form>
</div>
The short answer is: You need to change the name attribute of your submit button to something other than submit, then you will be able to call form.submit() using your JS.
Currently your page works as such:
User enters info and clicks submit
Your JS captures the event and
prevents default action
You display the thank you message and then
submit() the form.
The problems with this approach are:
The thank you message is displayed before the actual message is sent.
There is no form validation
The message is only displayed for 2 seconds, and only before the actual email is sent.
A better approach is:
User fills out form and clicks submit
JS captures the event, prevents default, validates all of the data, and if everything is valid if submits the form, POSTing the form values to the current page, this will reload the page and clear the form fields.
Your PHP script will take the POSTed variables, send the email, and display your thank you message on the page.
The advantages are:
You don't display a message until the email is actually sent
You are making sure the form has valid entries
Your message is displayed after refresh and wont disappear after 2 seconds
Heres how, (code isn't tested):
Make a hidden input in your form with the name 'valid':
<input type="hidden" name="valid" value="false">
Once the your JS has validated the inputs you would set this to true and submit() the form. This will post the variable to your PHP along with the rest of the form values.
form.valid.value = 'true';
consultForm.submit();
in your php you write an if statement:
$successMessage == '';
create empty variable success message than we will assign a message if a form submission is detected.
if($_POST['valid] == 'true'){ //keep in mind we are passing a string
not an actual boolean
//insert your php email script here
$success = mail($to,$email_subject,$email_body,$headers);
//assigning return value of mail() to variable named success
if($success){
$successMessage = 'Your Message was sent!'
} else {
$successMessage = 'There was a problem, message was not sent'
}
you can then echo $successMessage anywhere in your HTML.
<?php echo $successMessage ?>
when the page is initially loaded, before the form submit, $successMessage will be an empty string, so echo $successMessage will have no affect on the page.

How to make page not reload and not open php page after click on input with type submit?

I have page in HTML CSS JS: https://handmade.company/seo/index.html
on this page i have form
<form class="webform" action="send.php" method="post">
<input class="webinput" type="text" name="imja" placeholder="Ваше имя">
<input class="webinput" type="text" name="phone" placeholder="Ваш телефон">
<input class="webinput" type="text" name="sajt" placeholder="Ваш сайт">
<input class="webinput_btn" type="submit" value="Отправить запрос">
</form>
with php file SEND.PHP
<?php
$imja = $_POST['imja'];
$phone = $_POST['phone'];
$sajt = $_POST['sajt'];
$wrong = 'при отправке сообщения возникли ошибки';
$good = 'сообщение успешно отправлено';
if (mail("office#handmade.company", "Заказ с сайта", "Ваше имя: ".$imja. " Ваш телефон: ".$phone. "
Ваш сайт: ".$sajt ,"From: office#handmade.company \r\n"))
{ echo "<script>alert('$good');window.location.href='index.html'</script>;";
} else {
echo "<script>alert('$wrong');window.location.href='index.html'</script>";
}?>
The problem is: when i click input with type="submit" button browser go to page https://handmade.company/seo/send.php and alert and after it it go back to index.html
I want: the page not reload and browser not redirect me to send.php page. I just want alert and nothing should change anymore
i tried to add function with preventDefault onclick on submit input BUT my php stopped working
Remove send.php page
Change method = "post" to method = "get"
Do document.getElementsByClassName("webform")[0].onsubmit = function( e ) { e.preventDefault(); }
Use JavaScript to get URL parameters which will be the values of the from
Then alert
you can do this with Javascript or Jquery and Ajax. But if you want a simple way. You can try to add to your php file.
header('Location: https://handmade.company/seo/index.html');
exit;
replace https://handmade.company/seo/index.html for the url you want

How to display javascript alert without reset form

I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.
I tried this way:
if($pwd != $pwd2) {
echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
I also tried the one below but still the same thing happened:
if($pwd != $pwd2) {
?>
<script type="text/javascript">
alert("Password does not match!");
</script>
<?php
}
Your validation is on server side, once you hit the server the form gets reset everytime, for showing validation error from server you need to pass the values to the form again with errors.
If you want to show the alert on validation error, use client side validation with jQuery or simple JS. In this way your form's values remain the same and the alert will be popped up.
if you really need using php
<?php
$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : "";
$pwd2 = isset($_REQUEST['pwd2']) ? $_REQUEST['pwd2'] : "";
if($pwd != $pwd2) {
echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
>
<input name"pwd" value="<?php echo $pwd; ?>">
<input name"pwd2" value="<?php echo $pwd2; ?>">
If you want other input fields not to be empty after submission you should try this using php.
Let's say your input field is username.
$username = $_POST['username'];
<input type="text" name="username" value="<?php echo htmlentities($username); ?>">
When you use this, after you clicked ok and get the alert, your username field will not be empty. The value you entered will appear in the text field.
Try this code to solve your problem.
$username = $_POST['username'];
$password = $_POST['password'];
<input type="text" name="username" value="<?php echo htmlentities($username);
?>">
<input type="password" name="password">

How to make a complete Iframe registration / login / userpanel

So far i have such code
<form action="register.php" target="login" type=post>
<label for="name">Account </label><br><br>
<input type=text id="name" name="account" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<label for="name">Password</label><br><br>
<input type=text id="name" name="password" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<button type=submit>Register</button>
</form>
I placed it inside an IFrame but when i try to use php with such code:
<?php
If (IsSet($_GET["account"]["password"])) { $Account = $_GET["account"]; $Password = $_GET["password"];
$AllRight = True;
For ($I=0; $I<StrLen(WrongChars); $I++) {
If (StrPos($Account, SubStr(WrongChars,$I,1))) {
Echo "<p>Your Name musn't contain the char \"".SubStr(WrongChars,$I,1)."\"</p>";
$AllRight = False;
}
}
If (file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
Echo "<p>This Account already exists!</p>";
$AllRight = False;
}
If ($AllRight) {
$Text .= "$Password ";
File_Put_Contents (AccountFilesPath.$Account.AccountFilesEnding, $Text);
if(!file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
echo "<p>Error during account cration!</p>";
}
Echo "<p>This Account is created succesfully!</p>";
}
}
?>
yet the responce im getting is a fresh registration page with no work done...
i want my iframe to individually register text files like (user1.txt) with ($Password) inside. Along with having a link to the login, and upon login have a User Control Panel.
I don't understand why you are using an iframe for this but I can see that you use $_GET in your php when your form submits $_POST (type="post")
Try changing that in your PHP code and see if it works
Edit*
As stated in the comments this is not a $_GET index $_GET["account"]["password"]
Let's say you stick with POST since your html form submits a POST,you must use something like this:
if(isset($_POST["account"]) && isset($_POST["password"]))
And to be sure what variables you get from your form, I recommend you to print your Post array before any manipulation.
print_r($_POST);

PHP form handling- display error message using javascript

I have a form.php file that redirects to a sendformdata.php file when I submit the form. However, I can't get the sendformdata.php file to display an error message within the form when the proper fields aren't filled out.
I am simply redirected to the include file, db_connect.php, which shows up as a blank page. How can I get the page to stay on form.php and display an error message in html? This is my current sendformdata.php file:
<?php
include_once('db_connect.php');
$lokotitle = $description = $category = $showyourname = $yourname = $lat = $lng = "";
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$lokotitle=$_POST['lokotitle'];
$description=$_POST['description'];
$category=$_POST['category'];
$showyourname=$_POST['showyourname'];
$yourname=$_POST['yourname'];
$lat=$_POST['lat'];
$lng=$_POST['lng'];
// Validation will be added here
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
?><script>$('#notitle'.text($error_message));</script><?php
exit;
}
if(!isset($error_message)){
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `new`.`web_form`
(`lokotitle`, `description`, `category`, `showyourname`, `yourname`, `lat`, `lng`) VALUES ('$lokotitle', '$description', '$category', '$showyourname', '$yourname', '$lat', '$lng')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
?><script>window.location.href = "../index.php"; </script> <?php
exit;
}
}
?>
This is a section of form.php that I am trying to display an error message in:
<form class="form-horizontal" role="form" action="handleform/sendformdata.php" method="POST">
<legend></legend>
<div class="form-group">
<label for="lokotitle" class="col-sm-2">Loko Title</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="lokotitle" id="lokotitle" placeholder="Title">
<span id="notitle"></span>
</div>
Thanks in advance for the help!
I recommend you to use both html5 required attribute which will force the user to enter the data. But remember the user can bypass front end validation (by means of inspect element), hence back end validation is also necessary.
Use required attribute like:
<input type="text" required />
You can try this
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
echo "<script>
document.getElementById('#notitle').value='".$error_message."';".
"</script>";
exit;
}
Let me know if this solves your problem

Categories

Resources