How do you send more than 2 forms to PHP? - javascript

I've gotten an assignment and it is:
Make a website/page which processes forms. You shall have atleast 4 questions/forms and you need to process it in php. After that you should be able to tell the user what they got wrong and what they got right. You should also be able to write your name and it should appear on the php site somewhere.
So here I am with a site, I got 3 questions so far (I wanted to try before I went full scale). I use jQuery to hide and show the questions and I use radio inputs and a text input for the name. When I hit submit I've tried almost everything. Currently working with jQuery like this:
$(".knapp3").click(function() {
$('#fraga1, #fraga2, #name, #fraga3').submit();
});
The php only processes the value inside #name which is my text input. My forms look like this:
<div class="fraga1">
<h1>Hejsan?</h1><br>
<form id="fraga1" action="idk.php" method="POST">
<input type="radio" name="tva" value="1">hej<br>
<input type="radio" name="tva" value="12">Hejsan<br>
<input type="radio" name="tva" value="13">Tjena<br>
</form>
</div>
<div class="fraga2">
<h1>Vad heter jag?</h1><br>
<form id="fraga2" action="idk.php" method="POST">
<input type="radio" name="tva" value="2">qqq<br>
<input type="radio" name="tva" value="22">123<br>
<input type="radio" name="tva" value="23">xxx<br>
</form>
</div>
<div class="fraga3">
<h1>Vilken linje går jag?</h1>
<form id="fraga3" action="idk.php" method="POST">
<input type="radio" name="tre" value="1">Teknik<br>
<input type="radio" name="tre" value="32">Samhälle<br>
</form>
</div>
<div class="namn">
<form id="name" action="idk.php" method="POST">
Skriv in namn: <input type="text" name="name"><br>
</form>
</div>
What is wrong? the php looks like this:
<?php
$x = 0;
if (isset($_POST["fraga1"])){ //if isset is nothing, therefore it doesnt run these statements.
$fraga1 = $_POST["fraga1"];
if($fraga1 == 1){
$x+1;
}
}
if(isset($_POST["fraga2"])){
$fraga2 = $_POST["fraga2"];
if($fraga2 == 2){
$x+1;
}
}
if(isset($_POST["fraga3"])){
$fraga3 = $_POST["fraga3"];
if($fraga3 == 3){
$x+1;
}
}
else{
echo '<p>Nope</p>';
}
echo $x;
?>
<?php
echo $_POST["name"]; //Only this one is working.
echo $_POST["fraga1"]; //This one gives the error "undefined index"
?>

Problem is solved. The solution is was like someone commented, to submit just 1 form and put all the data in there. To access it from php you just needed the name of the radio input.

use the tag id="fraga1" /2/3/4 in your inputs and put them in one form, then use the following jquery-post to send it to php in onclick-event of submit button
$.ajax({
type: 'POST',
url: 'idk.php',
data: {fraga1:$('#fraga1').val(),fraga2:$('#fraga2').val(),fraga3:$('#fraga3').val(),fraga4:$('#fraga4').val()},
dataType: "json",
success: function (data) {
//do something...
},
error: function (err) {
console.log(err)
}
});
you can use javascript jquery to $('.fraga2').show() and $('.fraga1').hide() the questions and at the end execute to post above in a button event. this is very basic programming, if you didn't have a idea how to do this i recommend reading 2 or 3 tutorials on basic php an js or go to a forum for dummis and not pros.

Related

Get a value from a PHP Page to a Javascript in Another Page Issue

