Unable to validate form on submit - javascript

I'm using a small library called liveValidation.js.
I'm using this to validate a couple of inputs in a form.
It should automatically disable the form button if there's some invalid inputs, but it doesn't seam to work.
Here's my HTML code:
<form method="POST" id="contactForm">
<label for="name">Name</label>
<input type="text" name="name" id="contactFormName" value=""/>
<label for="email">E-Mail</label>
<input type="text" name="email" id="contactFormEmail" value=""/>
<label for="message">Your message here</label>
<textarea name="message" id="contactFormMessage"></textarea>
<input type="submit" id="submit" value="submit"/>
</form>
Here's how I initialize liveValidation.js:
function liveValidation() {
var name = new LiveValidation('contactFormName');
name.add(Validate.Presence);
var email = new LiveValidation('contactFormEmail');
email.add(Validate.Presence);
email.add(Validate.Email);
var message = new LiveValidation('contactFormMessage');
message.add(Validate.Presence);
};
$(document).ready(function ($) {
$("#loadingDiv").hide(400);
liveValidation();
sendEmail();
});
and this is the AJAX request code:
function sendEmail() {
var form = $("#contactForm");
var resultDiv = $(".formResult");
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "sendEmail.php",
data: form.serialize()
}).done (function (){
resultDiv.addClass('success').html('Message sent successfully')
}).fail(function () {
resultDiv.addClass('fail').html("Message not sent. Try again")
});
}
});
};
Any thought why this is not working properly?
Here's the livevalidation website if it could help -> http://livevalidation.com/

You need to check manually if the form is valid. To do that you need one (any one) of the LiveValidation objects
Try this
$(document).ready(function ($) {
var obj = liveValidation();
sendEmail(obj);
});
function liveValidation() {
var name = new LiveValidation('contactFormName');
name.add(Validate.Presence);
var email = new LiveValidation('contactFormEmail');
email.add(Validate.Presence);
email.add(Validate.Email);
var message = new LiveValidation('contactFormMessage');
message.add(Validate.Presence);
return name;
};
function sendEmail(obj)
{
var automaticOnSubmit = obj.form.onsubmit;
$("#submit").click(function () {
var valid = automaticOnSubmit();
if(!valid)
{
alert('The form is not valid!');
event.preventDefault();
}
else
{
//submi form
}
});
}
An alternate and better way, you can use any LiveValidation object to attach the event
$(document).ready(function ($) {
liveValidation();
sendEmail();
});
function liveValidation() {
var name = new LiveValidation('contactFormName');
name.add(Validate.Presence);
var email = new LiveValidation('contactFormEmail');
email.add(Validate.Presence);
email.add(Validate.Email);
var message = new LiveValidation('contactFormMessage');
message.add(Validate.Presence);
var automaticOnSubmit = name.form.onsubmit;
name.form.onsubmit = function(){
var valid = automaticOnSubmit();
if(valid)
alert('The form is valid!');
else
alert('The form is not valid!');
return false;
}
};
function sendEmail()
{
$("#submit").click(function () {
//submit form here
});
}

Related

Submit form to google sheet without reloading page and without jQuery using appscript doGet

