Angular to submit second form after first form validation/promise - javascript

I'm submitting a form with an update() function in Angular, which then authenticates, returns a promise, and then submits a second form if successful.
The problem is, the second form won't submit with the document.getElementById(elementID).submit(); method. It will, however, submit with document.getElementById(elementID).click(); but only on non-touch devices of course.
Bottom line - why won't submit() work?
Here is a jsFiddle with a reduced and simplified version: http://jsfiddle.net/jimcamut/xos805gk/
Here is my function that handles the form submissions in its full version.
$scope.update = function(user) {
if ($scope.earlyUser.$valid) {
$scope.master = angular.copy(user);
console.log("Form submitted on front end");
// This integrates ParseJS and submits the data to a database - all good here, except after the promise
var parseUser = new Parse.Object("LaunchUser");
parseUser.setACL(new Parse.ACL());
parseUser.save({
name: $scope.master.name,
email: $scope.master.email,
zipcode: $scope.master.zipcode
},{
error: function(model, error) {
console.log("error is...");
console.log(error);
}
// Returns a promise
}).then(function(object) {
// Problem area here when attempting to submit second form...
document.getElementById('mc-embedded-subscribe').submit();
$scope.reset();
});
} else {
alert("Please correct the red form fields.");
}
};

element with id='mc-embedded-subscribe' is an input, but you need to "submit()" a form.
this line
document.getElementById('mc-embedded-subscribe').submit();
should be changed for
document.getElementById('mc-embedded-subscribe-form').submit();
Here you have a new fiddle with this changes, and it works!
http://jsfiddle.net/kx8dn8wc/

Related

Form not submitting data after validation

long time reader first time poster. I am having an issue with a form. It has email validator with JavaScript and once the validation is correct it supposedly has to submit the data but this doesn't happen. If I run the form without the validation the data goes through without a problem but with the validation I have a success message and then no data.
function ValidateEmail(email)
{
var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(!email.match(mailformat))
{
alert("valid email is required");
return false;
}else{
document.querySelector('form').submit();
setTimeout(function(){
window.parent.location = "https://www.xxxs.com/";
}, 3000);
}
}
window.onload= function(){
document.querySelector('input[type="submit"]').addEventListener("click",
function(e){
e.preventDefault();
var email = document.querySelector('input[name^="Email"]').value;
ValidateEmail(email);
});
}
Thank you for your help
You haven't provided the markup to go along with it, so I can only speculate that there's a problem with the markup.
I also have no idea why you've added this.
setTimeout(function(){
window.parent.location = "https://www.xxxs.com/";
}, 3000);
Apart from this, it works pretty well for my sandbox.
PS: I can't comment yet due to reputation, but #Kayden van Rijn might be interested in
/* Links that start with "https" and end in ".org" */
a[href^="https"][href$=".org"] {
color: green;
}
from MDN Web Docs

Click and wait for the new page to load

I am trying to login to a webpage. I filled the username and the password and also clicked the login button as shown in the code below.
casper.start(startURL, function () {
this.fill('.header-login-wrap', { // FILL THE USERNAME AND PASSWORD
email: username,
password: password
}, false); // Do not submit the form immediately
this.click('.btn-login'); // CLICK THE LOGIN BUTTON
this.waitForSelector('.modal',
function pass() {
console.log('pass');
},
function fail(resp) {
console.log('fail', resp);
}
);
});
After I have clicked the button, how to get to the new page. As soon as we log in, we are presented with a modal that has a class .modal. I am trying to wait before it loads. But every time the function fail is called with resp = 5000. Do not understand what it means. Is this the correct way to click the login button and then wait for the new page to load?
First, have you tried set to true the last parameter of fill()?
this.fill('.header-login-wrap', { // FILL THE USERNAME AND PASSWORD
email: username,
password: password
}, true); // Submit the form immediately
If this doesn't work, try to separating in steps, like casper.then() steps:
casper.start(startURL, function () {
this.fill('.header-login-wrap', { // FILL THE USERNAME AND PASSWORD
email: username,
password: password
}, false); // Do not submit the form immediately
});
casper.then(function(){
this.click('.btn-login'); // CLICK THE LOGIN BUTTON
});
casper.then(function(){
this.waitForSelector('.modal', function(){
this.capture('after_login.png');
this.echo('pass');
},function() {
this.capture('after_login_fail.png');
this.echo('fail');
}
);
});
All this assuming the selectors are the correct ones. I added capture() to log on images what the script is 'seeing'. For this you have to set the loadImages: to trueon pageSettings when creating the casper object.

redirected to a different page after submit validation

my php code echo "joined"; after everything works correctly and echo other messages if there was an error, when everything is submitted I want the user to be redirected to another page but it doesn't, when I click on submit it echos "joined" everything gets checked and submitted to the database but I need click on it a second time to get redirected to the other page.
$("#submit").click(function() {
$.post($("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
});
$("#myForm").submit(function() {
return false;
});
var ack = $("#ack").text();
if (ack.match('joined')) {
window.location.replace("user-login.php");
}
});
Your problem is that $.post() is an asynchronous function, and you treated your code as synchronous.
In other words, when the browser reaches this line:
var ack = $("#ack").text();
if (ack.match('joined')) {
window.location.replace("user-login.php");
}
the POST call has not finished yet, so the if is not happening.
So you need to move this logic in the 'success' callback of the $.post() function:
$.post(
$("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#ack").empty();
$("#ack").html(info);
if(info.match('joined')) {
window.location.replace("user-login.php");
}
}
);

Seeking more elegant solution to preventDefault() dilemma

