I have an html form. The form sends login request to server. The html response from server is put in an iframe.
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe").val();
var iframedocument = myiframe.contentDocument;
var response = iframedocument.queryselector("pre");
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
<form method="post" target="dummyframe" action="https://kintai.jinjer.biz/v1/sign_in">
<input name="company_code" type="hidden" value="1234" />
<input name="email" type="hidden" value="1234" />
<input name="password" type="hidden" value="1234" />
<input type="submit" value= "submit" id= "submit" />
</form>
I want to read response from the server to validate password. If I get error message from server, I want to alert "wrong password" in my html page. Am I missing something? It doesn't work. The code doesn't seem incorrect. Your help is greatly appreciated.
You need to change your script to below:
$(document).ready(function(){
$("#submit").click(function(event){
$("#dummyframe").on('load',function() {
var myiframe = $("#dummyframe");
var iframedocument = myiframe.contentDocument;
if (iframedocument.document) iframedocument = iframedocument.document;
var response = iframedocument.queryselector("pre").innerHTML;
var errormessage = '{"code":500,"message":"入力項目に誤りがあります","data":{}}';
if (response == errormessage ){
alert('wrong password');
}
else {
alert('password is ok');
}
});
});
});
Related
I am using Flask Framework..
I have a form tag in the front end for login id and password and a submit button.
I want to use JavaScript in the front end to verify the data provided by the user in the form field and then if everything is okay, then I want to send the data provided by the user to the back end server and process it using python..
But how can I control the process that when the user click on the submit button the control will go to the JavaScript code and then after validation, the data is sent to the back end server
In the snippet I have given a dummy example. In that my doubt is how to first send the control to the validate_login_form() written in Java Script and then after validation the control should go to the {{url_for('home')}} written in the action part using the Jinja2 template engine
Here the trouble that i am having is, after filling up the form, when the user clicked of the submit button, the control goes fine to the Java Script function written to validate the form but even if the Java Script returns false, the control automatically goes to the back end server.
But what i want to do is if the Java Script returns false, the control should stop there and ask the user to again fill in the form.
function validate_login_form(){
let login_id = document.getElementById('login_id').value
let password = document.getElementById('password').value
if(login_id == '' && password == ''){
alert('please enter the login id and password')
return(false)
}
else if(login_id == '' && password != ''){
alert('please enter the login id')
return(false)
}
else if(login_id != '' && password == ''){
alert('please enter the password')
return(false)
}
else{
if(login_id == 'test' && password == 'test'){
return(true);
}
else{
alert('please enter the valid login id and password')
return(false)
}
}
}
<html>
<head>
</head>
<body>
<form action="{{url_for('home')}}" onsubmit="validate_login_form()">
<label for="login_id">LogIn</label>
<input type="text" name="login_id" placeholder="login Id" id="login_id">
<label for="password">Password</label>
<input type="password" name="password" placeholder="password" id="password">
<br><br>
<input type="submit" value="submit" >
</form>
<script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
</body>
</html>
Simple: https://www.w3schools.com/jsref/event_onsubmit.asp.
There your go:
<form onsubmit="myFunction()">
Enter name: <input type="text">
<input type="submit">
</form>
<script>
function myFunction() {
return true;
}
</script>
HTML from example:
<form method="POST" id="myForm">
<input type="email" name="email" id="email"/>
<input type="password" name="password" id="password"/>
<button type="submit">Login</button>
</form>
javascript:
var myForm = document.getElementById("myForm");
myForm.onsubmit = function(e){
e.preventDefault();
// validate here and produce data
fetch('/mypage', {
method: "POST",
credentials: "include",
cache: "no-cache",
body: data,
headers: new Headers({
"Content-Type": "application/json",
}),
})
.then((response) => {
if (response.status !== 200) {
// handling if status is not ok(200)
}
response.text().then((res) => {
// response handling
if(res === "success"){
// redirect to homepage or do anything
} else {
// something went wrong
}
});
})
.catch((err) => {
// error handle
});
}
Flask/Python:
from flask import request
#app.route('/mypage', methods=['GET', 'POST'])
def myPage():
if request.method == "POST" and request.json:
data = request.json
# send data to database
return 'success', 200
The only problem here in the codes are in the form tag in html,
I should have written onsubmit=return validate_login_form()
instead of onsubmit=validate_login_form()
By this code if the JavaScript function returns true then the page will be redirected to the url written in the action field of the form tag
and if the JavaScript function returns flase then the control will remain in the same page without being redirected.
That's how the flow can be controlled
function validate_login_form(){
let login_id = document.getElementById('login_id').value
let password = document.getElementById('password').value
if(login_id == '' && password == ''){
alert('please enter the login id and password')
return(false)
}
else if(login_id == '' && password != ''){
alert('please enter the login id')
return(false)
}
else if(login_id != '' && password == ''){
alert('please enter the password')
return(false)
}
else{
if(login_id == 'test' && password == 'test'){
return(true);
}
else{
alert('please enter the valid login id and password')
return(false)
}
}
}
<html>
<head>
</head>
<body>
<form action="{{url_for('home')}}" onsubmit="return validate_login_form()">
<label for="login_id">LogIn</label>
<input type="text" name="login_id" placeholder="login Id" id="login_id">
<label for="password">Password</label>
<input type="password" name="password" placeholder="password" id="password">
<br><br>
<input type="submit" value="submit" >
</form>
<script src="{{ url_for('static', filename='scripts/login.js') }}"></script>
</body>
</html>
I'm trying to add Google's recaptcha in my website's contact form. I've used the <input type="submit"> instead of button tag for submitting the form. But it doesn't work with AJAX. And with button tag, the captcha response is always empty. You can check the problem on vipiny.com.
This is the contact form.
<form action="" method="post" id="contactForm" name="contactForm">
<div>
<label for="contactName">Name <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactName" name="contactName">
</div>
<div>
<label for="contactEmail">Email <span class="required">*</span></label>
<input type="text" value="" size="35" id="contactEmail" name="contactEmail">
</div>
<div>
<label for="contactSubject">Subject</label>
<input type="text" value="" size="35" id="contactSubject" name="contactSubject">
</div>
<div>
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea cols="50" rows="3" id="contactMessage" name="contactMessage"></textarea>
</div>
<div class="g-recaptcha captcha" data-theme="light" data-sitekey="6LfAkhQUAAAAAC2D3LxhB9XtYeoJGhuvR31sq9HW"></div>
<div>
<button class="submit">Submit</button>
</div>
</form> <!-- Form End -->
And I'm using ajax to send the data to sendMail.php file.
$('form#contactForm button.submit').click(function() {
$('#image-loader').fadeIn();
var contactName = $('#contactForm #contactName').val();
var contactEmail = $('#contactForm #contactEmail').val();
var contactSubject = $('#contactForm #contactSubject').val();
var contactMessage = $('#contactForm #contactMessage').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;
$.ajax({
type: "POST",
url: "inc/sendEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false; }); });
And this is so far my sendMail.php file. I'm trying to validate that if $error['captcha'] is empty along with other input field checks, the mail will be sent.
$secret = "<--secret key-->";
$user_ip = $_SERVER['REMOTE_ADDR'];
if(isset($_POST['g-recaptcha-response'])){
$response = $_POST['g-recaptcha-response'];
// echo "GOT response:".$response."<br/>";
}
else{
// echo "No reCAPTCHA response.<br/>";
}
//Verify response data
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$user_ip");
$responseData = json_decode($verifyResponse);
if(!$responseData->success){
$error['captcha'] = "Please prove that you're not a robot.";
}
Any suggestions what might be going wrong?
You forgot to add the ? after the url
url: "inc/sendEmail.php?",
OR
you could leave out the ? and send your data like
data: { this: this, that: that, another: another},
also since you are not posting the g-recaptcha-response to the php file with the form, but instead with AJAX you have to send the post manually to your php file.
var g-recaptcha-response= $('#contactForm .g-recaptcha-response').val();
var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
'&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage + '&g-recaptcha-response=' + g-recaptcha-response;
you made also need this to confirm the recaptcha in php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
https://developers.google.com/recaptcha/old/docs/php
I'm currently trying to create a contact form which I have used on other websites I have developed before, however, I'm having a problem with this one.
If the required fields are not filled in, an error message should fade in near the submit button and say "... is required."
Once all necessary fields are filled in, and the "Send message" button is clicked, the form is supposed to fade away and the success message is supposed to fade in, but at the minute, the form does nothing when you click the button.
Here is the HTML I am using;
<form id="contactForm" action="#" method="post">
<fieldset>
<div><input name="name" type="text" id="name" title="Name" value="Name •" /></div>
<div><input name="email" type="text" id="email" title="Email" value="Email •" /></div>
<div><input name="number" type="text" id="number" title="Contact Number" value="Contact number" /></div>
<div><input name="datepicker" type="text" id="datepicker" title="Date required" value="Date required"><div id="datepicker"></div></div>
<div><textarea name="message" class="form-poshytip" id="message" title="Message">Enter your message below; •</textarea></div>
The send mail configuration;
<!-- send mail configuration -->
<input type="hidden" value="my#email.co.uk" name="to" id="to" />
<input type="hidden" value="You have mail" name="subject" id="subject" />
<input type="hidden" value="send-mail.php" name="sendMailUrl" id="sendMailUrl" />
<!-- ENDS send mail configuration -->
<p><input type="button" value="Send message" name="Button" id="submit" span id="error" class="warning"></span></p>
</fieldset>
</form>
I have tried changing the input type of the button from
<input type="button" to <input type="submit"
and all that does is reload the page without sending the form.
This is the Javascript code I have;
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
// number
var number = $("input#number").val();
//datepicker
var name = $("input#datepicker").val();
//required:
//name
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// email
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required.");
$("input#email").focus();
return false;
}
// message
var message = $("#message").val();
if(message == ""){
$("#message").fadeIn().text("Message required.");
$("input#message").focus();
return false;
}
// send mail php
var sendMailUrl = $("#sendMailUrl").val();
//to, from & subject
var to = $("#to").val();
var from = $("#from").val();
var subject = $("#subject").val();
// data string
var dataString = 'name='+ name
+ '&email=' + email
+ '&message=' + message
+ '&to=' + to
+ '&from=' + from
+ '&subject=' + subject;
// ajax
$.ajax({
type:"POST",
url: sendMailUrl,
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
I have tried over and over again to get this to work but it doesn't... And it doesn't make any sense why it doesn't on this webpage I'm developing but does on others...
Is there SOMETHING I'm missing that I just can't see or is this code completely chuffed?
Try to include this
$(document).ready(function(){
//your code here
});
Your function in javascript capture click button but your form is current working if you doesn't capture it.. try this code I hope it help
Change your code to
$("#contactForm").submit(function(e) {
$("#error").hide();
// number
var number = $("input#number").val();
//datepicker
var name = $("input#datepicker").val();
//required:
//name
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// email
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required.");
$("input#email").focus();
return false;
}
// message
var message = $("#message").val();
if(message == ""){
$("#message").fadeIn().text("Message required.");
$("input#message").focus();
return false;
}
// send mail php
var sendMailUrl = $("#sendMailUrl").val();
//to, from & subject
var to = $("#to").val();
var from = $("#from").val();
var subject = $("#subject").val();
// data string
var dataString = 'name='+ name
+ '&email=' + email
+ '&message=' + message
+ '&to=' + to
+ '&from=' + from
+ '&subject=' + subject;
// ajax
$.ajax({
type:"POST",
url: sendMailUrl,
data: dataString,
success: success()
});
return false;
});
<script type="text/javascript"src="prototype.js"></script>
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
function sendRequest() {
var oform = document.forms[0];
var sBody = getRequestBody(oform);
var oOptions = {
method: "post",
parameters: sBody,
onSuccess: function (oXHR, oJson) {
saveResult(oXHR.responseText);
},
onFailure: function (oXHR, oJson) {
saveResult("An error occurred: " + oXHR.statusText);
}
};
var oRequest = new Ajax.Request("edit_status.php", oOptions);
}
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "Request completed: " + sMessage;
}
});
//]]>
</script>
I am new to ajax. i have a project at hand that really need a lot of ajax functionality. I am following this above code from a book i bought. when i copy this code on my local server, the ajax.request function is not working when i click the submit button. It takes me straight to the php page. Please can someone help me look at this?
**
<form method="post" action="SaveCustomer.php"
onsubmit="sendRequest(); return false">
<p>Enter customer information to be saved:</p>
<p>Customer Name: <input type="text" name="txtName" value="" /><br />
Address: <input type="text" name="txtAddress" value="" /><br />
City: <input type="text" name="txtCity" value="" /><br />
State: <input type="text" name="txtState" value="" /><br />
Zip Code: <input type="text" name="txtZipCode" value="" /><br />
Phone: <input type="text" name="txtPhone" value="" /><br />
E-mail: <input type="text" name="txtEmail" value="" /></p>
</form>
<div id="divStatus"></div>
**
**
header("Content-Type: text/plain");
//get information
$sName = $_POST["txtName"];
$sAddress = $_POST["txtAddress"];
$sCity = $_POST["txtCity"];
$sState = $_POST["txtState"];
$sZipCode = $_POST["txtZipCode"];
$sPhone = $_POST["txtPhone"];
$sEmail = $_POST["txtEmail"];
//status message
$sStatus = "";
//database information
$sDBServer = "localhost";
$sDBName = "ajax";
$sDBUsername = "root";
$sDBPassword = "";
//create the SQL query string
$sSQL = "Insert into Customers(Name,Address,City,State,Zip,Phone,`Email`) ".
" values ('$sName','$sAddress','$sCity','$sState', '$sZipCode'".
", '$sPhone', '$sEmail')";
$oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
#mysql_select_db($sDBName) or $sStatus = "Unable to open database";
if ($sStatus == "") {
if(mysql_query($sSQL)) {
$sStatus = "Added customer; customer ID is ".mysql_insert_id();
} else {
$sStatus = "An error occurred while inserting; customer not saved.";
}
}
mysql_close($oLink);
echo $sStatus;
?>
**
you arent firing the ajax i see you define the options but thats it try
using jquery u can wait for form submission
$('your form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'your url',
type:'post',
data:'your data',
success:function(data, jxhr){
//your success function
},
error:function(){}
});
});
the e.preventDefault() prevents the synchronous submission from firing default methods
looking at your code the sendRequest() can be changed to sendRequest(event) then add the event.preventDefault. I always have issues with return false
I have a very small page being managed by some javascript. When I load the page into the browswer the link after the form (id=login_linker) works fine.
However, when I load it into a div the same link wont work. Does anyone have any ideas.
Here is the body of the page that is being included.
<body>
<p>Forgot your password?</>
<form name="forgotpassform" id="forgotpassform" onsubmit="return false;">
<label for="email">Email: </label>
<input id="email" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="35">
<input type="button" style="margin-top: 15px; position:relative; left:50px;" id="forgotpassbtn" onclick="forgotpass()" value="Send me a new password">
<br>
</form>
<span id="emailstatus"> </span>
<span id="status"></span>
Log In
</body>
The javascript:
function forgotpass(){
var e = _("email").value;
var status = _("status");
var forgotpassform = _("forgotpassform");
if(e != ""){
_("forgotpassbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "forgotpass.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no_user"){
status.innerHTML = 'There was no matching email in the system.';
_("forgotpassbtn").style.display = "block";
} else if(ajax.responseText =="email_not_sent"){
status.innerHTML = 'There was a problem sending your temporary password.';
} else {
//status.innerHTML = ajax.responseText;
forgotpassform.innerHTML = "You have sent a temporary password to your email address. Please check your email.";
}
}
}
ajax.send("e="+e);
} else {
status.innerHTML = "Please enter your email address.";
}
}
function emptyElement(x){
_(x).innerHTML = "";
}
function loadlogin(){
$('#loginwindow').toggle(400);
$('#loginwindow').load("forgotpass.php");
$('#loginwindow').toggle(400);
}
$(document).ready(function(){
$(document).on('click', '#login_linker', function(){
alert('ok');
showlogin();
});
});
function showlogin(){
$('#loginwindow').load("login.php");
$('#loginwindow').toggle(400);
}
Here is the script to load the forgot password page ie the HTML above
function forgotpass(){
$('#loginwindow').toggle(400);
$('#loginwindow').load("forgotpass.php");
$('#loginwindow').toggle(400);
}
I don't know how your code to load the link using js is (it would be better if you post it too), but I guess the problem is you try to bind the event just after document is ready, and at that moment, the link isn't loaded yet. Bind it after loading it.