I'm trying to submit data from html form to a google sheet, everything works correctly, but when I try to submit the form without reloading the page, the data is not displayed.I am trying to implement this in pure js without any libraries.
Apps Script code
var SHEET_KEY = '1IW8xdxivaSALFgUxGs9SIwAe07S6ZENEx-Ekr8l8aqU'
var SHEET_NAME = 'page1'
function doGet(e) {
var lock = LockService.getPublicLock()
try {
var doc = SpreadsheetApp.openById(SHEET_KEY)
var sheet = doc.getSheetByName(SHEET_NAME)
var data = []
data = [
e.parameter['pr_name'],
e.parameter['ing'],
e.parameter['gramm'],
e.parameter['class_p'],
]
sheet.getRange(sheet.getLastRow() + 1, 1, 1, data.length).setValues([data])
return ContentService.createTextOutput(
JSON.stringify({ result: 'success' })
).setMimeType(ContentService.MimeType.JSON)
} catch (e) {
return ContentService.createTextOutput(
JSON.stringify({ result: 'error', error: e })
).setMimeType(ContentService.MimeType.JSON)
} finally {
lock.releaseLock()
}
}
html form
<form class="gform" method="GET" action="https://script.google.com/macros/s/AKfycbxoDeBDNJtnPkNxsMmWwIAT7ojRnxgzWBH-wHQnCmfWD6a-gsOdPrSopQ_fK3GJVtlw3w/exec" >
<input type="text" name="pr_name" >
<input type="text" name="ing">
<input type="text" name="gramm">
<input type="text" name="class_p">
<input type="submit">
</form>
js сode shows that everything works but data does not appear
let form = document.querySelector('form');
form.addEventListener('submit', function(evt) {
evt.preventDefault();
sendData();
});
function sendData() {
const XHR = new XMLHttpRequest();
const FD = new FormData( form );
XHR.addEventListener( "load", function(event) {
alert( event.target.responseText );
} );
XHR.addEventListener( "error", function( event ) {
alert( 'Oops! Something went wrong.' );
} );
XHR.open( "GET", "https://script.google.com/macros/s/AKfycbxoDeBDNJtnPkNxsMmWwIAT7ojRnxgzWBH-wHQnCmfWD6a-gsOdPrSopQ_fK3GJVtlw3w/exec" );
XHR.send( FD );
}
I get this response
{"result":"success","data":[null,null,null,null]}

AngularJS + ASP.NET $http.post returning 401

