Multiple AJAX forms with the same ID on the same page - javascript

I have two AJAX newsletter subscribe forms on the same page (top and bottom). Both forms have the same ID. The top form works perfectly, however I'm unable to get the alert messages to appear in the bottom form.
I found this question but wasn't sure how to implement the answer into my code.
Here's the form:
<div class="newsletter">
<form id="newsletter" class="newsletter-signup" action="" method="POST" accept-charset="UTF-8">
<input id="hero-section-newsletter-email-input" type="email" name="email">
<button class="button" type="submit">
Subscribe
</button>
<div id="newsletter-alert" style="display: none;" data-alert></div>
</form>
</div>
Here's the jQuery:
(function() {
'use strict';
var newsletterAlert = function(message) {
$('#newsletter-alert').text(message);
};
var isValidEmail = function(email) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return pattern.test(email);
};
$('#newsletter').on('submit', function(e) {
var data,
$form = $(this),
$email = $form.find('input[type="email"]');
e.preventDefault();
$('#newsletter-alert').show();
if ( !isValidEmail( $email.val() )) {
newsletterAlert('Looks like you entered an invalid email address! Please try again.');
} else {
newsletterAlert('Subscribing you now...');
data = $form.serialize();
$.ajax({
url: 'PATH_TO_SUBSCRIBE_PHP',
type: 'post',
data: data,
success: function(msg) {
if ( msg === 'success') {
newsletterAlert('Success! Please check your email to confirm.');
$email.val('');
} else {
newsletterAlert( msg );
}
},
error: function(msg) {
newsletterAlert('Error! ' + msg.statusText);
}
});
}
});
})();
Any help would be appreciated. Thanks

Don't use the same ID for the top and bottom forms.
An id must be unique in a document -- see MDN Docs.
Instead have two separate id's and reference them both in the one jQuery call when you are binding to the submit event:
$('#newsletter_top, #newsletter_bottom').on('submit', function(e) {
// ...
});
and in your HTML:
<form id="newsletter_top" ...>
</form>
<form id="newsletter_bottom" ...>
</form>

Related

form validation through javascript - error alert coming but saving the data

here I am comparing the location name whether its already entered or not, In my code I am getting alert when I click submit button but also data submitted. onchange function not working as I expected, can anyone help me how stop the data not submitting when I get alert?
When submitting time validation should be done, why because in our test server we are getting some delay after click button, so only data submitting after alert also. do you have any idea on this? Thanks in advance
<form class="form-inline" id="desgForm" accept-charset="UTF-8" method="post" action="../locationSubmit.htm" enctype="multipart/form-data">
<input type="text" id="locationName" autocomplete="off" name="locationName" class="form-control validate[required]" onchange="desgCheck();" onkeyup="firstToUpperCase1();" value="">
<button type="submit" class="btn btn-primary" >Save</button>
</form>
Javascript:
<script>
function desgCheck()
{
var locationName = document.getElementById('locationName').value;
$.ajax({
type: "POST",
url: "../designation/locationName.htm",
data: {
locationName: locationName
},
dataType: "text",
success: function (data)
{
if ($.trim(data) !== 'Data available')
{
alert("This Location already exist!!");
document.getElementById("locationName").value = "";
return false;
}
},
error: function (error) {
document.getElementById("locationName").value = "";
}
});
}
function firstToUpperCase1() {
var str = document.getElementById("locationName").value;
var a = str.toUpperCase();
$("#locationName").val(a);
}
jQuery("#desgForm").validationEngine();
</script>

Trying to stop form from redirecting after submit (return false & prevent.default are not working!)

