error: "Please use POST request" with Form and Javascript - javascript

I made a small form and I want it to post information back to the user when the inputs are left blank.
For some reason it says please use post request, so I added it and now it gives me a different error message.
Here is the code:
http://jsfiddle.net/pwtnY/
<div id="main">
<form name="myForm" method="post">
<label><span>First Name:</span><input type="text" class="firstname" name="fname"></label><br/>
<label><span>Last Name:</span><input type="text" class="lastname"></label><br>
<label><span>E-Mail:</span><input type="text" class="email"></label><br/>
<label><span>Phone:</span><input type="text" class="phone"></label><br/>
<input type="submit" name="submit">
</form>
<div id="answer"></div>
</div>
Javascript:
$(document).ready(function(){
$('input:submit').click(function(){
$firstname = $('.firstname').val();
$lastname = $('.lastname').val();
$email = $('.email').val();
$phone = $('.phone').val();
if($firstname === "" && $lastname==="" && $email ==="" && $phone === ""){
$("#answer").html("Please fill out all fields.");
}
});
});
Anyone know what the problem could be and how I could go about solving it?

When you click submit, the form is actually posting to your django backend. If you want to do frontend validation before posting to your server, prevent the submit button from actually posting.
$('input:submit').click(function(event){
event.preventDefault();
$firstname = $('.firstname').val();

In your fiddle you haven't included jquery library. If you don't want to submit anything to the server, replace submit button with simple button <input type="button" value="submit">. There is updated your example: fiddle
P.S. You probably want to use OR instead of AND in your validation to validate if any of the fields is empty

Related

PHP/JavaScript form validation, invalid email check

So i'm working on form validation for a website.
What i have accomplished so far is when the form is submitted, validate.php checks if the email is in the correct format.
If it is, it proceeds in calling the sendMail() function included in the validate.php which proceeds in sending the email and then redirects the user back to the home page after 5 seconds. (This part works <-)
If it isn't, that's where i'm stuck.
What i'm trying to accomplish at this stage, is somehow get PHP to send a script tag, <script> emailError(); </script>, to the current page (contact.html) and execute the script which simply appends a paragraph saying that the email is incorrect. What i am getting, however is the validate.php has its own error in the else statement simply saying Error in a blank page (which is what i don't want, i put it there to see if the validation was working correctly).
I tried to add this (the script mentioned above) in the else statement in validate.php:
validate.php
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
echo("<script> emailError(); </script>");
}
?>
So what i was hoping it would do, is echo it into the page executing the JavaScript function but it didn't work and i think i know why.
PHP, to my knowledge, executes on request of user interaction (press button, click something, etc...) or upon page loading (Correct me if i'm wrong, still learning).
To make sure that the echo did not work, i inspected the page in real-time while using the form and didn't see any sign of the script tag being inserted into the HTML.
At this point, i have tried many alternative solutions, i don't even know where to begin. I could really use some help and any tips for improving my form.
This is the contact page that i'm working on. Feel free to try it out and see the results for yourself but Please don't spam!
Click Here
emailError.js
This is what i wanted to echo into the page with PHP.
function emailError(){
var targetElement = document.getElementById("emailform");
var errorElement = document.createElement("P");
var errorMessage = document.createTextNode("Invalid Email");
errorElement.appendChild(errorMessage);
errorElement.setAttribute("id","error");
document.body.appendChild(errorElement);
}
contact.html
This is just a segment of contact.html showing my form.
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
I'm not asking for something to copy n' paste, simply something to push me in the right direction.
Well, first of all, You are submitting your form to validate.php, and then never redirect back to contact.html, that's why you dont see the script tag appended. And from whay i see, that string 'Error' does not appear to be in your code, so I'm guessing that you did not paste the entire code. My suggestion, is to redirect to the contact form back again if the condition fails, and change contact.html to contact.php in order to be able to do a validation. Here is some rough code:
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
header('Location: contact.php?error=1');
}
?>
and then, in your contact.php file:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
if ($_GET['error']) {
echo "<script> emailError(); </script>";
}
This is just a rough example, it can be more robust, with this solution, if somebody enters your contact form with the query param "error" he will get the javascript executed. But as I said, this is a concept and a rough solution to explain how you could solve your problem.
You can't execute java function like you are trying to.
If you use ajax, than in the success response function, set the respone to a div.
For example, if you have a success function that gets the data in an argument called data, than set an empty div with an ID like "emailResponse" in your page, and use this in the function:
var responseDiv = document.getElementById("emailResponse");
responseDiv.innerHtml = data;
Add this to your html:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
<div id="emailResponse"></div>
</form>
And in your PHP, change to this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
echo "Your message was sent!";
}else {
echo "You email was invalid!";
}
UPDATE:
If you are not using ajax - you need to redirect to the contact page with some parameter in GET, or set some SESSION variable.

