Form submit is not posting dynamic created fields by jQuery - javascript

Actually I am generating input fields for HTML-Form dynamically.
Now my problem is when submit the form nothing will be post to my php.
So when I am using
echo "<pre>"; print_r($_POST) ; echo "</pre>";
in my php there is an empty array.
Here is my html-form:
<form method="POST" action="../php/saveTraining.php" id="trainingForm">
<section id="mainCategory" class="hidden">
<label><input type="checkbox" name="mainCat" id="Krafttraining">Krafttraining</label>
<label><input type="checkbox" name="mainCat" id="Joggen">Joggen</label>
</section>
<section id="categoryKrafttraining" class="hidden">
<label class="subCategory"><input type="checkbox" class="subCategory">Kurzhantel</label>
<label class="subCategory"><input type="checkbox" class="subCategory">Bankdrücken</label>
</section>
<section id="categoryJoggen" class="hidden">
<label><input type="number" name="joggingKm" id="joggingKm">Kilometer</label>
<label><input type="number" name="joggingTime" id="joggingTime">Zeit</label>
</section>
<input type="hidden" id="saveTraining" name="sent" value="save">
</form>
you can ignore the 3rd section, because actually I am not working with it.
So here is the .js code where I create the additional fields:
('#'+ category +' :checkbox').off('change').change(function (event) {
console.log("YUP");
sectionID = 'sect'+ $(event.target.parentNode).text();
if (this.checked){
//append input fields
$('#'+category).append( '<section id='+sectionID+'><h5>'+$(event.target.parentNode).text()+'</h5><label><input type="number" name="saetze" id="saetze">Sätze</label>' +
'<label><input type="number" name="wiederholungen" id="wiederholungen">Wiederholungen</label></section>');
}else{
console.log("HIER");
//delete not necessary input fields
$('#'+sectionID).remove();
}
});
here is my .php connection :
<?php
$host= "127.0.0.1";
$user= "censored";
$pw= "censored";
$db= "censored";
$mysqli = new mysqli("localhost", "$db", "$user", "$pw", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
echo $mysqli->host_info . "\n";
?>
and here is the .php that get called from form submit:
<?php
include ('datenbankConnect.php');
$saetze = $_POST['saetze'];
$wiederholungen = $_POST['wiederholungen'];
echo "werte:";
echo $saetze;
echo "<pre>"; print_r($_POST) ; echo "</pre>";
?>
So when submitting the form I also get the following message from my php:
Notice: Undefined index:
Notice: Undefined index:
Maybe you could help me. It would be great!
So there is a problem with method="post". When I am using method="get" and accordingly changing the php to GET everything works fine.
So could it be possible that POST is not working for PhpStorm's integrated server?
SOLVED
The problem was that PhpStorm's integrated server have some issues with POST method. With GET everything works fine.
And guys, don´t forget to give your input types names ;)

What is output of:
echo "<pre>"; print_r($_POST) ; echo "</pre>";
If you don't have saetze in your post array you should inspect HTML code with firebug or chrome devTools to see if your javascript code is working properly.

Related

Guestbook application doesn't work. I used html, php, mysql, javascript. Can't add messages to the guestbook page