this time i am having a problem to get a value of a php file where the goal is make a query (that part is done), validate if the query doesn't work, return false or else true.
That file is called into a javascript var to get the true/false value, but it doesn't work. I know that i'm failing because i printed the boolean value and alert shows "[object][object]".
Here is my HTML file
<form class="form-inline" id="formpqrs1" onSubmit="Validate()" method="get">
<label> <h4><b>Information</b></h4></label>
<br>
<select id="s2" name="s2" style="min-width:25%"></select>
<br><br>
<label><h4><b>Insert Element Name</b></h4></label>
<br>
<input name="Nombre" id="Lugarpqrs" type="text" class="form-control" placeholder="NOMBRE" required>
<br> <br>
<div id="motivos">
<label> <h4><b>Choose Type:</b></h4></label>
<br>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="1"><h5>Type 1</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="2"><h5>Type 2</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="3"><h5>Type 3</h5>
</label>
</div>
<div class=radio-inline>
<label>
<input type="radio" name="tipomotivo" id="tipomotivo" value="4"><h5>Type 4</h5>
</label>
</div>
<br><br>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here my Javascript file where i get the value of the php file, i validate from a radio button, then i create a var to get the value of the php file where the query is done.
function Validate(){
if($("#opcion:checked").val() === "1"){
var validar = false;
var validar = $.get("validaciones/Validar_Ubicacion.php?lugar="+$("#Lugarpqrs").val()+"");
if(!validar){
$.get("php/Ingresar_tipo.php?lugar="+$("#Lugarpqrs").val()+"");
alert("Success" + validar);
}
else{
alert("Element Already Exist in DB" + validar);
}
}
Here is my php file
<?php
$lugar=$_GET["lugar"];
$conexion = mysqli_connect($server, $user, $pass,$bd)
or die("ERROR");
$confirmacion = false;
$sql = "SELECT * FROM `lugar` WHERE `nombre` = '".$lugar."'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$close = mysqli_close($conexion)
or die("ERROR");
if(!$sql){
echo $confirmacion;
}
else{
$confirmacion = true;
echo $confirmacion;
}
?>
The last part if/else is where i validate if query fails that means the element doesn't exist then return $confirmacion value which is false or else $confirmacion = true which means element already exist and show an alert message in the script that is on another page.
Previously i tested other validations like the query and if/else validations of the radio button (first if validation) and it works, so, the problem is in my var validar, maybe i'm doing wrong when i get the value from my php file.
As always, thanks for your time and attention, all answers are welcome to me.
Good day.
You need to update your logic inside the jquery's .get function (since it's asynchronous.
Update your PHP file to output string "true" and "false" (best practice is to use JSON format & header) - this may work for you.
I updated for you your Javascript file:
function Validate(){
if($("#opcion:checked").val() === "1"){
var validar = false;
$.get("validaciones/Validar_Ubicacion.php?lugar="+$("#Lugarpqrs").val()+"",
function(data){
if(data=="true"){
$.get("php/Ingresar_tipo.php?lugar="+$("#Lugarpqrs").val()+"");
alert("Success" + validar);
}
else{
alert("Element Already Exist in DB" + validar);
}
});
}

How to submit two forms at a time and store first form submit output value as 2nd form value?

Using the below form 1, i'm generating a goo.gl short url inline in #shortUrlInfo area. I want to use the generated short url in 2nd form to save it in wordpress custom field.
Form 1:
<form method="post" action="">
<input style="display:none;" type='text' id='longUrl' value='<?php echo get_post_meta( get_the_ID(), 'longurl', true ); ?>' />
<input name="shorturlinput" type="button" id="shortIt" value="Short It" /></form>
<div class="info" id="shortUrlInfo"></div>
Form 2:
<?php
global $post;
if( isset($_POST['submit_meta']) ) {
if( ! empty($_POST['change_meta']) ) {
update_post_meta($post->ID, 'shorturl', $_POST['change_meta']);
}}
?>
<form method="post" action="">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
How can i submit the first form and pass the generated short url to 2nd form and submit that short url value in custom field with one click?
Or atleast, how can we display the generated short url in 2nd form input, which if we click on submit button, it should save in database.
It's my first question here & I've tried my best to find answer before posting here with no luck.
Well its all ajax . you need to post your data with ajax function to the controller which save the shortened url in data base , how ? like this :
give your second form + the first input of your second form 2 ids
$("#shortIt").click(function(){
var longUrl = $('#longUrl').val()
$.post("ur_url.php",
{
"longUrl": longUrl // here the url will be sent to your server and server communicates
// with goo.gl url shorter by its api and respond you with a variable called data
},
function(data, status){ // your server send here the shorturl and this function calls it
//also this function will be run after the server respond is completed
$('#inputID').val(data) // data will be set inside the input value
document.getElementById("#SecondForm").submit(); // your second form submits and your
// server needs to get the data and save it in your data base
});
});
all will be done with a single click .
also you can do many things when the process is going on . but i hope i gave you some clue :P
Try this in HTML:
<form (return to script)>
<input 1>
</form>
<input 2>
Then in script:
get input 1 and input 2
Next example code shows how to achieve what I believe you want (with one click!). Explanation first: one form (file #1) sends a text to a script (file #2), this script redirects to another form (file #3), this form gets the original text and automatically resend it to another script (file #4) that inserts it in database, next image explains it better:
As you can see, the text in the first form becomes a value for the second form.
Now the code. In order to test next code, you will have to create four text files and give them the given names (if you change the filenames, you will have to change the "action" property in the forms), copy-paste my code in your files, then, open you browser and run only the first file like this) :
http://localhost/form_sequence_1.php
These are the files:
form_sequence_1.php
<html>
<body>
FORM 1
<br/>
<form method="post" action="form_sequence_2.php">
Enter a text
<input type="text" name="my_text" />
<br/>
<input type="submit" value="Send text" />
</form>
</body>
</html>
form_sequence_2.php
<?php
session_start();
$_SESSION[ "my_text" ] = $_POST[ "my_text" ];
header( "Location: form_sequence_3.php" );
?>
form_sequence_3.php
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
FORM 2
<br/>
<form method="post" action="form_sequence_4.php" id="my_form">
Text entered in previous form
<input type="text" name="my_text" value="<?php echo $_SESSION[ "my_text" ]; ?>"/>
<br/>
<input type="submit" value="AUTOSENDING FORM IN 3 SECONDS" />
</form>
</body>
</html>
form_sequence_4.php
<?php
session_start();
echo $_SESSION[ "my_text" ] . " succesfully inserted into database.";
?>
More explanations:
Value in form 1 sends the text to form 2.
In the middle of form 1 and form 2 we need a script to capture the value.
Form 2 automatically resends the value thanks to a timer in JavaScript.
The last script gets the value and insert it in database (not for real).
The advantage of this approach is that the scripts allow you to do many things with the value or values, like validating or conversion.
Next is your code with my JavaScript timer code adapted :
<?php
global $post;
if ( isset($_POST['submit_meta']) )
if ( ! empty($_POST['change_meta']) )
update_post_meta( $post->ID, 'shorturl',$_POST['change_meta'] );
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
<form method="post" action="" id="my_form">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
</body>
</html>

On submit, remote call php - why aren't $_POST values being posted?

So, I'm a bit in unfamiliar territory with json and remote calls but the url and datatype is correct and... it is clearly arriving at target. BUT.!
It's a very simple form with 3 visible and 2 hidden fields.
<form id="subChange" action="#" method="POST">
<div style="clear:both;">first name</div>
<div>
<input id="fart" type="text" style="margin:4px;width:90%;" name="newFirst" value="" data-validetta="required,characters,remote[check_update]">
</div> last name<BR>
<div>
<input type="text" style="margin:4px;width:90%;" name="newLast" value="" data-validetta="required,characters,remote[check_update]">
</div> eMail<BR>
<div>
<input type="hidden" name="oldName" value="Conor" data-validetta="remote[check_update]">
</div>
<div>
<input type="hidden" name="oldEmail" value="cburkeg#gmail.com" data-validetta="remote[check_update]">
</div>
<div>
<input type="text" style="margin:4px;width:90%;" name="newEmail" value="" data-validetta="required,email,remote[check_update]">
</div>
<div style="margin-top:12px">
<input type="submit" name="sub_change" value="change it" data-validetta="remote[check_update]">
</div>
</form>
Here is the js
<script type="text/javascript">
$(function(){
$("#subChange").validetta({
realTime : true,
bubbleLoc:"right",
onValid : function( event ){
event.preventDefault();
$("#changeDIV").html("thanks Conor <P>Your subscription has been updated");
},
remote : { check_update : { type : "POST", url : "checkNewsUpdate.php", datatype : "json" }}
});
})
</script>
With fields filled we test Submit; name='sub_change' value='change it'
if (isset($_POST['sub_change'])) {
$count = count($_POST);
$postdata = file_get_contents("php://input"); //... write to file, etc.
}
output -
$count: 1
$postdata: sub_change=change+it
What happened to the other fields?
My only current working solution is to set each field with the remote call and set a $_POST validation (done auto., in real time) for each input which writes to a remote file. On submit we then call the contents of that file. Only trouble is it misses the 2 hidden files - there is no auto trigger :(
This is a clumsy work-around (that doesn't even work).
I thought about setting the hidden fields as an ID but getting the value with PHP is a trial. There must be something real simple I am missing here.

Returning Error If Radio Button NOT selected - PHP

I've searched through a lot of previously asked questions about php and radio buttons but I haven't yet found something helping in my situation. I'm building a quiz for a server-side scripting class. I'm stuck on the actual quiz part. I want an error message to echo if the user does NOT select an answer to a question. Instead when I hit the submit button without selecting any options, I'm automatically redirected to the results page. How do I correct my code so that the user is given the error message if they hit submit without answering all of the questions? Below is the current code i've written out in an attempt to check the radio buttons and next steps.
<div id="question5"> <!-- each quiz question gets this set up -->
<h2 id="question5_error">WAIT! You did not pick an answer to this question!</h2>
<p>5. What creature pulls the Hogwarts carriages?<br>
<input type="radio" name="creature" value="Cornish Pixies" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Cornish Pixies"){ echo"checked";} ?> > Cornish Pixies<br> <!-- php code checks to see if radio button has been selected-->
<input type="radio" name="creature" value="Clydesdales" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Clydesdales"){ echo"checked";} ?> > Clydesdales<br>
<input type="radio" name="creature" value="Hippogriffs" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Hippogriffs"){ echo"checked";} ?> > Hippogriffs<br>
<input type="radio" name="creature" value="Thestrals" <?php if (isset($_SESSION["creature"]) && $_SESSION["creature"]="Thestrals"){ echo"checked";} ?> > Thestrals<br>
<input type="hidden" name="sent" value="sent" onclick="Project1_Page2.php">
<input type="submit" name="goresults" value="Get Results?">|<input type="reset" name="resetquiz" value="Reset Quiz.">
</form>
</article>
<?php
if(isset($_GET["sent"])){
echo "<script type = 'javascript'>";
if(!isset($_GET["question1"])){ // QUIZ QUESTION 1 CHECK
$_SESSION["author"]=$_GET["author"];
}
else{
echo "document.getElementById('question1').style.backgroundColor = '#ffcccc';
document.getElementById('question1_error').style.display = 'block';";
}
if(!isset($_GET["question2"])){ // QUIZ QUESTION 2 CHECK
$_SESSION["godfather"]=$_GET["godfather"];
}
else{
echo"document.getElementById('question2').style.backgroundColor = '#ffcccc';
document.getElementById('question2_error').style.display = 'block';";
}
if(!isset($_GET["question3"])){ // QUIZ QUESTION 3 CHECK
$_SESSION["prison"]=$_GET["prison"];
}
else
{
echo"document.getElementById('question3').style.backgroundColor = '#ffcccc';
document.getElementById('question3_error').style.display = 'block';";
}
if(!isset($_GET["question4"])){ // QUIZ QUESTION 4 CHECK
$_SESSION["badguy"]=$_GET["badguy"];
}
else
{
echo"document.getElementById('question4').style.backgroundColor = '#ffcccc';
document.getElementById('question4_error').style.display = 'block';";
}
if(!isset($_GET["question5"])){ // QUIZ QUESTION 5 CHECK
$_SESSION["creature"]=$_GET["creature"];
}
else
{
echo"document.getElementById('question5').style.backgroundColor = '#ffcccc';
document.getElementById('question5_error').style.display = 'block';";
}
echo "</script>";
}
?>
Without seeing your HTML, it's hard to tell but here are some suggestions
in your form tag, remove "Action" attribute
<form method="post/get" >
then create a variable
$haserror = false;
and I'm not sure what are you trying to achieve here, but change the code like this
if(!isset($_GET["question1"])){ // QUIZ QUESTION 1 CHECK
$_SESSION["author"]=$_GET["author"];
echo "document.getElementById('question1').style.backgroundColor = '#ffcccc';
document.getElementById('question1_error').style.display = 'block';";
$haserror = true;
}
do the same for all checkboxes
then at the end do your if to show the result page
if(!$haserror)
{
echo '<META http-equiv="refresh" content="0;URL=newpage.php">';
}
however I suggest to rewrite the whole thing, because you are approaching it in a wrong way
First of all if you are using radios you have set their attribute name to one like
<form method="post">
<input name="question" value="1" />
<input name="question" value="2" />
<input name="question" value="3" />
<input name="question" value="4" />
</form>
in this way you set your logic statement like so.
if(isset($_POST['question'])){
//here you put the the right answer based on the user what he/she chose.
}
I suggest you to use POST is secured. If you are using GET the values of radio will appear on the url. I hope this will help.
Peace

Send value of div on form submit

I am trying to submit a form with a couple of different inputs, which all work fine. However, one of the inputs is a textarea (sort of). I had to alter it into a content editable div, mainly because I created my own bold, italic and underline buttons which wouldn't work with normal textareas. The problem is that the form on submit is not sending the text to the php and i was wondering what i could do to get the value of the div in the php.
Here is the "textarea":
<div id="dash_new_shout_textarea" name="dash_new_shout_textarea"
class="dash_new_shout_textarea" contenteditable="true"
placeholder="Write your shout..." name="dash_new_shout_textarea"
value="<?php echo isset($_POST['dash_new_shout_textarea']) ?
$_POST['dash_new_shout_textarea'] : '' ?>"></div>
The form is just a normal form with method=post.
Here is the php:
$newShoutTextarea = $_POST['dash_new_shout_textarea'];
Thanks for the help
I would suggest that you follow the other answers and use jQuery, but since there is no jQuery tag in your question I suppose that I should provide a good non-jQuery solution for you.
HTML
<form onsubmit="prepareDiv()">
<div id="dash_new_shout_textarea" class="dash_new_shout_textarea" contenteditable="true" placeholder="Write your shout..." name="dash_new_shout_textarea" value="<?php echo isset($_POST['dash_new_shout_textarea']) ? $_POST['dash_new_shout_textarea'] : '' ?>"></div>
<input type="hidden" id="dash_new_shout_textarea_hidden" name="dash_new_shout_textarea" />
</form>
Javascript
function prepareDiv() {
document.getElementById("dash_new_shout_textarea_hidden").value = document.getElementById("dash_new_shout_textarea").innerHTML;
}
Your PHP remains the same.
What you can do is this:
<div id="dash_new_shout_textarea"></div>
<input type="hidden" name="dash_new_shout_textarea" id="dash_new_shout_textarea_hidden" />
<script type="text/javascript">
setInterval(function () {
document.getElementById("dash_new_shout_textarea_hidden").value = document.getElementById("dash_new_shout_textarea").innerHTML;
}, 5);
</script>
the problem is that a DIV is not a form element and cannot be posted. If you use some javascript, you could populate a hidden input field with the data and then receive it server side as POST variable
You can add a hidden input to your form and update it with jquery
<div id="dash_new_shout_textarea" name="dash_new_shout_textarea"
class="dash_new_shout_textarea" contenteditable="true"
placeholder="Write your shout..." name="dash_new_shout_textarea"
value="></div>
<form id="target" method="post" action="destination.php">
<input id="textarea_hidden" name="textarea_hidden" type="hidden" value="">
<input type="submit" value="Submit">
</form>
script
$("#target").click(function() {
$("#textarea_hidden").val($("#dash_new_shout_textarea").val());
});
What you can do is use jQuery for this.
DEMO HERE
Proper scenario would be:
*Get value from div and save it into hidden field. *
This has to be done when you submit form:
$(function () {
$("#send").on("click", function () {
$("#hiddenfield").val($("#dash_new_shout_textarea").text());
alert($("#hiddenfield").val());
$("form#formID").submit();
});
});

Categories