Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick - javascript

I am creating a form filling website it should return alert message if contact,email is not up to our standard.
But I am getting this error Uncaught ReferenceError: submitToAPI is not defined at HTMLButtonElement.onclick
var URL is I am passing these data to AWS API gateway and trigger a lambda function.
form html code
<h4>Name:</h4>
<input type="text" style="height:35px;" id="name-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Company Name:</h4>
<input type="text" style="height:35px;" id="cname-input" placeholder="Enter name here…" class="form-control" style="width:100%;" /><br/>
<h4>Contact Number:</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/>4>
<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>
javascript
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
function submitToAPI(e) {
e.preventDefault(e);
var URL = "https://abc1234.execute-api.us-east-1.amazonaws.com/01/contact";
var e_name = /[A-Za-z]{1}[A-Za-z]/;
if (!e_name.test($("#name-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_cname = /[A-Za-z]{1}[A-Za-z]/;
if (!e_cname.test($("#cname-input").val())) {
alert ("Name can not less than 2 char");
return;
}
var e_phone = /[0-9]{10}/;
if (!e_phone.test($("#phone-input").val())) {
alert ("Please enter valid mobile number");
return;
}
if ($("#email-input").val()=="") {
alert ("Please enter your email id");
return;
}
var e_email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,6})?$/;
if (!e_email.test($("#email-input").val())) {
alert ("Please enter valid email address");
return;
}
var e_name = $("#name-input").val();
var e_cname = $("#cname-input").val();
var e_phone = $("#phone-input").val();
var e_email = $("#email-input").val();
var data = {
name : e_name,
cname : e_cname,
phone : e_phone,
email : e_email,
};
$.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("There is some issue with our servers please contact our landline for enquiry");
}});
}
</script>

You are using the script tag with a src attribute, your browser is only executing the remote JS (Jquery)
Create a new script tag without the src and add your code in this new block!

Correct way is to first load jQuery as your script is dependent on it.
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
</script>
After that you can include your script
<script>
$(document).ready(function () {
function submitToAPI(e) {
// your code
}
});
</script>
Make sure jQuery is properly loaded into your page. Check network tab in dev console, make sure there is no "404".
$(document).ready(function () {
// This code is being loaded after jQuery has been initialized
});

Related

Input type email still allows to go through

I have a textbox of input type email because it's meant for email addresses. So my page looks like this:
The input type of email should handle the syntax of email.So if email is test###gmail.com,it should not gone through though. When I hit send, it still able to initiate the email.
My javascript function:
<script>
//function to send email
function sendmessage(){
var recipient = document.getElementById("recipient").value;
var subject = document.getElementById("subject").value;
var content=document.getElementById("content").value;
$.ajax({
url: 'sendemail.jsp',
type: 'POST',
data: {
recipient:recipient,
subject:subject,
content:content
},
success: function (data) {
alert("Successfully initiated email to queue");
},
error: function (request, error) {
alert("Request: " + JSON.stringify(error));
}
});
}
</script>
<body>
<div class="email_font">
   To:<input type="email" style="font-size: 10pt;" size="70" id="recipient"><br><br>
Subject:<input type="text" style="font-size: 10pt" size="70" id="subject" ><br><br>
Content:<br><textarea cols="80" rows="10" id="content" style="font-size: 13pt;">
<%=files%>: <%=url%>
</div>
<div class="Send">
<button type="button" style="font: 13px/1.231 Trebuchet MS;" onclick="sendmessage()"> Send </button>
</div>
Clicking send still allows to send, is there anything I made wrong?
You can Split the emails on a comma and validate the entries one by one
Following is the code to accept multiple valid email id both comma and semicolon as separator
function validateEmails(emailString) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var result = emailString.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!regex.test(result[i])) {
return false;
}
}
return true;
}
Use the following code and it should help:
HTML:
<div class="input-wrp">
<input type="email" name="email" placeholder="E-MAIL ID*" required>
<p class="error">Email Error</p>
</div>
JS:
$('input[type="email"]').on('input', function() {
email($(this)); //Function Call
});
function email(input) { //Function
var inputVal = input.val();
var reg = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!reg.test(inputVal) && inputVal.length > 0) {
input.parent().find('.error').show();
} else {
input.parent().find('.error').hide();
}
}