I have a simple application to make and i'm struggling to make it work.
It's a guestbook page which I have to make and it must have 3 fields:
Name
Email
Message box
A submit button.
All of the message must be at least 5 chars and at the push of the button, it must get under the message box.
For this, I created
I. Three files:
1.index.html - where is the main code in JS and also html
2.addcomment.php
3.guestbook.php
II. One Database (which I named it "db1")
The Problem is that when I click submit, instead of recording the comment underneath, the addcomment.php code appears in my html page. What could be the problem.
I won`t put the "head" part of the index.html page here because it's only JS which checks the fields to be correct. I'll put the "body" of the html page so you can tell me if something it's wrong:
//Update:
<body>
<div id="wrapper"
</div>
<div id="menu">
<hr/>
<ul id="mainMenu">
<li>Home</li>
<li>Guestbook</li>
</ul>
<hr/>
</div>
<div id="content">
//finished update
<h2>Sign to the Guest Book </h2>
<form name="guest" method="post" action="addcomment.php" onsubmit="return Validate();">
<span>Name:</span> <input type="text" name="name"/><br />
<span>Email:</span> <input type="text" name="email"/><br />
<p>Message:</p> <textarea name="message" rows="10" cols="50"> </textarea> <br />
<input type="submit" value="Sign this in the Book" />
</form>
</div>
</div>
<div id="footer">
<hr/>
<p>Thank you for the visit! </p>
</div>
</body>
</html>
the addcomment.php code which is called above:
<?php
$host="localhost";
$user="db1";
$pass="test123";
$dbname="db1";
$con=mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno($con))
{
echo "<h1>Failed to connect to MySQL: " . mysqli_connect_error() ."</h1>";
}
$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$sql="INSERT INTO db1(name,email,message) VALUES('$name','$email','$message')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
echo "Values stored to db!";
mysqli_close($con);
?>
So. I installed XAMMP. and using xammp control panel I started the server Apache and MySql. Using that, I created a db using localhost/phpmyadmin which I named "db1". I gave the user and db the same name and I granted all acces for that user to my database.
Here is the SQL query I used for the table creation in phpmyadmin to my "db1":
CREATE TABLE db1(
id int(5) NOT NULL auto_increment,
name varchar(60) NOT NULL default ' ',
email varchar(60) NOT NULL default ' ',
message text NOT NULL,
Primary key(id)
);
Can you tell me why my page doesn't work? Why the messages doesn`t post? I simply don't get it and tried everything the past weekend.
Thanks a lot
Update: It worked. It seems that if we call it from the address bar and not from the folder with double click, it works. I just wrote in the address bar: localhost/guestbook, and it worked.
Here is my other file "guestbook.php" which I used to show on the index.html page the comments from the users:
<?php
$host="localhost"; //Add your SQL Server host here
$user="db1"; //SQL Username
$pass="test123"; //SQL Password
$dbname="db1"; //SQL Database Name
$con=mysqli_connect($host,$user,$pass,$dbname);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT name,message FROM db1");
while($row = mysqli_fetch_array($result))
{ ?>
<h3><?php echo $row['name']; ?></h3>
<p><?php echo $row['message']; ?></p>
<?php }
mysqli_close($con);
?>
I also updated the html code above so you can see how I created the menu for guestbook list.

php - select option value not passed to post

Im pretty stuck at this code, I really can't see why it should not work, i don't know if some javascript code im running beforehand is interfering?
Only showing relevant part of the code
The first section with javascript updates page when selecting another dropdown, and is placed before the code that im struggling with:
`
<script type="text/JavaScript">
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var location = elLocation.options[elLocation.selectedIndex].value;
document.getElementById("form1").action = "choose.php?id=" + location;
document.getElementById("form1").submit();
}
</script>
<form id="form1" name="form1" method="post">
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<?php
if ($chosen_id == "1") { ?>
<option value = "1" selected><?php echo "dropdown text" ?></option>
<? } else { ?>
<option value = "1"><?php echo "dropdown text" ?></option>
<?php } ?>
</select>
</form>
<form method="post" action="update.php">
<select size="1" id="choice" name="value">
<?php
while($row = mysqli_fetch_array($query)) {
$id = $row['id'];
$number = $row['number'];
>?
<option value = "<?php echo ($id) ?>"><?php echo "ID=" . ($id) . " - #" . ($number) . ""?></option>
<?php
}
mysqli_close($db_conn);
?>
</select>
<input name="submit" type="submit" value="Submit">
</form>
update.php:
<?php
if (isset($_POST['submit'])) {
$chosen_id = $_POST['id'];
}
?>
`
I've only posted the code handling the select option and the post part...
Why is the $chosen_id variable always 0 ?
The while loop works, and fill's the variable, as this is tested with echo command inside the option line
Any help is much appreciated...
$_POST['id'] and <select size="1" id="choice" name="value">
Use $_POST['value']
You are trying to print the wrong key
if you trying to get the value of form_location_id
$chosen_id = $_POST['form_location_id'];
And if you trying to get the value of choice
$chosen_id = $_POST['value'];
This is why when you post a form to php it use html name attribute as key to assign the value to $_POST Array
I'd change Update.php to
<?php
if (isset($_POST['value'])) {
$chosen_id = $_POST['value'];
}
?>
You need to use the form_location_id to get the required value. You are using the wrong key to access the data. You need to use the name of the input. In this case, the input is the select and the name of that is form_location_id. So, you need to do this.
$value = $_POST['form_location_id'];
Try it out and do let me know if it worked out for you.
Thanks for everyone posting idea's - i've actually got it working, the code was actually working, only error was a misplaced tag, which was placed inside a tag, when placed outside this tag it works ;)

preparing online test in php using javascript

