targeting a specific form with serialize() - javascript

Following on from my previous question, which was so quickly answered by Meder it wasn't funny, there's now an additional question that's popped up in the process of making a reusable jQuery form submitted that doesn't take the user away from where they were.
Problem
The jQuery serialize() function is performing its magic on all forms within a page, and not the specific form which was submitted. Example code below.
How do I capture the form's unique name/id, and replace "form" within $("form").serialize() with the name of the target form so only that is serialised?
Form code
<form name="contact" id="contact" action="">
<input name="_recipients" type="hidden" value="joe#fake.com" />
<input name="_subject" type="hidden" value="Title" />
...
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label><br />
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label class="error" for="email" id="email_error">This field is required.</label><br />
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label class="error" for="phone" id="phone_error">This field is required.</label><br/>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send your suggestion" />
</fieldset>
</form>
jQuery serialise and post
var dataString = $("form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/_global/assets/scripts/formmail/formmail.asp",
data: dataString,
...

var dataString = $('#contact').serialize()
If you are attaching an event handler to a button or the form's submit event then you can refer to it with this if inside the submit event handler function scope, eg
$('#contact').submit(function() {
alert( $(this).serialize() );
});
I highly recommend reading http://docs.jquery.com/Selectors

By using the "form" string as a selector, you are actually getting all the FORM elements within the page, in order to select only one form, you can:
Get the specific form by its id attribute (using the id selector):
var dataString = $("#contact").serialize();
Or by its name attribute (using the attributeEquals selector):
var dataString = $("form[name=contact]").serialize();

$("#contact").serialize()
Instead of using serialize there's a nice plugin that allows you to post your forms asynchronously. All you have to do is:
$(function() {)
$('#contact').ajaxForm();
});
Also don't forget to assign the correct action to the form, it shouldn't be empty.

Related

how to send form element values directly to php page using javascript

What I am trying here is when you click on submit button I am calling one javascript function which takes all the form element values and passes it to the php page without storing them inside the variable and then send those variables.
Example of my form:
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" onsubmit="sendvalues()" value="Stash the file!" />
</form>
Now on javascript, I want to send userid and email fields to directly go to php page without first retrieving them into a variable and then send that variable via ajax.
function sendValues() {
var formElement = document.querySelector("form");
console.log(formElement);
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "<?php echo VIEW_HOST_PATH;?>process_data.php");
formData.append("process_type", 'process_data');
request.send(formData); //want to send all form userid, email directly to php page
request.onreadystatechange = (e) => {
console.log(request.responseText)
}
}
Is this possible to send user_id and email values to php page directly? So, for example, form element which contains emailed and user info and any other forms element and they all send to php page via ajax but most important without storing this element values in javascript variables.
thanks
In your form you should specify property "action". That action would be your php file that will handle your submit action. Also you could add to this form id selector.
<form id="file-info" enctype="multipart/form-data" action="/process_data.php" method="post" name="fileinfo">
And now in your function sendValues() you could submit form like this:
function sendValues() {
document.getElementById("file-info").submit();
}
or you do not even need this function if you set your input button type to submit:
<input type="submit" name="submit" />
And then in your php file you can use your variables like:
if (isset( $_POST['submit']))
{
$userId = $_POST['userid'];
$email = $_POST['email'];
}
Try this one then
HTML CODE
<form enctype="multipart/form-data" method="post" class='submit_form' name="fileinfo">
<label>Your user name:</label>
<input type="text" name="name" id='name' placeholder="name" required /><br />
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" id='userid' placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" value="Stash the file!" class='submit' />
JQUERY CODE on the same page (include jquery)
$('body').on('click', '.submit', function(e) {
e.preventDefault();
$.ajax({
'url': 'mpay.php',
'type': 'POST',
'data': $('.submit_form').serialize(),
success: function(response) {
console.log(response);
}
});
});
PHP CODE The file name is mpay.php
$arr = [
'name' => $_POST['name'],
'email' => $_POST['email'],
];
echo "<pre>;
print_r($arr);
echo "</pre>";
Hope this helps.

How can I get a value from a form in page 1 to another page by using JavaScript?