Calling PHP function from Javascript then change form action

I'm trying to change my form action in my HTML then submit using javascript.
The conditions are in PHP .
I need help if anyone can assist me.
This is my PHP function :-
<?php
error_reporting(0);
if(isset($_POST['email'])){
$email=$_POST['email'];
if(!empty($email)) {
$chrono = 0;
} else {
$chrono = 1;
}
}
?>
The motive of the PHP is to check null email entry.
Here's the javascript function :-
<script type="text/javascript">
function fireform(val){
// missing codes
document.forms["demoform"].action=val;
document.forms["demoform"].submit();
}
// missing codes
</script>
HTML :-
<form name="demoform" action="">
<input type ="text" name="name" id="name">
<input type="hidden" name="buttonpressed" id="buttonpressed">
<input type="button" value="submit B" onclick="fireform('b')">
I want to do it in a way , when the user entered an empty email , the PHP will read it as chrono = 0.
Then goes to javascript , if the chrono equal to 0 , the action will remain empty.
If the chrono = 1 , the javascript will change the action of the form and submit.
I need help thanks.
Your flow is unclear: it seems that you want to change the form action from PHP, but PHP is triggered after the form submission. So there's something weird in your flow. You also don't seem to have a field called email in your markup. Add it (or rename the field name):
<input type="text" name="email" id="email">
Nonetheless, having an empty action means the form will be submitted to the page itself.
Probably what you need is a client side validation of the email field. In the fireform() JavaScript function, just add a check for email field:
function fireform(val){
if (document.forms["demoform"].email.value.length > 0){
document.forms["demoform"].action = val;
document.forms["demoform"].submit();
}
}
This should be enough to get what you need.
I would recommend checking the email field (for being empty) in javascript, and when you have set the proper action submit the form in javascript.
Check the field:
$('#<enter id of field>').val();
Update the action:
$('form').attr('action', 'Enter your updatet action here');
Submit the form:
http://api.jquery.com/submit/

jQuery/PHP ajax contact form

