I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.
Related
Im making some web appication which loads pages without refresching te page. This all works great but now i have a form on one of these pages. I want to submit the form without the page to refresh. But when i submit the form after i loaded it with ajax the url in the browser will change from
localhost/documents/projects/test/
to
localhost.documents/projects/test/?form_type=register&Username=&first_name=&surname_prefix=&surname=&surname=&email=
When i just put the form html in my index.php and submit it there it works fine.
I hope someone can tell me what im doing wrong and how to fix it.
part of index.php
<div class="message"></div>
<div id="content">
<div id="page">
<div class="form_container">
<form id="form">
<input type="hidden" name="form_type" value="register" />
<input class="type_text" type="text" name="username" maxlength="20" placeholder="username" />
<input class="type_text" type="text" name="first_name" maxlength="50" placeholder="First Name" />
<input class="type_text" type="text" name="surname_prefix" maxlength="20" placeholder="Surname Prefix" />
<input class="type_text" type="text" name="surname" maxlength="50" placeholder="Surname" />
<label class="label" for="birth_date">dd-mm-jjjj</label>
<input id="birth_date" class="type_text" type="text" name="birth_date" maxlength="10" placeholder="Birth Date" />
<input class="type_text" type="text" name="email" placeholder="Email Address" />
<input class="type_submit" type="submit" value="Register" />
</form>
</div>
</div>
pageHandler.js
$(document).ready(function() {
var request;
//page handler
//pageRequest('home');
$('.click').click(function(event) {
var temp = $(this).attr('id');
var pages = ['home','register'];
if($.inArray(temp, pages) !== -1) {
pageRequest(temp);
//$('.message').html(temp);
}
event.preventDefault();
});
function pageRequest(temp) {
var page = $('#page');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
type: "POST",
url: "core/posts.php",
data: 'temp=' + temp
});
request.done(function(data) {
page.fadeOut(function() {
page.html('');
page.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
page.fadeOut(function() {
page.html('');
page.html(textStatus).fadeIn();
});
});
}
//form handler
$('#page').delegate( "#form", "submit", function(event) {
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
formRequest(serializedData);
event.preventDefault();
});
function formRequest(values) {
var message = $('.message');
if(typeof ajax_request !== 'undefined') {
request.abort();
}
request = $.ajax({
url: "core/posts.php",
type: "POST",
data: values
});
request.done(function(data) {
message.fadeOut(function() {
message.html('');
message.html(data).fadeIn();
});
});
request.fail(function(jqXHR, textStatus) {
message.fadeOut(function() {
message.html('');
message.html(textStatus).fadeIn();
});
});
}
});
posts.php
If(isset($_POST['temp'])) {
$temp = $_POST['temp'];
$url = '../content/templates/'.$temp.'.html';
if(file_exists($url)) {
$html = file_get_contents($url);
echo $html;
}
else {
echo 'Sorry, couldn\'t find the page.';
}
}
//form handler
if(isset($_POST['form_type'])) {
require_once('../admin/config/database.functions.php');
$function = new myDBFunctions();
switch($_POST['form_type']) {
case 'register' :
$username = $_POST['username'];
$firstname = $_POST['first_name'];
$surnamep = $_POST['surname_prefix'];
$surname = $_POST['surname'];
$birthdate = $_POST['birth_date'];
$email = $_POST['email'];
echo 'Thanks for your registration';
break;
case 'login' :
echo 'login';
break;
case 'password_recovery' :
echo 'password recovery';
break;
}
}
I have found the problem but not why it occured. I had a $_POST['username'] in my posts.php file while the the name of the html input field was Username. I have changed this and now the url in the browser doesn't change anymore. I'm happy I've found the problem but i still dont get why the data send by ajax would appair in the url.
"I want to submit the form without the page to refresh"
There are a few ways to do this, I think the easiest is to intercept and stop the form from actually submitting like a regular HTML form and instead make an ajax call with the data in the form fields.
To do this, you will need to intercept the submit event of the form, get the values of all the inputs in the form and make an ajax call with the data to the server:
<form id="myForm">
....
</form>
<script>
$('#form').on("submit", function(event) {
// stop the form from submitting
event.preventDefault();
// get data in the inputs of the form
var data = {};
var $inputs = $('#form').children("input, select, textarea");
inputs.each(function($element){
data[$element.attr('name')] = $element.val();
});
// submit data to the backend
request = $.ajax({
type: "POST",
url: "",
data: data
});
});
</scipt>
EDIT:
This was related to a typo elsewhere in my Javascript. I had forgotten to check the Javascript console. Thank you for your comments.
This is my first post on this site. I have been reading it for a long while though.
I am working on a login form utilizing jQuery, AJAX, and PHP. Several times now I have run into the problem where I am redirected to the PHP page where I see the echoed data I wanted returned. I have tried to figure this out but I am stuck.
EDIT:
I did include jQuery:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
HTML:
<form name="login" id="loginForm" action="login.php" method="post">
<label for="usernameInput">Username: </label>
<input type="text" name="usernameInput" id="usernameInput" placeholder="Username" autofocus required>
<label for="passwordInput">Password: </label>
<input type="password" name="passwordInput" placeholder="Password" required>
<input type="submit" name="loginSubmit" value="Log In">
</form>
jQuery:
function login () {
$('#loginForm').on('submit', function(e){
e.preventDefault();
var formObject = $(this);
var formURL = formObject.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: formObject.serialize(),
dataType: 'json',
success: function(data)
{
$("#loginDiv").remove();
if(data.new) {
$("#setupDiv").show();
} else {
statusUpdate();
/* EDIT: Changed from dummy text 'continue()' */
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#loginDiv").append(textStatus);
}
});
});
}
Call:
$(document).ready(function() {
login();
});
PHP:
// Main
if (isset($_POST['usernameInput'], $_POST['passwordInput']))
{
require "hero.php";
// Starts SQL connection
$sql = getConnected();
$userArray = validateUser($sql);
if ( $userArray['id'] > 0 ) {
sessionSet($userArray);
$userArray['user'] = (array) unserialize($userArray['user']);
$userArray = json_encode($userArray);
echo $userArray;
exit();
}
else
{
echo 'Username does not exist';
}
}
else
{
echo "Please enter a username and password.";
}
I know I have not included everything, but here's the output:
{"id":"11","name":"st5ph5n","new":true,"user":[false]}
So everything up to $userArray is working as expected. Why is this not staying on index.html and instead redirecting to login.php?
Thank you for any responses.
I am Submiting form through MOUSE CLICK and ENTER too.
Ajax Call is checking is there any designation which i already in DATABASE.. If not, user can submit form otherwise SUBMIT button will DISABLE
JQUERY
function check_designation(e){
text = $('#req1').val();
data = "data=" + text;
text_length = text.length
if(text_length == 0)
{
$('#result_span').html('');
}
if(text_length > 3 ){
$.ajax({
url: "designation_ajax.php",
type: "POST",
data: data,
cache: false,
success: function (response) {
if ($.trim(response) == "access") {
$("#result_span").html('<div class="green">' + text + ' is available '+'</div>');
$('#create_desg').removeAttr('disabled');
}
else if ($.trim(response) == "no access") {
$("#result_span").html('<div class="red">' + text + ' is already in use'+'</div>');
$('#create_desg').attr('disabled','disabled');
}
else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
}
else{
$("#result_span").html('');
}
return true;
}
HTML FORM
<form id="formID" class="formular" method="POST" action="" onsubmit="formSubmit()" >
<fieldset>
<legend>Create Desination</legend>
<label> Designation<br clear="all" />
<input autocomplete="off" onkeyup="check_designation(event)" value="" class="validate[required,minSize[4]] text-input float_left" type="text" name="name" id="req1" />
<span id="result_span"></span>
</label>
<br clear="all" />
<input id="create_desg" value="Submit" type="button" />
</fieldset>
</form>
PROBLEM::::
Now what happen DISABLE button is not a solution... if there is already a DESIGNATION in a table.. submit button will disable but By ENTER it will submitted and i dont want to reload the page. and AJAX is not working when i PRESS ENTER
You must return false from your onsubmit handler in order to cancel the default action. But I would probably clean your code a bit and subscribe to the submit event unobtrusively:
<form id="formID" class="formular" method="POST" action="">
<fieldset>
<legend>Create Desination</legend>
<label>
Designation<br clear="all" />
<input autocomplete="off" value="" class="validate[required,minSize[4]] text-input float_left" type="text" name="name" id="req1" />
<span id="result_span"></span>
</label>
<br clear="all" />
<input id="create_desg" value="Submit" type="button" />
</fieldset>
</form>
You will notice that I have intentionally removed the onkeyup event from the input field. Hammering your server with AJAX requests every time some user hits a key while inside this field won't do any good to your server. If you want to implement this I would recommend you waiting for some input to accumulate and throttle before sending the AJAX request.
and then:
$(function() {
$('#formID').submit(function() {
var text = $('#req1').val();
if(text.length == 0) {
$('#result_span').html('');
}
if(text.length > 3) {
$.ajax({
url: 'designation_ajax.php',
type: 'POST',
data: { data: text },
cache: false,
success: function (response) {
if ($.trim(response) == 'access') {
$('#result_span').html('<div class="green">' + text + ' is available '+'</div>');
$('#create_desg').removeAttr('disabled');
}
else if ($.trim(response) == 'no access') {
$("#result_span").html('<div class="red">' + text + ' is already in use'+'</div>');
$('#create_desg').attr('disabled', 'disabled');
} else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
} else {
$('#result_span').html('');
}
// return false to prevent the default action
return false;
});
});
Also I would have the designation_ajax.php script return JSON instead of some access and no access strings that you are parsing and trimming in your success callback.
I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>
I have a feedback form in a pop-up div that otherwise works fine but processes SQL twice when the form results in error at first instance.
This is the html form:
<div id="stylized" class="myform">
<form id="form" method="post" name="form">
<p>Report:
<select id="fbtype" name="fbtype">
<option>Bug</option>
<option>Suggestion</option>
<option>Discontentment</option>
<option>Appreciation</option>
</select>
</p>
<p>Brief description:
<textarea name="comments" id="comments" cols="45" rows="10"></textarea>
</p>
<span class="error" style="display:none">Please describe your feedback.</span>
<span class="success" style="display:none">We would like to thank you for your valuable input.</span>
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
</form>
</div>
The feedback_form_submit() function is:
function feedback_form_submit() {
$(function() {
$(".submit").click(function() {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
}
And the processfeedback.php has:
include "./include/session_check.php";
include_once "./include/connect_to_mysql.php";
if (isset($_POST['fbtype'])){
$userid =$_SESSION['id'];
$fbtype=$_POST['fbtype'];
$comments=$_POST['comments'];
$sql = mysql_query("INSERT INTO feedback (userid, type, comments)
VALUES('$userid','$fbtype','$comments')") or die (mysql_error());
}
Could anyone figure out why does the form submits twice? And any suggestion to control this behaviour?
If this is actually the code you're using, you seem to have wrapped your onclick function around the $.click event-adding function:
function feedback_form_submit() {
$(function() {
// This adds a click handler each time you run feedback_form_submit():
$(".submit").click(function() {
// ... //
return false;
});
});
}
When I tried this on jsFiddle.net, I clicked Submit the first time and nothing happened, then the second time it posted twice, the third click posted three times, etc.
You should just keep it simple: take out the onclick attribute:
<input type="button" value="Submit" class="submit" />
and remove the feedback_form_submit() wrapper:
$(function() {
$(".submit").click(function() {
// ... //
return false;
});
});
This way the $.click handler function will be applied just once, when the page loads, and will only run once when Submit is clicked.
EDIT:
If your form is loaded via AJAX in a popup DIV, you have two options:
Keep your onclick but remove the $.click wrapper instead:
function feedback_form_submit() {
// ... //
}
and
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()" />
Note that you only need to return false if you're using <input type="submit" ... >; when using <input type="button" ... >, the browser does not watch the return value of onclick to determine whether to post the form or not. (The return value may affect event propagation of the click, however ...).
Alternatively, you can use jQuery's $.live function:
$(function() {
$('.submit').live('click',function() {
// ... //
});
});
and
<input type="button" value="Submit" class="submit" />
This has the effect of watching for new DOM elements as they are added dynamically; in your case, new class="submit" elements.
Your feedback_form_submit function doesn't return false and on submit click you're also posting to the server. There is no need to have onClick in:
<input type="button" value="Submit" class="submit" onclick="feedback_form_submit()"/>
Change that to:
<input type="button" value="Submit" class="submit"/>
And change your code to:
// Update: Since you're loading via AJAX, bind it in the success function of the
// AJAX request.
// Let's make a function that handles what should happen when the popup div is rendered
function renderPopupDiv() {
// Bind a handler to submit's click event
$(".submit").click(function(event) {
var fbtype = $("#fbtype").val();
var comments = $("#comments").val();
var dataString = 'fbtype='+ fbtype + '&comments=' + comments;
if(fbtype=='' || comments=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "processfeedback.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
// This is the success function for the AJAX request that loads the popup div
success: function() {
...
// Run our "onRender" function
renderPopupDiv();
}