I have only learned HTML, CSS, JavaScript and jQuery and I want to get a value from my form to my index page, which is located in different files, using the languages I know. So this is my form :
<form action="../index/index.html" method="GET">
<label for="name">Name :</label>
<input type="text" name="name" id="name" required>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="eg.yourname#gmail.com" required>
<input type="submit" name="submit" id="submit">
</form>
I want the value that a user submits in the #name input in my index's div tag when the submit button is pressed (this div has the class sing-in).
Both pages have their own JavaScript and CSS so if I would import the JavaScript of the page where the form is to my index pages it will mess up both pages I guess. Therefore, I want to do this without importing the JavaScript and just by taking the value from another page into my index page. Thank you.
When you submit your form and get redrected to your index page the values of the form will be put at the end of the url as GET parameters.
Example url: localhost:80/index/index.html?name=Eddie&email=eddie#gmail.com
To read the GET parameters you can use this code:
var urlString = window.location.href
var url = new URL(urlString);
var name = url.searchParams.get("name");
var email = url.searchParams.get("email");
//Check if name and email are set
Make sure to check if name and email have actually been set in index.html
You can get the values from for like this:
if this is the form
<form action="../index/index.html" method="GET">
<label for="name">Name :</label>
<input type="text" name="name" id="name" required>
<label for="email">Email :</label>
<input type="text" name="email" id="email" placeholder="eg.yourname#gmail.com" required>
<input type="submit" name="submit" id="submit">
</form>
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
or in jquery
var name = $('#name').val();
var email = $('#email').val();
have a look:
https://www.w3schools.com/jsref/prop_text_value.asp
this might help you

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

Dynamic Hidden Form Field Data Absent From POST

I have a form that, when submitted, does not post the dynamically added hidden field.
html:
<div>
<form action="thankyou.php" onsubmit="return validate()" id="orderform" method="post">
<input type="text" name="name" /><br>
<input type="text" name="email" required /><br>
<input type="text" name="charterco" required /><br>
<input type="text" name="bname" /><br>
<input type="text" name="dtime" required /><br>
<input type="submit" />
</form>
</div>
jquery:
$('#orderform').submit(function(eventObj){
$('<input />').attr('type','hidden')
.attr('id','list')
.attr('name','shopList')
.attr('value',sliststr>)
.appendTo('#orderform');
return true;
});
POST data from Chrome DevTools:
name:b
email:b#b.com
charterco:b
bname:b
dtime:12:00
message:Comment
I can't work out what's gone wrong. My sliststr variable turns up filled and correct in my little debugging test on jsfiddle here. For whatever reason, it isn't POSTing.
EDIT: As #JayBlanchard pointed out below, I am adding to the form after the POST has been written.
Try to append the dynamic element, set the value of it and then submit the form. Otherwise it's submitting the form and then appending the html in callback.
Try the following.
function validate(){
var shoplist = [1,2,3];
$('#orderform').append("<input type='text' name='shop' id='list'>")
$('[name="shop"]').val(shoplist)
$('#orderform').submit(function(eventObj){
return true;
});
}

JQuery - Duplicate Field Input Text In Real Time

I'm trying to figure out how to copy a users text input in one form field to another. Specifically, when someone fills in their email address in the contact form, it will be duplicated in the mailing list form.
Both these forms are using ajax so there's no concerns about the input text being lost on submit.
This is the code I have:
<div id="contact_form">
<form name="contact" method="post" action="">
<input type="text" name="name" id="name" size="30" value="Name" class="text-input" />
<label class="error" for="name" id="name_error">Please enter your name.</label>
<br />
<input type="text" name="email" id="email" size="30" value="Email" class="text-input" />
<label class="error" for="email" id="email_error">I need your email.</label>
<br />
<textarea rows="10" cols="30" type="textarea" name="message" id="message" value="Message" class="text-input" ></textarea>
<label class="error" for="message" id="message_error">A message is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit" value="Send" />
</form>
</div>
<div id="details">
<p>some details here, not sure what yet</p>
</div>
<div id="mail_list">
<input type="text" id="mail" value="Your email" name="mail_list" /><input type="submit" name="submit" class="button" id="submit" value="Send" />
</div>
I found this in the Jquery documentation, but couldn't get it to work:
$("#email").optionCopyTo("#mail");
Thanks!
You said you want it in real time. I assume that means while the user is typing, the value should be replicated for each keystroke.
If that's right, try this:
var mail = document.getElementById("mail");
$("#email").keyup(function() {
mail.value = this.value;
});
Or if you want more jQuery:
var $mail = $("#mail");
$("#email").keyup(function() {
$mail.val( this.value );
});
This will update for each keyup event.
I'd probably add a redundant blur event in case there's an autocomplete in the field.
$("#email").blur(function() {
$mail.val( this.value );
});
Since all your fields have unique ids, this is quite straight forward:
$(function() { // <== Doc Ready
$("#email").change(function() { // When the email is changed
$('#mail').val(this.value); // copy it over to the mail
});
});
Try it out with this jsFiddle
.change()
.val()
Is $("#mail") another input box ? It doesn't appear in your HTML (Edit: well it does now, but didn't at first :)
$("#mail").val($("#email").val()) should do what you want.
use keyup and change both.
$("#boxx").on('keypress change', function(event) {
var data=$(this).val();
$("div").text(data);
});
here is the example
http://jsfiddle.net/6HmxM/785/
you can simply do this
$('#mail').text($('#email').val())

Categories