I am attempting to submit the form data to another page to be processed and am currently need receiving any data. Below are the forms in question. Default form is the login for requesting username/password. One submit button.
<div id="form_wrapper" class="form_wrapper">
<form class="register">
<h3>Register</h3>
<div>
<label>Username:</label>
<input type="text" name="regname"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password:</label>
<input type="password" name="regpass" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input type="submit" value="Register"></input>
You have an account already? Log in here
<div class="clear"></div>
</div>
</form>
<form class="login active">
<h3>Login</h3>
<div>
<label>Username:</label>
<input type="text" name="username"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password: Forgot your password?</label>
<input type="password" name="password" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input type="submit" value="Login"></input>
You don't have an account yet? Register here
<div class="clear"></div>
</div>
</form>
<form class="forgot_password">
<h3>Forgot Password</h3>
<div>
<label>Username or Email:</label>
<input type="text" name="forgotuser" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<input type="submit" value="Send reminder"></input>
Suddenly remebered? Log in here
You don't have an account? Register here
<div class="clear"></div>
</div>
</form>
</div>
I would like to submit what ever the current form data is
$form_wrapper.find('input[type="submit"]')
.click(function(e){
e.preventDefault();
$.ajax({
url: 'locallogin.php',
type: 'POST',
data: $(this).serialize(),
success: function (results) {
alert(results);
}
});
});
locallogin.php
<?php
print_r($_POST);
?>
Right now the only response is an empty Array. Any ideas?
There are two issues - one as indicated in the comments - you need to use $_POST.
Another lies in,
data: $(this).serialize(),
$(this) is pointing to the button, so you are posting the serialized button. Try as follows :
data: $(".register").serialize(),
As mentioned previously, fix the $(this) and make it $("#form_wrapper") also fix the $POST to $_POST. Your JS should look like this.
$('#form_wrapper').find('input[type="submit"]')
.click(function(e){
e.preventDefault();
$.ajax({
url: 'locallogin.php',
type: 'POST',
data: $(this).closest('form').serialize()+'&buttonName='+$(this).val(),
success: function (results) {
alert(results);
}
});
});
AFTER THE QUESTION ABOUT THE BUTTON NAME.
Added code to the data line of the ajax call.
First, you're serializing $(this) in the click even of an input element. You might want to use data: $(this).closest('form').serialize(). Second, it's print_r($_POST) (you're missing the underscore).
Related
In the HTML, the forms look identical, just the form ID is changed. I use this JS file to submit the forms using AJAX:
$("#change-password").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-password").serialize(),
success: function(data) {
$("div.change-password-response").html(data);
}
});
e.preventDefault();
});
$("#change-email").submit(function(e) {
var url = "http://domain/actions";
$.ajax({
type: "POST",
url: url,
data: $("#change-email").serialize(),
success: function(data) {
$("div.change-email-response").html(data);
}
});
e.preventDefault();
});
HTML Part
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare parola</h4>
<form id="change-password" method="post">
<div class="form-group">
<label>Parola veche</label>
<input class="form-control" name="old_password" id="old_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Parola noua</label>
<input class="form-control" name="new_password" id="new_password" type="password" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma parola noua</label>
<input class="form-control" name="confirm_new_password" id="confirm_new_password" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-password">
<button type="submit" class="btn_1 green">Actualizeaza parola</button>
<div class="change-password-response form-response"></div>
</form>
</div>
<div class="col-md-6 col-sm-6 add_bottom_30">
<h4>Schimbare adresa email</h4>
<form id="change-email" method="post">
<div class="form-group">
<label>Email vechi</label>
<input class="form-control" name="old_email" id="old_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Email nou</label>
<input class="form-control" name="new_email" id="new_email" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Confirma email nou</label>
<input class="form-control" name="confirm_new_email" id="confirm_new_email" type="password" autocomplete="off">
</div>
<input type="hidden" name="action" value="change-email">
<button type="submit" class="btn_1 green">Actualizeaza Email</button>
<div class="change-email-response form-response"></div>
</form>
</div>
Now, my problem is that Form 1 is working, Form 2 is not triggering the AJAX and works as normal form. What am I doing wrong?
Check if #change-email has other binded events.
In Firebug, inspect #change-email element and go to Event tab.
In Chrome, inspect that element and go to Event Listeners tab.
You will see all binded events and corresponded callback functions.
If it will not help, try to submit a form manually from Console
Inspect a form, then run
$($0).submit();
If it will work, looks like you have some events on you button.
I'm having a little problem getting a form to submit via ajax. I think it's one of two problems:
leads.py (which I am able to view, but do not have the ability to modify) is expecting a submit input name of name="submitButtonName" and because I am using e.preventDefault(); to disable normal form submitting the form is not being handled by the handler when submitted.
It could be possibly that the data being serialized is wrong, when i output it to console it looks like this which appears to be duplicated:
first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com&remarks=&first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com
any suggestions?
here is the full script:
<!-- Defines element markup -->
<dom-module id="landing-modal">
<template>
<div id="landing-modal" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-body">
<p class=lead>
To view this listing, please provide us with some basic contact information...
</p>
<form class="form-horizontal lead-form" method="post" action="/leads/buy">
<div class="control-group">
<label class="control-label">Required Information</label>
</div>
<div class="control-group">
<label class="control-label">First Name</label>
<div class="controls">
<input type="text" name="first_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name</label>
<div class="controls">
<input type="text" name="last_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Email</label>
<div class="controls">
<input type="email" name="email_addr" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<div class="controls">
<input style="display:none;" type="text" name="remarks" value="" />
<input type="reset" value="Reset" name="reset" class="btn">
<input class="btn btn-primary" type="submit" name="submitButtonName" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</template>
<script>
$(document).on('submit', '.lead-form', function(e) {
$.ajax({
url: $('.lead-form').attr('action'), //gets the action url
type: $('.lead-form').attr('method'), //gets the form method post
data: $('.lead-form').serialize(), //creates the form submit date eg. FirstName=Mickey&LastName=Mouse
success: function(html) {
console.log($('.lead-form').serialize());
}
});
e.preventDefault(); //prevents the submit input from being submitted normally
});
Polymer({
is: 'landing-modal',
created: function() {},
ready: function() {},
attached: function() {},
detached: function() {},
attributeChanged: function(name, type) {}
});
</script>
</dom-module>
edit::
I tried to add
<input type="hidden" name="submitButtonName" />
<input class="btn btn-primary" type="submit" name="submit" value="Submit" />
which results in a 500 error in console
server side code:
if "submitButtonName" in kwargs:
errors = []
if not kwargs['first_name']:
errors.append("Please enter your first name.")
if not kwargs['last_name']:
errors.append("Please enter your last name.")
if not kwargs['email_addr']:
errors.append("Please enter your email address.")
if errors:
error_msg = "<ul>" + "".join([
"<li>"+x for x in errors
]) + "</ul>"
result['error_msg'] = error_msg
else:
save = True
if save:
# 'remarks' is an invisible field that can only get filled in by
# spam bots, so if there's a value in it, ignore the submission.
if kwargs['remarks']:
import sys
sys.stderr.write("Ignoring spam submission: %r\n" % ([mode,kwargs],))
else:
self.save_form(mode, kwargs)
raise cherrypy.InternalRedirect("/leads/thankyou/"+mode)
result.update(self.form.render(values))
if mode=="C":
result.update(self.cmaform.render(values))
if mode=="E":
result.update(self.contactform.render(values))
return result
I am trying to test PHP post data using AJAX. From page test I want to post on to the same page and check if PHP receives post data, if data is posted just to see if redirection is successful, so that I can write authentication code and assign session before page redirects.
When I click on the login button, I just checking isset post data and if data exists then redirect. I am not sure why this is not working. Any help is appreciated.
<script>
$(document).ready(function(){
$('#login').click(function(){
$.ajax({
type: 'POST',
url: 'http://domain.com/backend/test',
data: { username: "John", password: "Boston" }
});
return false;
});
});
</script>
<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
redirectto("http://domain.com/backend/test2");
// redirecto is a function equivalent to header location
}
?>
<form autocomplete="off" class="ui fluid form segment" method="post">
<div class="ui fluid form segment">
<div class="two fields">
<div class="field">
<label>Email/Username</label>
<input placeholder="Email/Username" name="username" id="username" type="text">
</div>
<div class="field">
<label>Password</label>
<input placeholder="Password" name="password" id="password" type="password">
</div>
</div>
<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
</div>
</form>
Change
<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
to
<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
Even if you triggered the click event of #login button, its a submit type and it will trigger the submit event first. Changing the button type should help.
In the JS, instead of using a click event, use submit.
I mean, instead of
$('#login').click(function(){
use
$('#login').submit(function(){
Also, you may add an action property to the form:
<form autocomplete="off" class="ui fluid form segment" method="post" action="#">
I have the following ajax script and form to login to my website:
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
<script>
$.ajax({
type: "post",
url: "/doLogin",
data: $('#login').serialize(),
success: function(result) {
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
but it doesn't preform the ajax, and brings me to the result page, which is not what I want. Is there any specific reason that the AJAX is not working? I'm kind of new to JavaScript so sorry if this is obvious.
You are running the Ajax function as soon as the script loads, and not doing anything to prevent the form from submitting normally when the form submits.
You need to move the JS you have already into a function. Then bind that function as a submit handler on the form. Then prevent the default behaviour of the submit event.
$('#login').on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
success: function(result) {
if (result == " success") {
window.location = "/index.php";
} else if (result == " failure") {
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
<form action="/doLogin" method="post" id='#login'>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<label for="email" class="input-group-addon">E-Mail</label>
<input type="email" class="form-control" name="email" id="email" value="" />
<br />
</div>
<div class="input-group">
<label class="input-group-addon" for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form>
</div>
That said - when you successfully login, you just redirect to another page. You are almost certainly better off not using Ajax at all for this.
The following link may be helpful if you are new to ajax
http://webdevelopingcat.com/jquery-php-beginner-tutorial-ajax/
login should be the form id but you did not post your form opening tag
<form id = "login">
and in your ajax code you should handle the submit event of the form like this:
$("#login").submit(function({ // your logic should be here
}))
I'm trying to open a nice popup for editing a domain object.
For this I have a popup template hidden inside an invisible div on a page.
When user clicks a button, I try to load the domain object with ajax, populate the template and show it.
Trouble is that only first field inside template is populated.
Template:
<div class="popup" id="addDriverPopup">
<div class="close"></div>
<hr class="both"/>
<div class="container radius">
<form action="/driver/manageDriver" method="post" name="driverForm" id="driverForm" >
<input type="hidden" name="id" id="id" value="" />
<div class="title"><span>Uus autojuht </span><hr class="line"/></div>
<p class="name">Nimi </p>
<p class="input"><input type="text" name="firstName" id="firstName" value="" /></p>
<p class="name">Perekonna nimi </p>
<p class="input"><input type="text" name="lastName" id="lastName" value="" /></p>
<p class="name">Isikukood </p>
<p class="input"><input type="text" name="personalId" id="personalId" value="" /></p>
<p class="name">Telefoni number </p>
<p class="input"><input type="text" name="phoneNumber" id="phoneNumber" value="" /></p>
</form>
</p>
</div>
</div>
Javascript:
$jq.ajax({
url: 'show',
dataType: 'json',
data: {driverId: driverId},
success: function( data ) {
var popup = $jq('#addDriverPopup').clone();
popup.find("#id").val(data.id);
popup.find("#firstName").val(data.firstName);
popup.find("#lastName").val(data.lastName);
popup.find("#personalId").val(data.personalId);
popup.find("#phoneNumber").val(data.phoneNumber);
alert(popup[0].innerHTML); // only id field is field in the template.
},
error: function(xhr, error) {
alert(error);
unblockUI();
}
});
Output of alert():
<div class="close"></div>
<hr class="both">
<div class="container radius">
<form action="/driver/manageDriver" method="post" name="driverForm" id="driverForm">
<input name="id" id="id" value="1271672" type="hidden">
<div class="title"><span>Uus autojuht </span><hr class="line"></div>
<p class="name">Nimi </p>
<p class="input"><input name="firstName" id="firstName" value="" type="text"></p>
<p class="name">Perekonna nimi </p>
<p class="input"><input name="lastName" id="lastName" value="" type="text"></p>
<p class="name">Isikukood </p>
<p class="input"><input name="personalId" id="personalId" value="" type="text"></p>
<p class="name">Telefoni number </p>
<p class="input"><input name="phoneNumber" id="phoneNumber" value="" type="text"></p>
</form>
<p></p>
</div>
Data returned from the server:
{"id":1271745,"firstName":"Burak","lastName":"Torum","personalId":"123456","phoneNumber":"123456"}
I double checked element ids for typos. Debug shows that the correct elements are found.
What am I missing?
Thanks in advance
Try changing
alert(popup[0].innerHTML);
to
alert(popup.html());
Also I a not seeing the '#addDriverPopup' element on the code you provided... is that on the DOM somewhere?
What is #addDriverPopup made of?
it's possible that the problem is that the ids are conflicting. Because you are cloning, you end up with multiple ids with the same value.
There could just be some sort of conflict as a result. May want to consider classes.
per my comment below:
$jq.ajax({
url: 'show',
dataType: 'json',
data: {driverId: driverId},
success: function( data ) {
$("#id").val(data.id);
$("#firstName").val(data.firstName);
$("#lastName").val(data.lastName);
$("#personalId").val(data.personalId);
$("#phoneNumber").val(data.phoneNumber);
$jq('#addDriverPopup').dialog({
close: function(){
//Do stuff here to clean up, this syntax may be a bi
}
});
},
error: function(xhr, error) {
alert(error);
unblockUI();
}
});
As pointed in the question comments by #rcdmk, it seems that it is a platform issue.
I had to refactor the code to return the ready-for-editing form to the client instead of json. Solution is less elegant, but cross-platform :)