The problem I've been trying to solve for hours and hours now is following: I cannot stop the redirecting of #myform action after the data has been submitted succesfully to database. I've tried multiple methods but none seem to work. I'm in dire need of help!
The code:
Html(mainview.php):
<div id="submitAccordion">
<form id="myForm" action="userFiles.php" method="post">
Name: <input type="text" name="accordionName" /><br />
<input id="sub" type="submit" name="go" />
</form>
<span id="result"> </span>
</div>
Javascript(mainview_script.js):
$("#sub").click(function () {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function () {
return false;
});
php(userFiles.php):
session_start();
require_once 'database.php';
if ( isset($_SESSION['user_id']) ) {
$sql = "INSERT INTO useraccordion (id, h3) VALUES (:id, :accordion)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->bindParam(':accordion', $_POST['accordionName']);
if ( $stmt->execute() ) {
echo "Succesfully inserted";
} else {
echo "Sorry, there was an error";
}
}
I have tried ajax method, prevent.default etc, but none work!
Either change your input type to button
<input id="sub" type="button" name="go" value="Submit"/>
Or try this:
$("form").submit(function(e){
e.preventDefault();
});
First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...
$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});
That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...
HTML...
<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>
Javascript...
$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});
It is sufficient to prevent deafult action on sub:
$("#sub").click(function (e) {
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function (event) { event.preventDefault(); });
That should stop the submission
If you are submitting your form data via ajax or jquery then you should change your input type form 'submit' to 'button' type
<input id="sub" type="button" name="go" value="go"/>

Custom made google form opens another tab on submit

I have made a custom google form and using google spreadsheet as my database.
But on clicking the submit button on the form the same page opens in a new tab
and the previous page text boxes have the data that the user has entered .
The custom form code is :
<form action="" target="hidden_iframe" method="POST" id="mG61Hd" onsubmit="submitted=true;">
<h5>Name</h5>
<input type="text" id ="_name" name="name">
<h5>emailaddress</h5>
<input type="text" id="_email" name="email">
<h5>message</h5>
<textarea name="entry.839337160" id ="_message"></textarea>
<button class="btn btn-lg btn-warning" onclick="postContactToGoogle()">Send</button>
</form>
The JavaScript code is :
function postContactToGoogle() {
var name = $('#_name').val();
var email = $('#_email').val();
var message = $('#_message').val();
validate();
if(validate=true)
{
$.ajax({
url: "https://docs.google.com/forms/d/1sKGYnZfwEC_3sQvsjjx57swxLxdHMHPBC89s5C72x5s/formResponse",
data: { "entry.2005620554": name,
"entry.1045781291": email, "entry.839337160": message },
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
swal("Heyy there","Thank You for your feedback!","success");
$('#_name').val('');
$('#_email').val('');
$('#_message').val('');
window.setTimeout(function(){location.reload()},4000)
},
200: function () {
swal("Heyy there","Thank You for your feedback!","success");
$('#_name').val('');
$('#_email').val('');
$('#_message').val('');
window.setTimeout(function(){location.reload()},4000)
}
}
});
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)
(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var email = $('#_email').val();
if (validateEmail(email)) {
} else {
swal('Oops!','The email '+email+' is not valid','error');
return false;
}
}
I myself solved the above issue by keeping the target of the form to a hidden iframe and creating a hidden iframe on the same page.

submitting a form via AJAX

I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});

submit the form using ajax

I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html page with various fields. At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.
function sendMyComment() {
var oForm = document.forms['addComment'];
var input_video_id = document.createElement("input");
var input_video_time = document.createElement("input");
input_video_id.setAttribute("type", "hidden");
input_video_id.setAttribute("name", "video_id");
input_video_id.setAttribute("id", "video_id");
input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
input_video_time.setAttribute("type", "hidden");
input_video_time.setAttribute("name", "video_time");
input_video_time.setAttribute("id", "video_time");
input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
oForm.appendChild(input_video_id);
oForm.appendChild(input_video_time);
document.forms['addComment'].submit();
}
The last line submits the form to the correct page. It works fine. But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values. anyone can help me?
Nobody has actually given a pure javascript answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
What about
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...
success: function(response) { ... },
});
You can catch form input values using FormData and send them by fetch
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
<input hidden name="crsfToken" value="a1e24s1">
<input name="email" value="a#b.com">
<input name="phone" value="123-456-789">
<input type="submit">
</form>
Look on chrome console>network before 'submit'
You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:
<form action="" method="post" onsubmit="your_ajax_function(); return false;">
Your Name <br/>
<input type="text" name="name" id="name" />
<br/>
<input type="submit" id="submit" value="Submit" />
</form>
Hope it helps.
Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.
document.querySelector('.ajax-form').addEventListener('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
let parsedData = {};
for(let name of formData) {
if (typeof(parsedData[name[0]]) == "undefined") {
let tempdata = formData.getAll(name[0]);
if (tempdata.length > 1) {
parsedData[name[0]] = tempdata;
} else {
parsedData[name[0]] = tempdata[0];
}
}
}
let options = {};
switch (this.method.toLowerCase()) {
case 'post':
options.body = JSON.stringify(parsedData);
case 'get':
options.method = this.method;
options.headers = {'Content-Type': 'application/json'};
break;
}
fetch(this.action, options).then(r => r.json()).then(data => {
console.log(data);
});
});
<form method="POST" action="some/url">
<input name="emails[]">
<input name="emails[]">
<input name="emails[]">
<input name="name">
<input name="phone">
</form>
It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.
So, your code will look like:
function sendMyComment() {
$('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
$.ajax({
type: 'POST',
url: $('#addComment').attr('action'),
data: $('form').serialize(),
success: function(response) { ... },
});
}
I would suggest to use jquery for this type of requirement . Give this a try
<div id="commentList"></div>
<div id="addCommentContainer">
<p>Add a Comment</p> <br/> <br/>
<form id="addCommentForm" method="post" action="">
<div>
Your Name <br/>
<input type="text" name="name" id="name" />
<br/> <br/>
Comment Body <br/>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>​
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
$("#submit").click(function(){
$.ajax({
type: 'POST',
url: "mysubmitpage.php",
data: $('#addCommentForm').serialize(),
success: function(response) {
alert("Submitted comment");
$("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
},
error: function() {
//$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
alert("There was an error submitting comment");
}
});
});
});​
I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest.

Categories