script in head doesn't seem to be executing - javascript

I'm trying to use lambda on AWS with api gateway to do a contact form on a static S3 web site, based on this blog post: https://aws.amazon.com/blogs/architecture/create-dynamic-contact-forms-for-s3-static-websites-using-aws-lambda-amazon-api-gateway-and-amazon-ses/
I don't think my script is running because my submit button does nothing. Any ideas what I might be doing wrong?
Here's my full page code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ltdrescue Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script "text/javascript">
function submitToAPI(e) {
e.preventDefault();
var URL = "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact";
var Namere = /[A-Za-z]{1}[A-Za-z]/;
if (!Namere.test($("#name-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var mobilere = /[0-9]{10}/;
if (!mobilere.test($("#phone-input").val())) {
alert ("Please enter valid mobile number");
return;
}
if ($("#email-input").val()=="") {
alert ("Please enter your email id");
return;
}
var reeamil = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!reeamil.test($("#email-input").val())) {
alert ("Please enter valid email address");
return;
}
var name = $("#name-input").val();
var phone = $("#phone-input").val();
var email = $("#email-input").val();
var desc = $("#description-input").val();
var data = {
name : name,
phone : phone,
email : email,
desc : desc
};
$.ajax({
type: "POST",
url : "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("Successfull");
document.getElementById("contact-form").reset();
location.reload();
},
error: function () {
// show an error message
alert("UnSuccessfull");
}});
}
</script>
</head>
<body>
<div id="wrap">
<div class="top_corner"></div>
<div id="main_container">
<div id="header">
<div id="logo"><img src="images/logo.gif" alt="" title="" border="0" /></div>
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Adopt</li>
<li>Support Us</li>
<li>Resources</li>
<li><a class="current" href="contact.html" title="">Contact</a></li>
</ul>
</div>
</div>
<div class="center_content_pages">
<div class="financial-application-form">
<h2>Contact Us</h2>
<p>
Please use this form to contact us with any suggestions or questions.
<br><br>
<b>Note:</b> due to the ever increasing number of animals in dire need of rescue, we are unable to intake owner surrenders.
</p>
<form id="contact-form" method="post">
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Phone:</h4>
<input type="phone" style="height:35px;" id="phone-input" placeholder="Enter phone number" class="form-control" style="width:100%;"/><br/>
<h4>Email:</h4>
<input type="email" style="height:35px;" id="email-input" placeholder="Enter email here…" class="form-control" style="width:100%;"/><br/>
<h4>How can we help you?</h4>
<textarea id="description-input" rows="3" placeholder="Enter your message…" class="form-control" style="width:100%;"></textarea><br/>
<div class="g-recaptcha" data-sitekey="6Lc7cVMUAAAAAM1yxf64wrmO8gvi8A1oQ_ead1ys" class="form-control" style="width:100%;"></div>
<button type="button" onClick="submitToAPI(event)" class="btn btn-lg" style="margin-top:20px;">Submit</button>
</form>
</div
</div>
<div class="testimonials">
<h2>Need to find a new home for your pet?</h2>
<p>
<img src="http://images.adoptapet.com/images/shelter-badges/Approved-Shelter_Paw-Print_Badge.png">
</p>
</div>
<div class="clear"></div>
</div>
<div class="footer">
<div class="footer_links">
<a class="current" href="default.html" title="">Home</a>
About
Adopt
Support Us
Resources
Contact
</div>
</div>
</div>
</div>
</body>
</html>

You have not added the script tag correctly Please refer below to correct it.
Wrong Way
<script "text/javascript">
Right Way
<script type="text/javascript"></script> OR <script></script>
See in HTML5 you can omit the type attribute but it's a good practice to add it.

Related

ajax jquery is not working

I am trying to submit the login request using Jquery Ajax. But the form is not submitting. I am tried to find the issue but can not. the code is vey simple but as I have started learning javascript so I am failing to find the problem in my code. Below is the code Please find the problem with it......
$(function() {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function(event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function(response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function(data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css" />
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
your html and javascript is working perfectly.
can you post your php code?.
otherwise try put this code in your login.php file:
<?php
echo "form submitted";
?>
If you are using js fiddle then import the jquery js file on the dropdown on the left side of the panel.
$(function () {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function (event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function (response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function (data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css"/>
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
Actually the problem was here. as the default form submission is prevented through javascript and I was looking for the message.
if (isset($_POST['submit_form'])) {
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
if (!empty($email) && !empty($password)) {
echo "Login Must be Successful...!";
} else {
echo "Login Failed....!";
}
}

Although ReCaptcha is loaded, why is it not displayed?

i have two HTML forms, ReCaptcha showA on one, but not the other. The code is identical fro both. What could be causing this problem?
Form-1 (ReCaptcha show display underneath Choose File.
Form-2 (Shows here)
PHP
require_once '/home/deje/public_html/writers-tryst/ReCaptcha/autoload/autoload.php';
// Register API keys at https://www.google.com/recaptcha/admin
$siteKey = '6LffIB8TAAAAACanI10YyJ-Rmw8CAKobwRDqr7Yr';
$secret = '6LffIB8TAAAAAEtF8obobrsoyn7T5BSL9Ewr2rFY';
// reCAPTCHA supported 40+ languages listed here: https://developers.google.com/recaptcha/docs/language
$lang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : "en";;
if (isset($_POST['g-recaptcha-response'])) {
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
echo 'err=' . $errors;
} else echo "no errors";
}
echo json_encode(array("sitekey" => "$siteKey", "lang" => "$lang"));
/*
$str1 = "'<div class='g-recaptcha' data-callback='recaptchaCallback' data-sitekey='$siteKey'></div>";
$str2 = "<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=$lang;</script>'";
echo $str1 . $str2;
*/
JS
$(function () {
$.ajax({
url: 'php/recaptcha.php',
type: 'post',
dataType: 'json',
cache: false
}).done(function (result, success, xhr) {
var script = "<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=" + result.lang + "'</script>";
var div = "<div class='g-recaptcha' data-callback='recaptchaCallback' data-sitekey= " + result.sitekey + "></div>"
$("#recaptcha-elements").append(div + script)
}).fail(function (xhr, desc, err) {
var msg = formatError("Initialize recaptcha error: ", err, xhr.responseText);
showMessage(0, msg);
console.log(msg);
});
});
ReCaptcha Callback
function recaptchaCallback() {
setTimeout(function() { $("#recaptcha-elements").css({ "display": "none" })}, 10000);
$('.btn.btn-default').removeAttr('disabled');
};
Form-1 HTML
<!DOCTYPE html>
<html>
<head>
<title>Writer's Tryst - Writers Form</title>
<link type="text/css" href="css/writers.css" rel="stylesheet" />
</head>
<body>
<div class="container center_div">
<!--<form id="form-writers" class="form-horizontal well">-->
<form action="php/writers.php" method="post" enctype="multipart/form-data" target="upload-target" onsubmit="startUpload();" >
<h1>Writers</h1>
<p>
<input id="title" name="title" class="form-control" placeholder="Title" required autofocus="true" />
</p>
<p>
<label for="work-type" class="fixed50">Type:</label>
<select id="work-type" name="work-type">
<option value="fiction">Fiction</option>
<option value="non-fiction">Non-Fiction</option>
<option value="screenplay">Screenplay</option>
<option value="play">Play</option>
</select>
</p>
<p>
<p>For an explanation of the genres shown here, see <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_genres">List of genres</a></p>
<label for="genre" class="fixed50">Genre:</label>
<select id="genre" name="genre">
</select>
</p>
<p>
<label for="subgenre" class="fixed50">Sub-Genre:</label>
<select id="subgenre" name="subgenre">`
<option value="-1">None</option>
</select><br/>
</p>
<p>
<label for="nbrPages" class="fixed50">Number of pages:</label>
<input id="nbrPages" name="nbrPages" required style="width: 48px" placeholder="Pages" /><br/>
</p>
<p>For a limied time, writers can upload their sysnopsis or query letterr for <span style="color: #f00; font-weight:bold">FREE</span>. We reserve the right to change this policy without notice.</p>
<div id="tips">The objective of a sysnopsis or query letter is to entice enablers into requesting your manuscript.
It must be concise and to the point, no more than two pages and, of course very well writtehref=n. Remember, brevity is the sole of wit.
Sample Query Letter
</div>
<div class="form-group">
<p id="file-warning">Your synopsis or query letter must be a PDF file.
<a target="_blank" href="https://www.freepdfconvert.com/" target="_blank">Free file conversion to PDF</a></p>
</div>
<div class="form-group">
<label for="file2upload">PDF to Upload</label>
<input id="file2upload" name="file2upload" type="file" required value="File to upload" />
</div>
<div id="recaptcha-elements"></div>
<div class="form-group">
<button type="submit" id="writers-submit" class="btn btn-default">Submit</button>
</div>
<input id="userid" name="userid" type="hidden" />
<iframe id="upload-target" name="upload-target" src="#" ></iframe>
</form>
<input id="filesize-limit" name="filesize-limit" type="hidden" value="2250000" /> <!--document size limited to 2,250,000-->
<script src="js/recaptcha.js"></script>
<script src="js/genres.js"></script>
<script src="js/writers.js"></script>
</div>
</body>
</html>

Persisting Session Storage

I need to persist the login status in sessionStorage but I cant seem to get it to work, can someone help me edit the sessionstorage code to make this work?
Below is my code with the session storage script that I'm trying to make work.
<head>
<meta name="viewport" content="width=device-width, user-scalable=yes, initialscale=1.0">
<link rel="stylesheet" type="text/css" href="logincss.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="loginjavascript.js"></script>
<script>
$(document).ready(function () {
$('#form').submit(function (event) {
$.post(this.action, $(this).serialize(), function (data) {
alert(data.msg+" "+data.status);
$('#status').html(data.msg);
if (data.status==1){
$('#hide').toggle();
//'Sessionstorage here'
$('login').click(function () {
var name = this.name;
var info = 'div#' + name;
if ($(info).is(':hidden')) {
if (sessionStorage[name]) {
var obj = JSON.parse(sessionStorage[name]);
var div = 'div#' + obj.pid;
$(div).html(item({product: obj}));
}
}
$(info).toggle();
return false;
});
}
}, 'json');
event.preventDefault();
});
});
</script>
</head>
<header class="cf">
<img src="images/badnoise.png" alt="logo" width="199" height="92">
<nav>
<ul>
<li id="login">
<div id="status">Not logged in</div>
<a id="login-trigger" href="#">
Log in <span>▼</span>
</a>
<div id="login-content">
<form id="form" action="login.php">
<fieldset id="inputs">
<input id="username" type="email" name="Email" value="bard#stratford.com" placeholder="Your email address" required />
<input id="password" type="password" name="Password" value="Hamlet34" placeholder="Password" required /><br/>
Password contains at least 1 capital letter. <br/>
Password contains at least 5 lower case letters. <br/>
Password contains at least 1 number.<br/>
Password must be a minimum of 8 characters.
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit1" value="Log in">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form>
</div><br/>
</li>
</ul>
</nav>
<center><h1>Artists<a> || <a href="songs.php">Songs</h1></center><h1>
</header>
Thank you

Ajax Contact Form Not Sending Emails [duplicate]

This question already has answers here:
Ajax Contact Form Problems - No email being sent
(2 answers)
Closed 9 years ago.
Sorry for being a noob but I'm trying my best. I've done and read everything I could find and I have never got this to work. Would really appreciate the help. The form id matches in the html and javascript. The PHP is linked in the Javascript and I have the javascript linked in the head of my html. What am I missing? I've tried other codes I found online as well and nothing.. The issue is that no email ever gets sent through. If you hit send the page reloads and thats it.
<!--[if lte IE 8]>
<script src="js/html5shiv.js"></script><![endif]-->
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.dropotron.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<script src="js/contact.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-noscript.css" />
</noscript>
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" /></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
</div>
</div>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if (preg_match( $test, $val ))
exit;
}
//send email
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
JS:
$('#contact').submit(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : dataString,
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
Thanks.
try preventing the default form submission by changing:
$('#contact').submit(function() {
...
to
$('#contact').submit(function(evt) {
evt.preventDefault();
//rest of your js code
and you dont have input elements with id name, email and message as per your posted code. Add those as ids to your input elements

jQuery not hiding elements

Here's my code, what I'm trying to do is have javascript check a form and then submit it to a PHP script via AJAX that will log the user in.
<!DOCTYPE html>
<html>
<head>
<title>RPEMS: Login</title>
<link rel="stylesheet" type="text/css" href="../main.css"></link>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type='text/javacript'>
$(function()
{
$('.error').hide();
$('.button').click(function()
{
$('.error').hide();
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var email = $('input#email').val();
var pass = $('input#pass').val();
var err = false;
if (!email)
{
$('label#emErr').show();
$('input#email').focus();
err = true;
}
if (!filter.test(email))
{
$('label#emValErr').show();
$('input#email').focus();
err = true;
}
if (!pass)
{
$('label#passErr').show();
$('input#pass').focus();
err = true;
}
if (err) return false;
var dataString = 'email=' + email + '&pass=' + pass;
$.ajax({
type: "POST",
url: "log.php",
data: dataString,
success: function(result)
{
if (result.success == true) window.location('../');
else $('p#phpErr).html(result.message).show();
}});
}
});
</script>
</head>
<body>
<div id="header">
<img id="logo" src="../img/logo.png"></img>
<ul id="navBar">
<li class="navLink">
Home
</li>
<li class="navLink">
About/Contact Us
</li>
<li class="navLink">
Calendar
</li>
<li class="navLink">
Login
</li>
</ul>
</div>
<form method='post' action=''>
<fieldset>
<label for='email'>Email: </label>
<input name='email' id='email' type='text'></input>
<br class='error'></br>
<label for='email' class='error' id='emErr'>This field is required</label>
<label for='email' class='error' id='emValErr'>Invalid email adress</label>
<br class='error'></br>
<label for='pass'>Password: </label>
<input name='pass' id='pass' type='password'></input>
<br></br>
<label for='pass' class='error' id='passErr'>This field is required</label>
<br class='error'></br>
<p class='error' id='phpErr'></p>
<input type='submit' name='submit' id='submit_btn' value='Submit'></input>
</fieldset>
</form>
Sadly when I load the page though, the errors aren't hidden, any idea why?
You have a Uncaught SyntaxError: Unexpected token ) in your code. Please make sure you are always checking your console in the browser. See jsfiddle
Here is your working jsfiddle. You are missing a single quote in your line else $('p#phpErr').html(result.message).show(); as well as a closing ); before your document.ready
Please always check your console as this will help you out with errors like this... If you dont know how to use the console. Check this out
you have illegal MIME-type for your script (missing s)
<script type='text/javacript'>
That is why browser even does not attempt to execute it
Change to correct type="text/javascript"
Also at last lines of your script there is several syntax errors, fix to this:
else $('p#phpErr').html(result.message).show(); //missing quote here
}});
}); //missing ) here
});

Categories

Resources