How to post data using Ajax jQuery?

I want to send data from my website to a server for login form. I have a PHP script for that and it works fine as I already made an Android application using the same script. I am new to web development so I got stuck here.
I am getting an error of invalid keys but I mention proper key values in the name attribute. And after success I want to capture those values and as it contains some user information and I want to display it later.
HTML code
<form id="loginform">
<label for="phonenumber">Mobile Number</label>
<br/>
<!--<input type="tel" name="telNo" type="tel" size="20" maxlength="13">-->
<input type="text" id="userid" name="userid" size="20" maxlength="13" class="numeric" /><br>
<span class="error" style="color: red; display: none">Input digits (0 - 9)</span>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
$(function() {
$(".numeric").bind("keypress", function(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
$(".error").css("display", ret ? "none" : "inline");
return ret;
});
$(".numeric").bind("paste", function(e) {
return false;
});
$(".numeric").bind("drop", function(e) {
return false;
});
});
</script>
<br/>
<label for="Name">Password</label>
<br/>
<input type="password" id="upassword" name="upassword">
<br/>
<input type="submit" value="Login">
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function(e) {
e.preventDefault();
$.ajax({
type: post,
url: "https://smilestechno.000webhostapp.com/ChkRMNRegistered.php",
data: frm.serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
</form>
Error
Notice: Undefined index: userid in /storage/ssd1/323/4193323/public_html/ChkRMNRegistered.php on line 6
Notice: Undefined index: upassword in /storage/ssd1/323/4193323/public_html/ChkRMNRegistered.php on line 7
{"result":[{"ResultStatus":"FAIL"},{"PPLink":"http://smilestechno.000webhostapp.com/ImagesUpload/abc.jpg"}]}

How to get value from text box Using Jquery in asp.net and bootstrap

i am trying to get value from text boxes in my views in asp.net using jquery. i have also used bootstrap in my project. Due to it jquery is not getting value. kindly anyone guide me how to get value in this case.
javascript:
function Validate()
{
var username = $("#username").attr('value');
var password = $("#password").attr('value');
var url = "/User/ValidateUser/";
alert(username);
$.ajax({ // function calling
url: url,
data: { userId: username, Password: password },
cache: false,
type: "POST",
success: function (data)
{
if (data == "1")
{
//alert("Valid user Id ");
}
else
{
alert("Invalid user Id ");
}
},
error: function (reponse)
{
alert("Invalid user ID");
}
});
}
html:
<input class="textbox" id="username" type="text" placeholder="Username">
<input class="textbox" id="password" type="password" placeholder="Password">
attr(key) gets what is in the markup. Not what the current value is. You should use val() when trying to get the value of an input. As demonstrated below.
$('button').on('click', function() {
console.log(
$('#test').attr('value'),
$('#test').val()
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="Yo yo man" />
<button>Log Value</button>
Use .val() to get value from input , textarea elements.
Please refer :
http://api.jquery.com/val/
var username = $("#username").val();
var password = $("#password").val();

How to distinguish which button was clicked in the html form and based on that pass different values with ajax?

I have the following html form:
<form class="center" id="myform">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
<div class="terms">
<input type="checkbox" class="required" value="None" id="terms" name="terms">I accept terms</input>
</div>
</p>
<input type="submit" id="sendfeedback" value="now" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" id="postmelater" value="send" disabled/>
</form>
And as you can see above, I have a form with two buttons. The logic behind it works like that, that when I want to put text to database with current timestamp - I choose button sendfeedback. However, there's also a possibility of adding the feedback with chosen timestamp, that is happening when user choses the date from datetimepicker and hits postmelater. Now, the ajax code for that looks like this:
$(document).ready(function () {
$('#myform').validate({// initialize the plugin
errorElement: 'div',
rules: {
email: {
required: true,
email: true
},
slogan: {
required: true,
minlength: 2
},
terms: {
required: true,
maxlength: 2
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
});
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
});
There's a validation process attached to the fields and so far - only support for the first button. How can I add a support for 2nd button, and in case when user clicks it - also pass the datetime attribute to ajax? Can I distinguish them somehow in Ajax? Thanks!
Here depends on functionality of validation plugin, when it reacts, but likely you can try to add onclick to buttons which sets some hidden variable, indicating which button was pushed. Like this:
<input type="submit" id="sendfeedback" onclick="this.form.clickedbtn.value=1" value="now" disabled/>
<input type="submit" id="postmelater" value="send" onclick="this.form.clickedbtn.value=2" disabled/>
and also add hidden input to the form like this
<input type="hidden" id="clickedbtn" name="clickedbtn">
Than in the handler add
var clickedbtn = $("#textarea").val();
...
clickedbtn: clickedbtn,
so form will look like this:
<form class="center" id="myform">
<input type="hidden" id="clickedbtn" name="clickedbtn">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
I accept terms
</p>
<input type="submit" id="sendfeedback" value="now" onclick="this.form.clickedbtn.value=1" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" onclick="this.form.clickedbtn.value=2" id="postmelater" value="send" disabled/>
</form>
And handler will look like this:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
var clickedbtn = $("#textarea").val();
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
clickedbtn: clickedbtn,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
After that in php script you can check
if ($_POST["clickedbtn"]==1) {
send now code
} else {
other code
}
Change
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
to
$('#myform').find('input, textarea').on('change', function () {
var sendfeedbackbtn = $('#sendfeedback');
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
if ($('#myform').valid()) {
sendfeedbackbtn.removeAttr('disabled');
datepicker.removeAttr('readonly');
if (isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
}
} else {
datepicker.attr('readonly', 'readonly');
sendfeedbackbtn.attr('disabled', 'disabled');
postmelaterbtn.attr('disabled', 'disabled');
}
});
So it enables the sendfeedback and the timestamp input area. And if not valid, all button and timestamp area will be disabled.
Then add
$('#myform').find('#datetimepicker').on('change', function () {
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
// Need to implement isTimeValid method.
if ($('#myform').valid() && isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
} else {
postmelaterbtn.attr('disabled', 'disabled');
}
});
So when the timestamp area is changed, check if its valid (need implement isTimeValid), and decide whether to make postmelater able to clicked or not.
And your submit handler should be:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
// Decide to send a timestamp data or not.
var timestamp = $('#datetimepicker').attr('readonly') ? null : $('#datetimepicker').val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php',
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
// So this value will be null or whatever your input
timestamp: timestamp
},
success: function(response)
{
alert(response);
}
});
}
And you can decide PHP side's behavior on whether the given timestamp is a null value or not.
As you give all these inputs an id, I directly use its id selector to get them, but you can still change to other selector at wish.
You could use js/php to set the default value of your date field to be current date. That way you would only need one submit button:
<input type="date" value="<?php echo date("Y-m-d")?>">
or
<input type="date" id="datefield">
<script>
document.getElementById("datefield").value = new Date().getFullYear()+"-"+("0"+(new Date().getMonth()+1)).slice(-2)+"-"+("0" + new Date().getDate()).slice(-2);
</script>
But if you absolutely want to have two buttons, you could do:
<input type="button" onClick="firstButton()">
<input type="button" onClick="secondButton()">
and
function firstButton(){
//do what you need to
document.getElementsByTagName("form")[0].submit();
}
...and same for button two.

Passing form's input to Parse.com

I am playing around a bit with Parse.com and I am trying to send HTML form's content to Parse.com
I am kind of a Javascript noob so for some reason I cannot find a way to pass a variable I got from the form's input to Parse.com for processing.
Here's my code:
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();{
alert(text_value);
}
});
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
name: text_value,
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
</script>
You should wrap the code that does the saving inside a function, then call it when the user clicks the button. You have a few errors with your {} brackets as well. Indenting your code when writing it will help you avoid that.
<div class="main">
<form action="">
<label>Insert your ingridient :</label>
<input type="text" id="text" name="name" value="" />
<input type="button" id="text_value" value="Get Value"/>
<script type="text/javascript">
$(document).ready(function() {
$('#text_value').click(function() {
var text_value = $("#text").val();
save(text_value);
});
Parse.initialize("myAPIKey", "myAPIKey");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
function save(value) {
gameScore.save({name: text_value}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
}
});
};
};
</script>

Categories