I have been fighting with this for quite awhile, searching questions, tutorials, and forums to not find a working solution. I'm extremely green in the realm of PHP and just now starting to learn.
Page in progress can be found here: http://williamsfuller.com/limedropdesign/
Goal: Use front end validation using jQuery Validate (http://jqueryvalidation.org/), if validation is successful then in the submitHandler run an ajax call to a php file that takes the form values and posts them to the server. On the ajax.done function clear the form and show that the submission has been successful.
Reason I'm using ajax is because I don't want the page to refresh and send the user back to the top of the page. This is a single page portfolio and if I was to do a post method on the form it will ruin the experience by reloading the page.
What I have achieved thus far:
-I have the jQuery validation working
-If the validation is successful the ajax call runs correctly activating the contact form submission file
-On the ajax.done function the contact form clears and a success message slides down telling the user the message has been sent
-On the php side of things I was able to hardcode a mail function that runs which tells me that the ajax call is working and the php file is working.
<?php
mail('email#gmail.com', 'Mail from Lime Drop Design', 'some body content for the email ');
?>
Where I'm stuck is taking the jQuery values and putting them into a working if($_POST){} and having that send off an email.
I also have a honey pot in the form to catch some bots, if all the information is validated and the subject field is still filled out I'm looking to just allow the POST to die.
HTML:
<form id="contactForm" method="get" action="">
<div class="form-group">
<input class="form-control"
type="text"
name="name"
id="name"
minlength="2"
placeholder="Name" required>
</div>
<div class="form-group">
<input class="form-control"
type="email"
name="email"
id="email"
placeholder="Your email address" required>
</div>
<div class="form-group">
<textarea class="form-control contactMessage"
name="message"
id="message"
rows="8"
minlength="10"
placeholder="Enter a message" required></textarea>
</div>
<input type="text" id="subject" name="subject" autocomplete="off">
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button id="formSubmit" type="submit" class="btn contact-btn pull-right">Send</button>
</div>
<div id="result">
Thank you, your message has been sent to Liz!
</div>
</form>
JavaScript:
$(document).ready(function(){
$('#result').hide();
$.validator.setDefaults({
submitHandler: function() {
var nameValue = $('#name').val();
var emailValue = $('#email').val();
var messageValue = $('#message').val();
console.log(nameValue, emailValue, messageValue);
$.ajax({
type: "GET",
url: "contactSubmission.php",
data: {
name: $('#name').val(),
email: $('#email').val(),
message: $('#messageValue').val()
}
}).done(function(){
$('#contactForm').find("input[type=text], input[type=email], textarea").val("");
$('#result').slideDown();
});
}
});
$("#contactForm").validate();
)};
PHP Working:
<?php
mail('email#gmail.com', 'Mail from Lime Drop Design', 'some body content for the email outisde post function');
?>
PHP not working (what I'm trying to achieve):
<?php
if($_POST){
$to = 'email#gmail.com';
$subject = 'Contact Form Submission';
$message = $_POST['messageValue'];
if($_POST['subject'] != ''){
die();
}
//Sanitize input data using PHP filter_var().
$nameValue = filter_var($_POST["nameValue"], FILTER_SANITIZE_STRING);
$emailValue = filter_var($_POST["emailValue"], FILTER_SANITIZE_EMAIL);
$messageValue = filter_var($_POST["messageValue"], FILTER_SANITIZE_STRING);
mail($to, $subject, $message);
}
?>
Any help on this would be greatly appreciated. I have been trying to get this to work for awhile now and I seem to just be stuck on the php POST at this point. Thanks in advance for any input or working example.
As pointed out, you're making a GET request with Jquery while php expect a POST one.
Then on your php, the post fields aren't good: You put 'Value' post field:
$_POST["nameValue"] while on Jquery it seems like the field is named name, try changing $_POST["nameValue"] to $_POST["name"] And do the same for message and email.
EDIT : Change $('#messageValue').val() to $('#message').val() in the post datas in your Jquery code, this value was the reason why the data wasn't succefully sent to PHP, in you console.log you've put the right ID but not in the post data, that's why you where thinking the correct values was sent by php.

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

Setting input value with javascript nullifies PHP post

I a have PHP form where I collect a bunch of values from text inputs, but for one input I have the input filled in via javascript (user selects a date from a calendar, that date then populates a text input). I've setup a simplified version of this:
<?php
$displayForm = true;
if ($_POST['submitFlag'] == 1) {
// Form was submitted. Check for errors and submit.
$displayForm = false;
$installationTime = $_POST['installation-time'];
// send e-mail notification
$recipients = "test#test.com";
$subject = "Test Email - Test Form Submission";
$message = wordwrap('Someone has filled out the secure form on test.com. Here\'s what they had to say:
Installation Time: ' . $installationTime .'
');
$headers = "From: test#test.com";
mail($recipients, $subject, $message, $headers);
// Output thank you message
?>
<h2>Thank You!</h2>
<?php if($installationTime == NULL){echo 'test failed: value submitted was null.';}else{echo 'test passed: value submitted was not null.';} ?>
<p>Your form has been submitted. Thank you for your interest in test.com.</p>
<?php
}
if ($displayForm) {
// If form was not submitted or errors detected, display form.
?>
<div class="note"><span class="required">*</span> Click me to set value of input.</div>
<form name="contactForm" id="contactForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>?state=submit">
<label for="installation-time" class="service-time">The time you have selected for installation is: <span class="required">*</span></label>
<input type="text" name="installation-time" id="installation-time" disabled value="<?php echo $_POST['installation-time']; ?>" />
<input type="hidden" name="submitFlag" id="submitFlag" value="1" />
<input type="submit" name="submit" id="submit" value="Sign-Up" />
</form>
<?php
} // End of block displaying form if needed.
?>
And then in jQuery I do one of these:
$('.note').click(function(){
$('#installation-time').val('test string');
});
When I submit the form, the PHP variable that's supposed to collect that value is null. Every other input in the form works, and if I remove the javascript and manually enter the exact same text that I had set with JavaScript into the input it works as well.
The question really is why populating a field with javascript as opposed to manually typing the exact same string into a text input would break things. Again there are no errors and the input is populated correctly on the front end. Somehow posting the form just doesn't pick up on the value when it's set by javascript vs. typed manually. There has to be something really fundamental I'm missing here.
Any idea what's going on here? I've spent hours puzzling over this to no avail.
Update:
Code updated, test page:
http://dev.rocdesign.info/test/
Solution: can't post a disabled input. I actually tested that back in the beginning and must have missed that removing the "disabled" on the input made it work, so I mistakenly ruled it out and moved on.
Thanks for the responses everyone. And for anyone else with this problem: use a hidden input to post the value.

Categories

Resources