Wrong post on submit - php

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

Related

Ajax image upload failure, Script doesn't get the php isset function

I've been following along with some ajax uploading tutorial and it was working properly.
Here it's how i done,
i created a form in html like this.
<form id="submit_form" action="php-script/test_lates_statusbx-script.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Select Image</label>
<input type="file" name="ui-is-status_is_photo_fl" id="image_file" />
<textarea name="status_is_text_ara"></textarea>
<span class="help-block">Allowed File Type - jpg, jpeg, png, gif</span>
</div>
<input type="submit" name="is_status_forum_btn" class="btn btn-info" value="Upload" />
</form>
<div id="image_preview">
</div>
and here its my ajax code,
$(document).ready(function(){
$('#submit_form').on('submit', function(e){
e.preventDefault();
$.ajax({
url:"php-script/test_lates_statusbx-script.php",
method:"POST",
data:new FormData(this),
contentType:false,
//cache:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
$('#image_file').val('');
}
})
});
});
and my php looks like this,
if(isset($_POST['is_status_forum_btn'])){
echo $fileactuname = basename($_FILES['ui-is-status_is_photo_fl']['name']);
echo $textareastatus = htmlspecialchars($_POST['status_is_text_ara']);
}
Problem: When i click the submit buttons it doesnt execute my code. But if i echo something outside of the isset function will does.Where am i wrong ?
A submit button is only a successful control if it is used to submit the form.
You are:
Using the submit button to submit the form
Preventing the default behaviour of the submit event so the form is not submitted
Collecting the data from the form with JavaScript
Making an HTTP request with that data
Since (due to step 2) the submit button is no longer being used to submit the form, it isn't included in the object you create with FormData().
Test for the presence of a different piece of data that you are sending.
e.g.
if(isset($_FILES['ui-is-status_is_photo_fl']))
In your php script, try like this
if (
isset($_FILES['ui-is-status_is_photo_fl']['name']) &&
$_FILES['ui-is-status_is_photo_fl']['error'] == 0
) {
print_r($_FILES);
print_r($_POST);
// Do the required task here
} else {
echo "error";
}

Multiple different forms in one ajax php page

Due to language limitations I might not understood how to ask Google about what I want to accomplish, but I hope you will understand.
I have three forms which i want to show on the same page without refresh. First form submits action to php which determines which function (with yet another form) to show. But buttons interfere and I am nowhere near what I wanted to do.
Index.php is supposed to send user input to calculator.php which then opens next form depending on value:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
<div id="parseSecondForm"></div>
<script type="text/javascript">
$(function(){
$('#form1').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('formaction'),
data: $(this).serialize(),
beforeSend: function(){
$('#parseSecondForm').html('<img src="loading.gif" />');
},
success: function(data){
$('#parseSecondForm').html(data);
}
});
});
});
</script>
calculator.php receives user input and echoes next form in #parseSecondForm div in index.php:
if (form1 === '1') {
echo '
<form id="form2" method="post" formaction="form2.php">
<input id="form2" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
else {
echo '
<form id="form3" method="post" formaction="form3.php">
<input id="form3" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
I tried to echo modified javascript from index.php, but it just resets all the forms.
Maybe there are some form scripts designated for the cause or any other ideas how can I fix the issue?
In Javascript/HTML you cannot have two items with the same IDs:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
form1 can be used only once.
Same for the php dynamically created forms.

how does method POST processes/excecutes in PHP

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
}

How to have two buttons in a same form to do different actions in ajax?

I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
debug: false,
submitHandler: function(form) {
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
</body>
process.php:
<?php
print "<br>Your name is <b>".$_POST['name']."</b> ";
?>
You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>
Js:
$("#review").click(function(){
var myData = $("#myform").serialize() + "&review=review";
$.post('process.php', myData , function(data) {
$('#results').html(data);
});
}
);
Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.
Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.

Multiple submit buttons php different actions

I have a website started where I want to have 2 separate submit buttons, one of which will take data entered and do some calculations to it to display on the same screen. I've got this successfully working with:
<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
and then I use:
if (!isset($_POST['submit'])){
Do actions, display calculations}
Now I want a second submit button that still grabs the data they entered but then goes to a different address. Is there an elegant way to do this?
You could add an onclick method to the new submit button that will change the action of the form and then submit it.
<script type="text/javascript">
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
</script>
...
<form id="form1">
<!-- ... -->
<input type="button" onclick="submitForm('page1.php')" value="submit 1" />
<input type="button" onclick="submitForm('page2.php')" value="submit 2" />
</form>
You can change the form action by using formaction="page1.php" in button property .
<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
<input type="button" type="submit" formaction="page1.php">Action 0</button>
<input type="button" type="submit" formaction="page2.php">Action 1</button>
</form>
Note: The formaction attribute of the button tag is not supported in Internet Explorer 9 and earlier versions.
The best way to deal with multiple submit button is using switch case in action script
<form action="demo_form.php" method="get">
Choose your favorite subject:
<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">Java Script</button>
<button name="subject" type="submit" value="jquery">jQuery</button>
</form>
Action / Server Side script:
demo_form.php
<?php
switch($_REQUEST['subject']) {
case 'html': //action for html here
break;
case 'css': //action for css here
break;
case 'javascript': //action for javascript here
break;
case 'jquery': //action for jquery here
break;
}
?>
Ref: W3Schools
Another approach is that You can create and Use some session variable to achieve it easily.
E.g. $_SESSION['validate'].
HTML and PHP Code for buttons
<button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>
jquery and ajax Script
<script>
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'handler-file.php',
data: new FormData(this),
dataType: "json",
enctype: 'multipart/form-data',
contentType: false,
cache: false,
processData:false,
error:function(error){
//your required code or alert
alert(error.responseText);
},
success: function(response){
if(response.status=='1')
{
//your required code or alert
$('#first_submit').hide();
$('#second_submit').show();
}
else if(response.status=='2')
{
//your required code or alert
$('#first_submit').show();
$('#second_submit').hide();
}
else
{
//your required code or alert
}
}
});
});
});
</script>
Handler PHP File
<?php
session_start();
$result['status']='0';
$result['error']='';
if(!isset($_SESSION['validate']))
{
if(!isset($_FILES['file']))
{
$result['error'].='[Er-02 file missing!]';
}
else
{
//your other code
$_SESSION['validate'] = true;
$result['status']='1';
}
}
else if($_SESSION['validate']==true)
{
if(!isset($_FILES['file']))
{
$result['error'].='[Er-03 Validation file missing!]';
}
else
{
//your other code
unset($_SESSION['validate']);
$result['status']='2';
}
}
else
{
$result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);
?>
It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.
Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.
Hope it helps!

Categories