How would you design this webpage with multiple forms? - javascript

I currently have a simple php/html page with only one form, where the user inputs a number, then the page loads itself (but this time with parameters).
Some key codelines :
<form action="index.php" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (!isset ($_GET["name"])) {
echo "<div> Adding some content related to the input </div>";
}
?>
Now i'm looking forward adding 3 more fields, and split my page for each form.
The user should be free to use the 4 forms separately, I don't want to have the page reload every time. I'm unsure how to design this page - should i rework my page and work with JS ?
I have basic knowledge with PHP, a little with JS. I will be able to google up most things i need but first i need a proper direction :) thanks !

you can use AJAX for this purpose...
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});

AJAX is a must if you don't want the page to reload between each interaction.
If you have trouble with it and want to opt for just PHP (with page reloads) you can handle multiple forms on one page easily enough - my preferred method is to set a hidden value in the form called 'action' settings its value & reading this in again when the page loads for example:
<?php if(isset($_POST['action']))
{
$action = $_POST['action'];
switch ($action)
{
case 'hello':
echo 'hello';
break;
case 'bye':
echo 'bye';
break;
}
}
?>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>
</form>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>
</form>
You could then save and echo out the values for each form each time keeping them updated as the user interacts with each of the forms.
AJAX is the nicer solution however

If you do not want to reload the page every time you submit each form then you should use Ajax for calling your api. You write the separate api in PHP, and then call that api in Jquery's Ajax.
Here the page won't be reloaded. Also you can call the ajax on each of the button click.

Related

How to stay on the same page after POST action is called in PHP [duplicate]

This question already has an answer here:
Understanding HTML Form Element behavior
(1 answer)
Closed 1 year ago.
I have a simple online form that calls a PHP script on submit.
<form name="newform" id="regForm" action="../includes/submit.inc.php" method="post">
When the submit button is clicked the site URL in the browser changes to http://example.com/includes/submit.inc.php and the page is blank.
I want to display a Thank you message after form is submitted and I want the URL to remain http://example.com
I've tried using JS to hide the main container of my website and enabling a DIV with the thank you message.
function submit() {
document.getElementById("main").style.display = "none";
document.getElementById("success").style.display = "inline";
}
document.getElementById('regForm').onsubmit = function () {
var terms = document.getElementById('consentBox');
if (!terms.checked) {
showWarnings(warnings);
return false;
}
submit();
return true;
};
This kind of works I can see the thank you message for a split second but then the browser goes to http://example.com/includes/submit.inc.php and the page is blank. I really want to avoid redirecting to another .php file. I know I could do something like this:
header( "location: ../success.php", true, 301 );
But prefer to display the message on the same page. How can I achieve this?
Thanks in advance.
You can add post php code in the same page where you written the main code.
For example-
<form name="newform" id="regForm" action="inex.php" method="post">
<?php
//and your php post code here
?>
This can achieved through the use of AJAX and the serialization of the form. This is written with the assumption that the php script returns a status message (html block looking to be displayed) upon successful completion. This can also be helpful for error handling, in the event there is an issue within the php script. This example makes use of the jQuery library.
<form name="myForm" id="myForm">
<input type="text" name="input1">
<input type="text" name="input2">
</form>
// Using jQuery
$('#myForm').submit(function(e) {
//Prevent Default
e.preventDefault();
// Gather Form Values into Array
var values = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
values[kv.name] = kv.value;
});
$.ajax({
method: "POST",
url: "pathToFile/formHandlingFile.php",
dataType: "html",
data: {
vals: values
}
})
.done(function(data) {
$('#main').hide()
$('#success').html(data)
$('#success').show()
})
});

Getting data from HTML form, and from Javascript array upon form submission

I'm stuck.
I have a regular HTML form that submits to itself.
<form action="<?php print $phpSelf;?>" method="post" id="PO">
<input>...</>
<input>...</>
<input>...</>
<input type="submit" id="btnCreate" name="btnCreate" value="Create" tabindex="900" class="button">
</form>
And I have an array in Javascript, I'll call it
var jArray;
I need to get the information from the form, and the information from the Javascript array. I can get each of them separately, but I don't know how to get them at the same time.
For the Javascript, this is the method I am using.
function submitPO(){
$.ajax({
type:"post",
url: "jsTo.php", //Send the variable to this page
data:{partsToAdd: jArray}, //{variable name (POST), data to be passed}
cache:false,
success: function(html){ //Function to execute when successful
console.log("Success in the function");
$('p#msg').html(html);
}
});
return false
}; //End of SubmitPO
<p id = "msg"></p>
<form>
<input type="submit" value = "submit" onclick = "return submitPO();">
</form>
When I press the button, it sends the array to jsTo.php where I can get it.
$selectedParts = $_POST['partsToAdd'];
That works fine. I use a similar method for getting the information from the HTML form.
$To = htmlentities($_POST["To"], ENT_QUOTES, "UTF-8");
So, like I mentioned above, I can get either the data from the javascript array, or the data from the form, but not both. Anyone able to help me figure this out? I've looked all over SO, and have found tons of resources on how to submit multiple forms with one button, how to post from JS to PHP, etc., but nothing that has touched on this issue.
You can get the data from the form with .serialize then you can add it to the array data with $.param
data:$.param({partsToAdd: jArray})+'&'+$('#PO').serialize(),
You can just serialized your form.
in your ajax data, just do
data: $('form').serialize()

Getting an Ajax response from a form.submit() to PHP

