I am building a sign up form, and want to include it into a div on the main page. The main page also includes a 'log in' form.
Both forms are included on the page using php include commands in the appropriate div i.e:
<?php include_once("login.php")?>
<?php include_once("signup.php")?>
Now when I use ajax on the second form i.e. the signup.php form, it sends back information from the fields in the first form. It doesn't help that they are both email and password fields.
Does anyone know how I can isolate the information from each form so i can send the data from each form separately? Below is all the relevant code for the forms and the Javascript.
Here is the code for the first form(login.php):
<form name="loginform" id="loginform" onsubmit="return false;">
<input style="margin-bottom:5px;" id="email" type="text" class="searchbox" onblur="checkusername()" maxlength="35" value="Email">
<span id="emailstatus"></span>
<input id="password" class="searchbox" type="password" onfocus="emptyElement('status')" maxlength="88" value="Password">
<p>Log In / <a href="#" onclick="forgotpass()">Forgot Password</p>
<span id="status"></span>
</form>
and the ajax for it:
function login(){
//isolate the variables from the form
var p = _("password").value;
var e = _("email").value;
var status = _("status");
if(e != "Email" && p != "Password"){
_("loginbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//start the Ajax Request
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
status.innerHTML = 'There was a problem. Please check your email and password and try again. ';
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?id="+ajax.responseText;
}
}
}
//data being sent by the ajax call
ajax.send("e="+e+"&p="+p);
} else {
status.innerHTML = "You're missing something..";
}
}
function emptyElement(x){
//The _(x) function is a shortcut for getElementById
_(x).innerHTML = "";
}
//This jQuery used to pre populate the email and password fields with "email" and "password"
$('input .seachbox').each(function(){
$(this)
.data('default', $(this).val())
.focus(function(){
if ($(this).val() == $(this).data('default')||''){
$(this).val() = ''
}
})
.blur(function(){
var default_val = $(this).data('default');
if($(this).val() == ''){
$(this).val($(this).data('default'))
}
});
});
and the second form(signup.php):
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Email Address:</div>
<input id="emails" type="text" class="searchbox" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" class="searchbox" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" class="searchbox" onfocus="emptyElement('status')" maxlength="16">
</form>
<br> Create Account<p>
<div class="statuserror"><span id="status" >This is a permanent error</span></div>
</div>
and the ajax for it:
function signup(){
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if( e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "OK"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
_("p1").innerHTML = "Please check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("e="+e+"&p="+p1);
}
EDIT - SOLUTION:- Have - after 3 days found a solution so stupid i had to share it. Basically I changed the id of the status div from "status" to "status1" and found that everything is working fine now. I think that it might be because on the login page I also have a div named status so the browser is unsure which div to put it in and just does nothing. This also explains why the signup.php page works when run alone in the browser but not when the login.php is included along with it in the main page.
Moral of the story - MAKE SURE YOUR IDS ARE ALL DIFFERENT!!
Thanks to everyone for the help.
Related
I am using a form to submit email and name to the user. After submitting the form email triggered and success message displaying. Success message fade-out after 10 seconds i.e. fine. Now I want to download a pdf also after fadeout success message.
I am achieving this via action.
I am using below code:
<form class="brochure brochure_1" method="post" id="custom_contact_form" action="http://example.com/contact/index/contact" onsubmit="return validateForm();" name="myForm">
<div class="input-box">
<input type="hidden" readonly="readonly" class="input-text required-entry toname" value="" name="toname"/>
<input type="hidden" value="<?php echo $this->getFromUrl(); ?>" name="submiturl" class="submiturl" />
</div>
<input type="text" class="input-text required-entry" value="" name="name" placeholder="Name"/>
<input type="text" class="input-text required-entry" value="" name="email" placeholder="Email"/>
<span><input type="submit" value="Download" /></span>
</form>
<script>
function validateForm() {
var name = document.forms["myForm"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (email == "") {
alert("Email must be filled out");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
jQuery('.success-msg').insertBefore(jQuery( ".breadcrumbs" ));
jQuery(document).ready(function(){
setTimeout(function() {
jQuery('.success-msg').fadeOut('fast');
}, 10000); // <-- time in milliseconds
});
</script>
Replace the document ready like this,
jQuery(document).ready(function(){
setTimeout(function() {
jQuery('.success-msg').fadeOut('fast');
}, 10000); // <-- time in milliseconds
window.location.href = href; //causes the browser to refresh and load the requested url, Put the url to download pdf here.
});
I have a user settings page where the user changes their name via ajax and calls an update script that works great. The problem is I include a separate sidebar file which echos the current name in the database, but doesn't change until you reload the page because it's a separate sidebar.php include.
included sidebar.php within settings.php page
<h2 id="profile-name">
<?php
if(!$userRow['name']){
echo "You";
}else{
echo ucfirst($userRow['name']);
}
?>
</h2>
//form starts
<form id="my_form" onsubmit="submitForm(); return false;">
Name: <input id="name" type="text" class="form-control" placeholder= "<?php echo $userRow['name']; ?>" name="name" value="<?php echo $userRow['name']; ?>"><br>
<input class="btn btn-default" id="mybtn" type="submit" value="Submit Form"> <span id="status"></span>
</form>
//ajax works fine and updates database
function _(id){ return document.getElementById(id); }
function submitForm(){
var formdata = new FormData();
formdata.append( "name", _("name").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "update_name.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
} else {
// _("status").innerHTML = ajax.responseText;
alert("saved");
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
Just can't figure out how to get the sidebar to update without reloading the page. Thanks everyone!
I want to post login email and password to a PHP page using AJAX
<form onsubmit="authenticate()">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
AJAX:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
}
httpc.send(params);
}
}
If the select query returns a row after authentication, it echoes "success, else it echoes "fail"
I think your problem is that you're sending your params from inside the function onreadystatechange, it probably doesn't work at all right now, because the "state" will change once you send something, but your code doesn't send anything until the "state" has changed... This should fix it:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
else
alert(httpc.responseText);
}
// Your httpc.send was here
}
httpc.send(params); // <-- should be here
}
You must also change your HTML to add a return false; after the call to the authenticate function, in order to prevent the form from doing its "default" action (submitting to itself, in "GET" mode).
<form onsubmit="authenticate(); return false;">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
i have this small javascript to check if the email is valid, i check client side, couse its not 100% important that the mail is valid, and i dont want to re-direct the user just to check.
The issue is that the popup does apear, but the users values are still inserted
<script>
function popup()
{
var email = document.getElementById("email").value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (document.getElementById("email").value == "") {
alert("Enter an email");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("The email is not valid");
return false;
}
else
window.location = "email.php";
return true;
}
</script>
and here is the HTML form
<form action="email.php" accept-charset="UTF-8" class="signup_form" id="signup_form" method="post">
<input class="txt accent-color colorize_border-color required" id="email" name="email" placeholder="Indtast E-mail her" data-label-text="Email" type="email">
<input class="submit button big btn" id="submit_button" name="submit" value="Deltag nu!" onclick="return popup()" type="submit">
</form>
if i remove "type submit" it works, but i dont get the values with $_POST on the next page, they are null.
Any way to get around this?
Canonical
window.onload=function() {
document.getElementById(("signup_form").onsubmit=function() {
var email = document.getElementById("email").value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (document.getElementById("email").value == "") {
alert("Enter an email");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("The email is not valid");
return false;
}
return true;
}
}
using
<form action="email.php" accept-charset="UTF-8" class="signup_form" id="signup_form" method="post">
<input class="txt accent-color colorize_border-color required" id="email" name="email" placeholder="Indtast E-mail her" data-label-text="Email" type="email">
<input class="submit button big btn" id="submit_button" name="submit" value="Deltag nu!" type="submit">
</form>
i have a small problem.
When the form is submitted and the form returns false it will not submit again.
For instance. if the user misses out their name it will return false and show a message stating to input their name.
But the user can not resubmit the form without refreshing the page which means all data is lost.
How do i go about stopping this?
Here is the html side:
<form action="javascript:parseResponse();" method="post" name="ajaxcontactform" id="ajaxcontactform">
<div class="contacttextarea">
<input name="contactform" type="hidden" value="1" />
<fieldset>
<textarea name="comment" cols="5" rows="5" class="contacttextarea"onfocus="if (this.value == 'Please Leave A Message') {this.value = '';}">Please Leave A Message</textarea>
</fieldset>
</div>
<div class="contacttextboxes">
<fieldset>
<input id="name" name="name" type="text" class="contacttextform" onfocus="if (this.value == 'Please Insert Your Name') {this.value = '';}"value="Please Insert Your Name">
</fieldset>
<fieldset>
<input id="phone" name="phone" type="text" class="contacttextform" onfocus="if (this.value == 'Please Insert Your Phone Number') {this.value = '';}"value="Please Insert Your Phone Number">
</fieldset>
<fieldset>
<input id="email" name="email" type="text" class="contacttextform" onfocus="if (this.value == 'Please Insert Your Email') {this.value = '';}"value="Please Insert Your Email">
</fieldset>
<fieldset>
<input name="send" type="submit" class="contactformbutton" value="Send">
</fieldset>
</div>
</form>
Here is the jquery side
$(document).ready(function() {
//// Start Contact Form ////
$('#ajaxcontactform').submit(function(){$('input[type=submit]', this).attr('disabled', 'disabled');});
$('#ajaxcontactform').submit(
function parseResponse() {
var usersname = $("#name");
var usersemail = $("#email");
var usersphonenumber = $("#phone");
var usersmessage = $("#comment");
var url = "contact.php";
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailReg.test(usersemail);
if(!valid) {
$("#contactwarning").html('<p>Your email is not valid!</p>').slideDown().delay(3000).slideUp();
return false;
}
if (usersname.val() == "" || usersname.val() == "Please Insert Your Name") {
$("#contactwarning").html('<p>Please Insert Your Name!</p>').slideDown().delay(3000).slideUp();
return false;
}
if (usersemail.val() == "" || usersemail.val() == "Please Insert Your Email") {
$("#contactwarning").html('<p>Please Insert Your Email!</p>').slideDown().delay(3000).slideUp();
return false;
}
if (usersphonenumber.val() == "" || usersphonenumber.val() == "Please Insert Your Phone Number") {
$("#contactwarning").html('<p>Please Insert Your Phone Number!</p>').slideDown().delay(3000).slideUp();
return false;
}
if (usersmessage.val() == "") {
$("#contactwarning").html('<p>You forgot to leave a message!</p>').slideDown().delay(3000).slideUp();
return false;
}
$.post(url,{ usersname: usersname.val(), usersemail: usersemail.val(), usersphonenumber: usersphonenumber.val(), usersmessage: usersmessage.val() } , function(data) {
$('#contactajax').html(data);
$("#ajaxcontactform").fadeOut(100).delay(12000).fadeIn(3000);
$('#contactajax').fadeIn(3000).delay(3000).fadeOut(3000);
});
}
);
//// End Contact Form ////
});
Here is the php part:
<?php
if(isset($_REQUEST['contactform']) && $_REQUEST['contactform'] == 1){
echo '<p>Success!</p>';
} else {
echo '<p>Form could not be sent, please try again!</p>';
}
All is working apart from when an error is shown it will not resubmit.
Try replacing action attribute value of form with some URL instead of JavaScript method. Also have the parseResponse() method body directly executed in Form.submit() event.
Edit:
Add following line of code before return false in every if condition. It will do the trick.
$('input[type=submit]', $("#ajaxcontactform")).removeAttr('disabled');
When the user clicks submit, it looks like you're disabling the submit button (to prevent double submissions, I assume).
When returning false, you're never re-enabling the submit button. You will need to make sure that the disabled attribute is removed from the submit button before returning false.
you would want to return false in any case since you want to submit the form without reloading the page.
simply add return false after $.post(); to prevent the page reload
and if you want to disable the submit button after the submission, then do it in the call back function of $.post