I have a jQuery form-submission routine that has an input integrity check in ERROR_CHECK.PHP that relies on GET variables passed to it for inspection. If the values passed to it are malformed, then an alert box appears that explains the error and how the form data should be remedied. This alert box will need to pop up until the form data is no longer malformed, at which point that data is used for repopulating data on the page.
Thus, in the jQuery routine I'm at the mercy of our friend preventDefault(), and I have found a solution that does work, but not elegantly. The variable allowSubmit is initialized as FALSE and remains that way—with preventDefault() also in effect—until the form data passes the integrity check, at which point allowSubmit switches to TRUE...but that only happens with the submission of the correctly-formed input data. This means the user must submit the form a SECOND TIME in order for the form data to be used to replace data on the page...and that, of course, is not a solution (press the submit button twice?)
However, by dynamically submitting the form (here, with the $('#my_form').submit() statement) immediately after resetting allowSubmit to TRUE, I've submitted the form again, thereby allowing the user to submit correctly-formatted data ONCE, as it should be from the get-go.
This is obviously a band-aid solution and not elegant. Can anyone see a more elegant way to structure this? (I'm working with jQuery fashioned by another developer, and this occurs in the midst of a longer self-calling JQuery function, and I have to work with it on its own terms, lest I have to refashion all other parts of the larger function in which it occurs.
Here's a distillation of the code (with self-describing variables, etc.), which works as described, although not as elegantly as I'd like:
var allowSubmit = false;
$('#my_form').on('submit', function(e) {
if (!allowSubmit) {
e.preventDefault();
// Check to see if input data is malformed:
$.get('error_check.php', { new_element_name: $('#new_element_name').val() }, function(data) {
if (data != 0) {
alert("An Error Message that explains what's wrong with the form data");
} else {
allowSubmit = true;
// The line below--an auto-submit--is needed so we don't have to press the submit button TWICE.
// The variable allowSubmit is set to TRUE whenever the submitted form data is good,
// but the code suppressed by e.preventDefault() won't execute until the form is
// submitted a second time...hence the need for this programmatic form submission here.
// This allows the user to correct the errant form data, press the submit button ONCE and continue.
$('#my_form').submit();
}
});
}
$('#element_name').val($('#new_element_name').val());
});
What you are doing is okay, your other options might be to write a click handler for a generic button and submit the form through that event after validation, then you wont need to preventDefault as you won't be preventing any kind of submit action. Another solution might be to re-trigger the event after validation.
$("button").click(function() {
$("#my_form").submit();
});
...
allowSubmit = true;
// alternatively
jQuery( "body" ).trigger( e );
...
The callback solution you have doesn't seem unreasonable. I agree with #scott-g that a generic button click event handler would probably be your best bet. A more testable way to write what you have here may be:
var formView = {
$el: $('#my_form'),
$field: $('#element_name'),
$newField: $('#new_element_name'),
$submitBtn: $('#btn-submit')
}
var handleSubmit = function() {
var formData = formView.$field.val();
remoteVerify(formData)
.done(formView.$el.submit)
.done(updateForm)
.fail(handleVerificationError);
};
var remoteVerify = function(formData) {
var deferred = $.Deferred();
var url = 'error_check.php';
var data = { new_element_name: formData };
$.get(url, data)
.done(handleRequest(deferred))
.fail(handleRequestErr);
return deferred;
};
var handleRequest = function(deferred) {
return function (data, jqxhr) {
if (data != 0) {
deferred.reject(jqxhr, "An Error Message that explains what's wrong with the form data");
} else {
deferred.resolve(data);
}
}
};
var handleRequestErr = function() {
// error handling
}
var updateForm = function () {
formView.$field.val(formView.$newField.val());
}
var handleVerificationError = function (jqxhr, errMsg){
alert(errMsg);
}
formView.$submitBtn.on('click', handleSubmit)
You could try using an async: false setting using $.ajax (I don't know what your php is returning, so I am just "pretending" it's a json array/string like so echo json_encode(array("response"=>$trueorfalse));):
<script>
$('#my_form').on('submit', function(e) {
var valid_is = true;
// Check to see if input data is malformed:
$.ajax({
async: false,
url: 'error_check.php',
type: 'get',
data: { new_element_name: $('#new_element_name').val() },
success: function(response) {
var Valid = JSON.parse(response);
if(Valid.response != true) {
alert("An Error Message that explains what's wrong with the form data");
valid_is = false;
}
}
});
if(!valid_is)
e.preventDefault();
$('#element_name').val($('#new_element_name').val());
});
</script>
If you use async: false it runs the script in order and waits to execute the rest of the script until after it receives a response. Scott G. says you can do it with what you have with some slight modifications so I would try that first.

submit search query if conditions are met

How would I go about integrating these two functions together so that when submitting the search form, it will first check the http get response, then depending on whether there was an error or not, either submit the form, or display an error message?
All that I've tried has either made the form not work at all, or not take into account the 'http.get function'.
var http = require("http");
var url = 'http://examplepage.com/';
search.submit(function (event) { // submit search query function
if (searchBox.val().length < 2) {
searchBox.focus();
event.preventDefault();
}
});
http.get(url, function (res) {
res.resume();
// successful - so submit search query
}).on('error', function () {
// unsuccessful - display error message
});
You should probably subscribe on click event for you button that triggers search, the go check the url and inside success handler do
Sample code of Click handler
http.get(url, function (res) {
// successful
if (searchBox.val().length < 2) {
$('your form selector').submit();
}
}).on('error', function () {
// unsuccessful - display error message
});

Categories