I am building a web application, I am having lots of confusion when ever I use POST method.
Lets say I have the below code
<?php
$abc = 'abc';
if(some condition){
$abc = 'xyz';
}
if(isset($_POST['submit'])){
header("Location:http://someexample.php/$abc");
die();
}
?>
<form method="POST">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
so as per my understanding, If I am not wrong.
When I click the SUBMIT / CLEAR button. The PHP file reloads the self page first before redirecting it to the header location.
If I am right. Is there any other way to avoid multiple redirects when we are working on big PHP files. When I have multiple SUBMIT button.
thank you in advance
You are basically redirecting your request to another page. Instead of redirecting the page using header you should use the action attribute of the form.
<form method="POST" action="yourexample.php" id="myForm">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
the form will redirect you to the second page. If you do not want to reload your page at all you should use ajax. You can use jquery and post your values to another page buy creating a function. In this case your form tag should not have the action attribute or you
should use preventDefault method.
$("#myForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
url will be the name of the page to which you want to redirect the user.
The data will be your form. You can use the .serialize() method to get your form data.
var data = $("myForm").serialize();
In success you can define a function on what to do in case of successful result.
Nothing wrong with multiple redirects: this is how traditional web works.
You may get reduce the number of redirects by using AJAX calls though.
Some notes on your pseudo-code:
it is quite useless to echo anything before Location header: noone is supposed to read the message. Not to mention that no output is allowed before headers.
http:// in front of address allowed only in case of fully qualified URI.
so, the code actually have to be
<?php
if(isset($_POST['submit'])){
header("Location: someexample.php");
die();
}
?>
Forms always post to the "action" attribute in it. If you don't want it to post to self, put your form opening tag as <form action="someexample.php" method="post">. The result will be the POST data being sent to someexample.php instead of to the same page as the form.
If you're looking into multiple form options on one page without redirect, take a look into AJAX submits.
The idea would be to send over the form to your receiving file, process the POST data, and return whatever you wanted returned from that process. For example:
$("form").submit( function(event) {
event.preventDefault(); //prevent the file submitting
var formData = $(this).serialize(); //process the form into an array for submission
$.ajax({
url: "receiver.php", //the url of the receiving file
type: "post", //setting method to post
data: formData, //set the data being sent to the form contents
success: function(response) {
$("div").html(response); //set the receiving div to the html you echo'd in the php document
}
});
});
Your receiver.php file can look exactly the same as a normal PHP document receiving POST data, so <?php if(isset($_POST['submit'])) {} ?> will still work exactly as you're expecting, without the page redirects! This solution does require jQuery though.
Edit:
To deal with the questions update of if(criteria) { $abc = 'xyz'; } there are a couple of suggestions.
To keep the asynchronous approach, go with $_SESSION variables. You could set them using the receiver.php and deal with them in the starting document.
To go back to a standard submission method onto the same document, either break your multiple options into radio inputs, checkboxes, or separate forms.
So:
<input type="radio" name="method" value="submit" />
<input type="radio" name="method" value="clear" />
That way you can choose what method to submit there.
Or you can break them into forms:
<form method="post">
<input type="submit" name="submit" value="submit" />
</form>
<form method="post">
<input type="submit" name="clear" value="clear" />
</form>
Finally, you could change the value of a hidden input on click if you wanted to change between submit and clear, so:
The HTML:
<form method="post">
<input type="hidden" id="method" name="method" value="" />
<input type="submit" id="submit" value="submit" name="submit" />
<input type="submit" id="clear" value="clear" name="clear" />
</form>
The jQuery:
$("#submit").click( function(event) {
event.preventDefault();
$("#method").val("clear"); //set the method to clear
$("form").submit(); //submit the form normally
});
$("#clear").click( function(event) {
event.preventDefault();
$("#method").val("submit");
$("form").submit();
});
The PHP:
<?php
if(isset($_POST['submit'])) {
//do something
} elseif(isset($_POST['clear'])) {
//do something else
}
Related
I have a PHP page (page.php) that I am using to post data into my database. I am using the form method post to send the data to my database. Inside the <form> I have a second <form> which I use to upload an image.
But when I click on Upload the outer <form> will posted: action="./submit.php".
Does someone know how I can fix this?
Here is my script:
page.php
<form name="reaction" method="post" action="./submit.php">
//multiple textboxes
//upload script
<form name="newad" method="post" enctype="multipart/form-data" action="page.php">
<table style="width:100%">
<tr><td><input type="file" name="image" value="Choose file"></td></tr>
<tr><td><br /><input name="Submit" class="btn2" type="submit" value="Upload"></td></tr>
</table>
</form>
<button type="submit">Post page</button>
</form>
well Ryan is right, you can't have a <form> inside a <form> my suggestion is change the html stucture or make it into one <form> with one action and maybe you can split the function inside submit.php
You can't have nested form like this in HTML.Follow this instruction to better undrestanding about form handling in PHP.
You can use two submit buttons in one form, they can each have a different formaction to specify where to submit.
<form name="reaction" method="post" enctype="multipart/form-data">
//multiple textboxes
//upload script
<table style="width:100%">
<tr><td><input type="file" name="image" value="Choose file"></td></tr>
<tr><td><br /><input name="Submit" class="btn2" type="submit" value="Upload" formaction="page.php"></td></tr>
</table>
<button type="submit" formaction="submit.php">Post page</button>
</form>
Both buttons will submit all the form fields, but the two scripts can simply ignore the fields that they don't care about.
Recommendations:
Step 1: separate each form
Step 2: give each form an id
Step 3: use jquery's $.ajax() to publish the forms to their respective targets URLs
Example of Ajax call:
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
Code from hog I was lazy to write one
I was looking for answer for my question but I didn't found solution. Here is similar topic link but I have different code and I don't know how to fit answer from this topic to my code.
Here is my problem. I'm sending my form with id order_form to test.php.
Every form value is sending proper except input submit. My script is based on checking that <input id="sendform" type="submit" value="ORDER PRODUCT" name="sendform"/> is send.
Below is code that I use to send form.
$("#order_form").submit(function() {
$.ajax({
type: "POST",
url: "includes/test.php",
data: $("#order_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
And here is content of test.php
echo '<pre>';
print_r($_POST);
echo '</pre>';
Here is examle form because my form is extremaly big.
<form id="order_form">
<input type="text" name="w2b" value="abc"/>
<input id="sendform" type="submit" value="ZAMAWIAM" name="sendform"/>
</form>
In HTML5 forms when you are passing through parameters and variables to the ajax functions the value data from "Submit Inputs" isn't passed through. So if you have a form set up as :
<form>
<input type="text" name="foo" value="bar">
<input type="submit" name="submitTest" value="Hello World!">
</form>
The value of "submitTest" isn't being sent through. The only thing that gets sent through is the parameter "foo" with the value of "bar". "submitTest" only submits the form and executes your ajax call in this case.
To fix this just add a hidden element in the form.
Now it would look this
<form>
<input type="text" name="foo" value="bar">
<input type="hidden" name="sendform" value="ZAMAWIAM">
<input type="submit" name="submitTest" value="Hello World!">
</form>
This will send through the value to your ajax call and you can use it for whatever you might need it for.
Make sure you wrap your jquery code in
$(function(){
//code here
});
Again Dont forget to prevent Default Event , Below is a rewrite of your jquery code
$(function(){
$("#order_form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/test.php",
data: $("#order_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});//end ajax
});//end on submit
});//end jquery
<form name="ipladder" id="ipladder" action="/checkuser/master-check.php" method="post">
<input name="ipladder" type="text" id="ipladder" />
<input type="submit" name="submit" id="botton" value="Check" />
<input type="submit" name="geo" id="botton"/>
</input></form>
I have one input box and 2 submit buttons. When the first button is pressed (name="submit") I want it to go to master-check.php as specified in the action= parameter. However when the geo button is pressed, I want it to go through a different action which I haven't specified because I didn't know how to do so.
What can I do so I can have 1 input box and 2 buttons each processing through different action files?
Maybe you can try altering the "action" parameter of your form in an onclick method that, after changing, submits the form. Something like:
$('#btn1').click(function(){
$('#ipladder').attr('action', 'location1.php');
$('#ipladder').submit();
});
$('#btn2').click(function(){
$('#ipladder').attr('action', 'location2.php');
$('#ipladder').submit();
});
Another option of couse, is to post to 1 page...and handle the logic (some redirect or whatever) there.
Make a single PHP script that handles which button has been pressed and then redirects to correct PHP handling script (after correcting what Juhana commented of course).
Instead of using form action, I think you can use Ajax to achieve what you want. It will be something like this:
<form name="ipladder" id="ipladder" method="post">
<input type="text" id="ipladder2" name="ipladder2" />
<input type="button" id="button1" name="submit" value="Check" onclick="action1()" />
<input type="button" id="button2" name="geo" value="Something else" onclick="action2()" />
</form>
and in the header you can define 2 Ajax functions:
<script type="text/javascript">
function action1()
{
$.ajax({
type: "POST",
url: "/checkuser/master-check.php",
data: $("ipladder2").val(),
success: //do something,
dataType: //return dataType
});
}
function action2()
{
$.ajax({
type: "POST",
url: //other URL,
data: $("ipladder2").val(),
success: //do something else,
dataType: //return dataType
});
}
</script>
Well you can achieve your goal by single php page as well.
on mastercheck.php something like this can help you.
<?php
if($_POST['submit'])
{
//you code for master-check.php
}
else if(isset($_POST['geo']))
{
//you code for other page goes here
}
?>
I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:
Here is my jQuery:
<script type="text/javascript">
function processForm() {
var action= $('#action').val();
var data = $('#data').val();
var dataString = 'action=' + action + '&data=' + data;
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
}
</script>
Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)
<form action="" method="post" onsubmit="processForm();return false;">
<input type="hidden" name="action" value="action1" />
<input type="text" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Here is my PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!
SOLUTION (via Jen):
jQuery:
<script type="text/javascript">
function processForm() {
var dataString = $("#yourForm").serialize();
$.ajax ({
type: 'POST',
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
</script>
HTML:
<form id="yourForm">
<input type="hidden" name="action" value="action1" />
<input type="text" id="data" name="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
What I learned: Use the .serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and .serialize() does not typically make mistakes sending the info to php.
Give this a try:
$("#yourForm").submit(function(){
// Could use just this line and not vars below
//dataString = $("#yourForm").serialize();
// vars are being set by selecting inputs by id but id not set in form fields
var action= $('#action').val(); // value of id='action'
var data = $('#data').val(); // value of id='data'
var dataString = 'action=' + action + '&data=' + data;
// dataString = 'action=&data=' so nothing is posted to db
// because input fields cannot be found by id
// fix by adding id fields to form fields
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
And change the form to (I added the id attributes):
<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:
When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="", which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.
When you put return false; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET) to a processing file, not '.'
Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.
Hope this small hint helps (:
My problem:
I have index.html:
<form action="toload.php" method="post">
Input: <input type="text" name="something" value="" /><br />
<input type="submit" value="Submit!" />
</form>
toload.php is something like:
<?php
echo "Your input was: " . $_POST["something"];
?>
The question is quite simple.
When I press the Submit! button, I would like to dynamically load the content toload.php in index.html without the need of a refresh.
Thanks in advance! please comment for any needed clarification.
EDIT, a more verbose explanation:
I'm not sure I'm being clear (or maybe I'm not understanding the answers do to my lack of technical skills) so I'll give it another go. (re-write)
I have an HTML for with a submit button that sends a variable through POST method.
This variable is used by a PHP file and after a certain process, it inserts and update a MySQL database and echoes out some other stuff.
This is working JUST FINE.
But now I want to improve it by avoiding the page "reload" (going to the .php).
I want the HTHL that comes as an output of my HTML file to be dynamically shown in my HTML page.
Is it more clear now?
something like this with jQuery!:
<form action="toload.php" method="post">
Input: <input type="text" id="something" name="something" value="" /><br />
<input type="submit" value="Submit!" onclick="submitme()" />
<div id="something2"></div>
</form>
and function to submit:
function submitme(){
var tosend=document.getElementById("something").value;
$.ajax({
type: 'POST',
url: 'toload.php',
data: 'something='+tosend,
success: function(msg){
if(msg){
document.getElementById("something2").innerHTML=msg;
}
else{
return;
}
}
});
}
You must use AJAX (XMLHttpRequest) for that - http://www.w3schools.com/XML/xml_http.asp.
(You've said simply - as long loading 100KB of jQuery is not simply IMHO, I suggested pure JavaScript solution)
In your case you can use $.post()DOCS. If you gave your form an id="myForm" then you could load the return data into the form's parent in the callback as follows:
$('#myForm').submit(function(e){
e.preventDefault();
$.post("toload.php", $("#myForm").serialize(), function(data) {
$(this).parent().html(data);
});
});