I am trying to add a new Stop to my database. But I get a 401 error in asp.net.
.js file:
(function () {
"use strict";
angular.module("app-trips")
.controller("tripEditorController", tripEditorController);
function tripEditorController($routeParams, $http) {
var vm = this;
vm.tripName = $routeParams.tripName;
vm.stops = [];
vm.newStop = {};
vm.addStop = function () {
alert(vm.newStop.name);
$http.post("/api/trips/" + vm.tripName + "/stops", vm.newStop)
.then(function (response) {
vm.stops.push(vm.newStop);
};
}
}
.html file (input form):
<form novalidate name="newStopForm" ng-submit="vm.addStop()">
<div class="form-group">
<label for="">Date</label>
<input class="form-control" id="arrival" name="arrival" ng-model="vm.newStop.arrival" required />
</div>
<div class="form-group">
<label>Location</label>
<input class="form-control" id="name" name="name" ng-model="vm.newStop.name" required ng-minlength="3" />
</div>
<div>
<input type="submit" value="Add" class="btn btn-success" ng-disabled="newStopForm.$invalid" />
</div>
</form>
C# Post code:
[HttpPost("/api/trips/{tripName}/stops")]
public async Task<IActionResult> Post(string tripName, [FromBody]StopViewModel vm)
{
try
{
if (ModelState.IsValid)
{
var newStop = Mapper.Map<Stop>(vm);
var result =await _coordsService.GetCoordsAsync(newStop.Name);
if (!result.Succes)
{
_logger.LogError(result.Message);
}
else
{
newStop.Latitude = result.Latitude;
newStop.Longitude = result.Longitude;
}
_repository.AddStop(tripName, newStop, User.Identity.Name);
if (await _repository.SaveChangesAsync())
{
return Created($"/api/trips/{tripName}/stops/{newStop.Name}",
Mapper.Map<StopViewModel>(newStop));
}
}
}
catch (Exception ex)
{
_logger.LogError("Failed to save new Stop: {0}", ex);
}
return BadRequest("Failed to save new stop");
}
GeoCoordsService.cs:
public async Task<GeoCoordsResult> GetCoordsAsync(string name)
{
var result = new GeoCoordsResult()
{
Succes = false,
Message = "Failed to get coordinates"
};
var apiKey = _config["Keys:BingKey"];
var encodedName = WebUtility.UrlEncode(name);
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={apiKey}";
var client = new HttpClient();
var json = await client.GetStringAsync(url);
var results = JObject.Parse(json);
var resources = results["resourceSets"][0]["resources"];
if (!resources.HasValues)
{
result.Message = $"Could not find '{name}' as a location";
}
else
{
var confidence = (string)resources[0]["confidence"];
if (confidence != "High")
{
result.Message = $"Could not find a confident match for '{name}' as a location";
}
else
{
var coords = resources[0]["geocodePoints"][0]["coordinates"];
result.Latitude = (double)coords[0];
result.Longitude = (double)coords[1];
result.Succes = true;
result.Message = "Success";
}
}
return result;
}
I have read, that this is probably caused because the data is not in the right format, does anyone know what would be the right format, my webpage returns error 400, but deeper in my C# I can see that function var json = await client.GetStringAsync(url);is returning an error 401 (Unotharized). I guess I should also add username somewhere, but I don't know where.
You're getting a 400 because the request you sent isn't what the server is expecting. Find out the object the server is expecting on that endpoint. Then form your request body to match that object.

$.getJSON request does not work on button click

I have tried to find a solution to this problem, I'm currently at a loss. I'm trying to gather info on streams using the twitch API.
I am able to get a .getJSON request to work when I pass in an array of usernames, null is returned if the user is offline or invalid.
$(document).ready(function() {
var streamers = ["ESL_SC2","OgamingSC2","cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninjas","meteos","c9sneaky","JoshOG"];
var url = "https://api.twitch.tv/kraken/streams/";
var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";
getInitialStreams(streamers, url, cb); //load hard-coded streams
});
function getInitialStreams(streamers, url, cb) {
//loop through the streamers array to add the initial streams
for (var i = 0; i < streamers.length; i++) {
(function(i) {
$.getJSON(url + streamers[i] + cb, function(data) {
//If data is returned, the streamer is online
if (data.stream != null) {
console.log("online");
} else {
console.log("offline");
}
});
})(i);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
<input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
<button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
However, when I try to call the API through a click function (eventually pulling any input through the form) .getJSON fails. As seen below.
$(document).ready(function() {
var url = "https://api.twitch.tv/kraken/streams/";
var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";
$("#addStreamerBtn").click(function(e) {
addStreamer("Ben", url, cb);
});
});
function addStreamer(streamer, url, cb) {
console.log("I'm inside the function");
$.getJSON(url + streamer + cb, function(data) {
console.log("WE DID IT");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
<input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
<button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
I don't understand why the code won't work for the 2nd snippet. Any guidance would be greatly appreciated.
The issue is because you've hooked to the click event of the submit button. This means that the form is being submit as your AJAX request happens, so the page is immediately unloaded and the AJAX cancelled.
To fix this, hook to the submit event of the form, and call preventDefault() on the event. Try this:
$(document).ready(function() {
var url = "https://api.twitch.tv/kraken/streams/";
var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";
$(".form-inline").submit(function(e) {
e.preventDefault();
addStreamer("Ben", url, cb);
});
});
function addStreamer(streamer, url, cb) {
console.log("I'm inside the function");
$.getJSON(url + streamer + cb, function(data) {
console.log("WE DID IT");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
<input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
<button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>

ajax request function does not work when its called

<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

How to retrieve input value before submit

I have to retrieve three input values before submitting so I can use ajax to fill in the form depending on the information inside these boxes.
I first check that the three boxes have text using this script:
<script>
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
var direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
});
});
</script>
What I need is that when these three fields have a value to retrieve that value so I can pass it through a URL in PHP before submitting (ajax maybe?)
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
$value would be the variable (direccion) which is in the script.
If you need more information please let me know.
You need to set the variable as global to access it outside.due to declaring it in change, the scope of variable remains within change function only. so declare the variable outside change event.like this:
<script>
jQuery(document).ready(function () {
var flag = false;
var direccion="";//declare variable
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');//define variable on every on change
}
});
});
</script>
On your form you can add an onsubmit attribute which will define an action to take when the form is submitted.
eg :
<form method='GET' action='' onsubmit='doAjax();return false;'>
<input type='text' id='inp_name' value='hello'/>
</form>
<script>
function doAjax(){
alert("this form won't be posted!");
return false;
}
</script>
you need to make a ajax call to the url which is constructed
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
var direccio="";
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
$.ajax({
url: "target.php",
data:{'value':direccion},
success: function(response) {
//process the data received from server script
});
});
});
PHP CODE(target.php):
$value=$_POST['value'];
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
//further processing of data at server end and finally echo the data to client
You need to do it with your last desired input tag. Suppose you want data up to the 3rd input tag then you need to Call your custom function in the 3rd input tag with onkeyup="myFunction()"
In myFunction() you can check if the fields are populated or not and can also do the ajax to transfer the data to server

Categories

Resources