I'm trying to combine a form.submit() call with a jquery/ajax call to get a response from my php login script - I've just spent a few hours trying to hack together some of the hundreds of posts/examples on a similar topic but am out of ideas now so am hoping someone can help.
My sign in form looks like this...
<form id ="signInForm" action= "/userManagement/proxy_process_login.php" method="post" name="login_form">
<input required id="signInUserId" name="email" type="text" placeholder="Username/Email" class="input-medium">
<input required id="signInPassword" name="password" type="password" placeholder="Password" class="input-medium">
<button id="signin" name="signin" class="btn btn-success" onclick="signInSubmit(this.form, this.form.signInPassword);">Sign In</button>
</form>
The function signInSubmit() (called by the button's onclick) simply validates the text fields, and replaces the plain text password with a hashed version before finally calling "form.submit()", like this...
//ommited a bunch of text input validation
var p = document.createElement("input");
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
password.value = ""; // Make sure the plaintext password doesn't get sent.
form.submit();
My PHP script (proxy_process_login) also works fine before adding any jquery/ajax and essentially does this...
if (login($email, $password, $mysqli) == true) {
// Login success (ok to reload existing page)
header("Location: ../index.php?login=success");
exit();
} else {
// Login failed (do NOT want to reload page - just message "fail" back via AJAX so I can update page accordingly)
echo "fail";
exit();
}
But given the route I'm taking to submit the form, I'm struggling to incorporate an Ajax example - because I've got this new "form" variable (with the hashed p variable appended), so I can't use an Ajax call which refers back to the form using jquery like this...
$.ajax({type:'POST', url: '/userManagement/proxy_process_login.php', data:$('#signInForm').serialize(), success: function(response) {
console.log(response);
}});
(because the jquery reference doesn't include the new variable, and I've already specified the php script in the action attribute of my form)
And I also can't call something like "serialize()" on my "form" variable inside signInSubmit().
Any ideas on an appropriate way to structure a solution to this?! Thanks!
Unfortunately there is no callback for native form submission using action attribute , it was used in the past to redirect you to that page and show the results there.
Modern method now is to use ajax call , after perventingthe default submission.
Solution:
HTML:
<form id="myForm">
<!-- form body here --!>
</form>
Javascript:
$("#myForm").submit(function(e){
e.preventDefault();//prevent default submission event.
//validate your form.
//disable your form for preventing duplicate submissions.
//call you ajax here.
//upon ajax success reset your form , show user a success message.
//upon failure you can keep your fields filled , show user error message.
})
this is a typical algorithm i use in any project i do , i recommend using parsley JS for front-end validation.

No Javascript Fallback for AJAX Form submission

I am new to AJAX and am in the process of converting some regular HTML forms to AJAX.
My existing implementation is as follows - form (on page1.php) posts to page2.php which does some validation on post data and redirects to an error page if something is missing. If the input is fine, it includes page3.php which processes the request and redirects back to page1.php.
php/page1.php
<form method="post" action="/php/page2.php" >
<input type="text" name="input1" placeholder="Howdy..." />
<input type="text" name="input2" placeholder="Howdy..." />
<input type="submit" value="Submit" />
</form>
php/page2.php
<?php
// perform some validation on inputs
if (empty($_POST['input1']))
{
$location ='Location: /php/error.php';
header($location);
exit;
}
// Inputs are fine
include('/php/page3.php');
?>
page3.php
<?php
// do some form processing
// redirect back to page1.php
$location = 'Location: /php/page1.php";
header($location);
exit;
?>
To convert to AJAX, I am using #SSL's solution on this SO link How to show loading gif when request goes Ajax
http://jsfiddle.net/clickthelink/Uwcuz/1/
The error from validation and success page are both displayed back on page1.php via the callback function.
php/page2.php
<?php
// perform some validation on inputs
if (empty($_POST['input1']))
{
// Echo erorr code isntead of redirect
echo "Please enter input1";
return;
//$location ='Location: /php/error.php';
//header($location);
//exit;
}
// Inputs are fine
include('/php/page3.php');
?>
page3.php
<?php
// do some form processing
// Echo success instead of redirect
echo "SUCCESS";
// redirect back to page1.php
//$location = 'Location: /php/page1.php";
//header($location);
//exit;
?>
This part is working fine.
My question (finally) is how do I handle users who have javascript disabled? I know the form will get submitted appropriately but I wont get the redirect back in case of the error or success. I would like to retain header() redirect type of functionality in this case also. Is this possible? I would appreciate the help.
You want to detect if this is an xhr request, and default to the non-ajax behavior if it is not.
I would look at $_SERVER['HTTP_X_REQUESTED_WITH']
Keep your current form setup as-is, if it is working for you without javascript.
For javascript enabled browsers you can hijack the 'submit' event on the form. Capture the event and post the form, via ajax, to scripts/pages that handle and return the data in a javascript-friendly format for final consumption.
For example, using jquery:
<form method="post" action="/php/page2.php" id="js-form" >
<input type="text" name="input1" placeholder="Howdy..." />
<input type="text" name="input2" placeholder="Howdy..." />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function(){
$('#js-form').on('submit',function(e){
// logic to submit ajax form and handle response
// return false to cancel native browser form submission.
return false;
});
});
</script>
Another idea is to keep the pages you already have, but send a flag with the ajax request to disable the browser redirect headers. For example, add 'src=ajax' when submitting the form via ajax. Then in the script use logic to say:
<?php
if( !empty($_REQUEST['src'] && $_REQUEST['src'] == 'ajax' ) {
// add redirect logic here.
}
?>

How do I process forms (front and back end) on the same page?

I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.

Categories

Resources