I want to create a test pattern in PHP using MySQL database.Here i want to fetch questions form database and display those in my html pages. Now i want to create a division with next button and when user clicks it should display the next question that fetched from database in the same division dynamically. i guess it can be achieved through jQquery or javascript but unable to get the logic.
can anyone help.
thanks in advance.
here is a sample code that i have tried to display multiple divisions with javascript.
this is my database structure,
fields : qid,question,opt1,opt2,opt3,opt4
this is php code for fetching data form database.
<?php
$result=executeQuery("select * from quest");
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
//echo $row['qid'];echo "<br/>";
echo $row['question']; echo "<br/>";
?>
<input type="radio" name="a1" value="'<?php echo $row['opt1']; ?>'" ><?php echo $row['opt1']; echo "<br/>"; ?>
<input type="radio" name="a1" value="'<?php echo $row['opt2']; ?>'" ><?php echo $row['opt2']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt3']; ?>'" ><?php echo $row['opt3']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt4']; ?>'" ><?php echo $row['opt4']; echo "<br/>";?>
<?php
}
}
?>
<input type="submit" name="submit" value="submit">
now this fetches all the rows at a time and displays it.
this is javascript
var x=1;
function myfunc(){
document.getElementById(x).style.display="block" ;
x++;
}
when i click on button every time,respected division is displayed, but i want to display all data within one common division when each time the button is clicked.
If you don't want to reload a page when clicking the next button, we can use a Javascript library called jQuery.
I would also suggest that you use prepared statement rather than using the deprecated mysql_* API.
Lets start first by re-establishing your mysql_* and turn it to mysqli_*:
/* ESTABLISH CONNECTION */
$con = new mysqli("Host", "username", "password", "database"); /* REPLACE NECESSARY DATA INSIDE */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest ORDER BY qid LIMIT 1")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4); /* BIND THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close();
} /* END OF PREPARED STATEMENT */
After we get the data, we can now put it inside your form.
<h1 id="question"><?php echo $question; ?></h1>
<input type="hidden" id="qid" value="<?php echo $qid; ?>">
<input type="radio" name="a1" id="op1" value="<?php echo $opt1; ?>"><span id="op1text"><?php echo $opt1; ?></span><br/>
<input type="radio" name="a1" id="op2" value="<?php echo $opt2; ?>"><span id="op2text"><?php echo $opt2; ?></span><br/>
<input type="radio" name="a1" id="op3" value="<?php echo $opt3; ?>"><span id="op3text"><?php echo $opt3; ?></span><br/>
<input type="radio" name="a1" id="op4" value="<?php echo $opt4; ?>"><span id="op4text"><?php echo $opt4; ?></span><br/>
<input type="submit" name="submit" id="submit" value="Next"> <!-- THIS SERVES AS THE SUBMIT AND NEXT BUTTON -->
Before you proceed, download the library here.
Now, we can create a script that will take the answer and go to the next question. We will submit the answer of the user to the database using AJAX.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script>
$(document).ready(function(){
$("#submit").click(function(){ /* WHEN SUBMIT IS CLICKED */
var qid = $("#qid").val(); /* GET THE question id */
var selected = $("input[type='radio'][name='a1']:checked");
if (selected.length > 0) { /* CHECK THE SELECTED RADIO BUTTON */
answer = selected.val();
}
$.ajax({
type: "POST", /* THE METHOD WE WILL BE USING TO PASS THE DATA */
url: "action.php", /* THIS IS WHERE THE DATA WILL GO */
data: {"questionid" : qid, "answer" : answer}, /* THE DATA WE WILL BE PASSING */
dataType : 'json',
success: function(result){ /* WHEN IT IS SUCCESSFUL */
/* THIS WILL REPLACE THE DATA IN OUR QUESTION PAGE */
$("#qid").val(result.questionid);
$("#question").html(result.question);
$("#op1").val(result.op1);
$("#op2").val(result.op2);
$("#op3").val(result.op3);
$("#op4").val(result.op4);
$("#op1text").html(result.op1);
$("#op2text").html(result.op2);
$("#op3text").html(result.op3);
$("#op4text").html(result.op4);
}
}); /* END OF AJAX */
});
});
</script>
Then, we can create the action.php which takes the data/answer from the question page.
<?php
if(isset($_POST["questionid"])){
/* INCLUDE OUR NEW ESTABLISHED CONNECTION HERE */
/* PUT HERE YOUR INSERT QUERY WHICH STORES THE USER'S ANSWERS */
/* THEN FETCH THE NEXT QUESTION */
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest WHERE qid > ? ORDER BY qid LIMIT 1")){
$stmt->bind_param("i", $_POST["questionid"]);
$stmt->execute();
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4);
$stmt->fetch();
$stmt->close();
} /* END OF PREPARED STATEMENT */
/* THIS SET OF DATA WILL REPLACE THE DATA IN OUR CURRENT QUESTION PAGE */
echo json_encode(array("questionid" => $qid, "question" => $question, "op1" => $opt1, "op2" => $opt2, "op3" => $opt3, "op4", => op4));
} /* END OF ISSET */
?>
if you dont want to implement with ajax. Then list all questions and use jQuery to display single div. Use 'click' functions on next button to display the next questions.
If you are going by this method, try the following instruction. Hope It will be simple for you.
Display all the questions and answers.
while($row=mysql_fetch_array($result)){ ?>
<li class="test " id="qid_<?php echo $row['id']; ?>" >
<?php echo $row['question']; /* here display the stuff */ ?></li>
<?php }
Create "prev" and "next" buttons.
<span class="prev_q">Prev</span>
<span class="next_q">Next</span>
Add this css( to make first question as active )
li.test { display:none; }
li.activequestion{ display:block;background:#cccccc; color:#c40001; }
Add the script to make prev, next buttons working
<script>
jQuery(document).ready(function(){
jQuery('li.test:first').addClass('activequestion');
jQuery('.next_q').click(function(){
var nonext=jQuery('.test:last').hasClass('activequestion');
if(nonext)
{ alert("no next available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').next().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
jQuery('.prev_q').click(function(){
var noprevious=jQuery('.test:first').hasClass('activequestion');
if(noprevious)
{ alert("no previous available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').prev().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
});
</script>

Passing url parameters in form action attribute

<?php for($i = 0; $i < $pin_num_rows; $i++){ ?>
<form action="/group/<?php echo $group_id ?>?Comment=<?php echo $pin_id[$i] ?>" method="post" id="group-comment-form">
<textarea name="group-comment" id="group-comment" placeholder="Add a comment..." spellcheck="false"></textarea>
</form>
<?php } ?>
This is the some part of my code. As you can see, I am passing the value of pin_id in my form action. The problem is, whenever I post comment, the form submits the value with /group/?Comment=1 but it supposed to submit with 1, when I comment to the first post. So, when I comment to the second post, it supposed pass 2 but it doesn't. It always passes /group/?Comment=1
I did echo this right after my textarea and I see that for every comment form, the number increments as it should be but when I submit, it submits with value 1. I am going crazy.
<?php echo "/group/<?php echo $group_id ?>?Comment=$pin_id[$i]" ?>
I have also this part in my code in the same loop above and it has the same logic but it works. I don't understand why the form part doesn't work.
Edit
Delete
EDIT
I wrote this simple program which demonstrates the same logic that I used for the site and this simple program works but website. I guess the problem is not about the names of form or textarea.
<?php
$inputValue = NULL;
$id = [1,2,3];
if(isset($_POST['inputName'])){
$inputValue = $_POST['inputName'];
echo "<br>Input Value: " . $inputValue;
}
if(isset($_GET['id'])){
$getValue = $_GET['id'];
echo "<br>Get Value: " . $getValue;
}
?>
<html>
<head><title>Multiple Forms in One Page</title></head>
<body>
<br>
Main Page
<br>
<?php for($i = 0; $i < 3; $i++){ ?>
<form action="index.php?id=<?php echo $id[$i] ?>" method="post" name="formName">
<textarea name="inputName"></textarea>
<input type="submit" name="submitName">
</form>
<?php } ?>
</body>
</html>
FOUND THE PROBLEM (BUT STILL NEED FIX)
<script>
$(function() {
$('textarea#group-comment').on('keydown', function(e) {
if(e.keyCode == 13 && !e.shiftKey){
document.getElementById('group-comment-form').submit();
}
});
});
</script>
I use this script to submit my forms. I don't have a submit button to submit. If I use submit button, everything works perfect but if I use this script above to submit the form, it won't work. What should I do to make the script above work?
SOLUTION
After I found where the problem is caused, I created another question to find a fix for the problem.
The answer is here: Solutution

Adding css and javascript to Yii's CHtml and other attributes

how do you covert this html code into the yii CHtml?
<form aciton='site/qrcode' method='POST'>
<input type='text' value='Generate Code here..' name='generate' id='gen' onclick='checkval()' class='ext'>
<input type='submit' value='Generate' id='submit'>
</form>
can anyone please help? My main aim of this is to knkow how to put a class and Onclick event in a textbox or button.
Use the third parameter of the textField method (htmlOptions array), like this:
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::textField('generate','Generate Code here...', array('id'=>'gen', 'onclick'=>'checkval()', 'class'=>'ext')) ?>
<?php echo CHtml::submitButton('Generate', array('id'=>'submit')); ?>
<?php echo CHtml::endForm(); ?>
(I left all the opening and closing tags for other html to be interspersed.)

Categories