php form to javascript - javascript

I need to pass the form id to javascript, but always shows the same data.
<script>
$(document).ready(function() {
$('input[name="submit"]').on('click', function(){
var vauid = $( "input[name='uid']" ).val(); alert("\n ID: "+vauid);
return false;
});
});
</script>
<? include "../includes/config.php";
$sql = "select * from table";
$reg = mysql_query($sql);
while($row = mysql_fetch_array($reg)){ ?>
<form action="" method="POST">
<input type="text" name="uid" value="<? echo $row['uid']?>" />
<input type="submit" name="submit" value="Show"/>
</form>
<? }?>

Part of the problem is that you're inserting numerous forms with elements having the same names - that is a bad idea as names are intended to be unique.
Second, when you click you have to reference the currently clicked info:
$(document).ready(function() {
$('input[name="submit"]').on('click', function(e){
e.preventDefault();
var vauid = $(this).prev("input[name='uid']").val();
console.log("ID: "+vauid);
});
});
Here is a working demo.
$(this) will be the clicked button from which we look for the previous input's value. I'm also using preventDefault() to stop the button's default action, rather than returning false.
In addition you should quit using alert() for troubleshooting., use console.log() instead.

Related

Can't enable disabled submit with JS Ajax (submit echoed by php)

I've tried everything:
document.getElementById('buy').setAttribute('disabled','false');
document.getElementById('buy').setAttribute('disabled',false);
document.getElementById('buy').removeAttribute('disabled');
document.getElementById('buy').disabled=false;
The input submit is has previously been echoed by php:
if (empty($basketproductos)) {
echo "<input type='submit' name='buy' value='Buy' disabled='disabled' id='buy'/>";
}
Also tried with disabled='true' instead of disabled='disabled'.
If you want to disable the button, you should set true for disable property.
document.getElementById('buy').disabled = true;
And like #Titus said (on the comment), make sure the element is added to the DOM before you execute a statement.
Maybe your js is executed before the html, this should work:
document.addEventListener('DOMContentLoaded', function(){
var buyButton = document.getElementById('buy');
buyButton.disabled = false; //or true
}, false);
or
<form action="">
<input type='submit' name='buy' value='Buy' disabled='false' id='buy'/>
</form>
<script>
var buyButton = document.getElementById('buy');
buyButton.disabled = false; //or true
</script>
Functional example here: https://jsfiddle.net/cfcdh99n/

First form from many gets submitted on click

Problem: Multiple forms on the same page, but only the first one is being submitted.
Tried the following:
Equating the data-ids of submit button and Form inorder to submit the clicked form (No Luck)
Dynamic form creation using Javascript.(disbanded that idea after a few tries since it was on a deadline)
Usecase
The number of forms depends on the User. If there is just one comment from him, the form submits, while if there are say 4 forms, only the first one will submit.
Javascript:
$(function() {
$(".submit").click(function() {
var data_id = $(this).data('id');
var form_id = $(this.form).data('id');
if (parseInt(data_id, 10) == parseInt(form_id, 10)) {
var commentid = document.getElementByID('commentid');
alert(commentid + formid);
} else {
alert("10");
}
});
});
PHP code:
if($comment['Comment_Username'] ==$this->getUser()->getName())
{$output .='div class="panel" data-class="'.$comment['CommentID'].'">';
$output .='<form class="form" action="" method="post" data- id="'.$comment['CommentID'].'">';
$output .='<textarea name="edit_text' class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
$output .='<input name="commentid" type="hidden" id="commentid" value="'.$comment['CommentID'].'"/>';
$output .='<input type="button' data-id="'.$comment['CommentID'].'" class="submit" value="submit"/>';
Any help would be greatly appreciated.
Thanks in advance
Wrong quote used here
$output .='<textarea name="edit_text" class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';

How to use Javascript to validate dynamically generated PHP form?

I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?
This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
Then, the use of jQuery saves pain...
Within your submit script:
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
Add this jQuery lib call in your head:
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
EDIT - See comments
Function validate should be this:
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}
getElementById returns the first element matching the selector. If you just want to verify that any of them were checked, you could do something like:
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;

onClick function inside a form with submit button causes error

When I use JavaScript button with onClick function inside the form tag in frontend.php, it causes mistake. I need this simple application that does simple job, but it got stuck at this.
I provide you two links. First is within the form tag (frontend.php) and there it doesn't work - ADDMORE BUTTON SIMPLY DOESN'T ADD MORE TEXTAREAS! And the second link is without the form tag, and it works, you can try and submit which will leave you to the welldone.php page.
1.LINK - There is a problem
2.LINK - No form tag, no problem
HTML FORM
<form action="http://www.balkanex.info/dev/frontend.php" method="post">
Title: <br/><input type="text" name="title"><br/><br/>
The question is: <br/><input type="text" name="ask"><br/><br/>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
FRONTEND.PHP FILE
<script>
am = 1;
function more(index) {
am++;
var textarea = document.createElement("textarea");
textarea.name = "answer" + am;
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner1").appendChild(div);
}
</script>
<?php
echo '<form action="welldone.php" method="post">';
$content = "";
$title = $_POST['title'];
$question = $_POST['ask'];
if($_POST['ask'] != "") {
$answer = '<textarea name="answer1"></textarea>';
$more = '<button type="button" name="more" onClick="more();">Add more</button>';
$content .= '1) '.$question.'<br/>'.$answer.'<br/><div id="inner1"></div>'.$more.'<br/><br/>';
}
echo $content;
echo'<br/><input type="submit" value="CALCULATE"></form>';
?>
RESULTS WELLDONE.PHP FILE
<?php
echo 'WOW, WELL DONE';
?>
The problem is that, when you use more, browser is uses <button name="more"> instead of function more. Then, you get
TypeError: more is not a function
This behavior is only present in forms, that's why without forms your code works.
You can fix it doing one of these:
Changing function name
Changing button name
Writing unobtrusive javascript, adding the event handler from a <script> element instead ofthe inline onclick attribute.
Anyway, your code is completely invalid and in quirks mode. You should validate it and fix the errors.

Sending data to Mysql through a showprompt in Javascript

I would like to send data that the user the filled in a show prompt box. I originally planned to send the data from a regular form, but changed my mind and want to do it through a show prompt box.
Here is my code:
<script type="text/javascript">
function show_prompt()
{
var name=prompt("question");
if (name!=null && name!="")
{
document.write("<p>This is your question " + name + "</p>");
}
}
</script>
the html for the form is:
<form id="propose" name="input" action="insertpropose.php" method="post"><br/>
<input type="submit" onclick="show_prompt()" value="propose" />
</form>
and the PHP is
$query="SELECT propose* FROM propose";
$result=mysql_query($query);
$result = mysql_query("SELECT * FROM propose");
I m new to programming, so I hope I was clear.
You can do something to this effect:
HTML:
<form id="propose" name="input" action="insertpropose.php" method="post"><br/>
<input type="submit" onclick="show_prompt()" value="propose" />
<input type="hidden" name="propose" value="">
</form>
Javascript:
<script type="text/javascript">
function show_prompt()
{
var name=prompt("question");
if (name!=null && name!="")
{
//set the hidden input value to the value entered in the prompt
document.input.purpose.value = name; //document.input referring to the form named 'input'
document.input.submit(); //submit the form
}
}
</script>
Your SQL is a bit wonky, so I changed it to function how I assumed you wanted it to work:
$purpose = $_POST['purpose'];
$query="SELECT propose FROM propose WHERE purpose = ". $purpose;
$result=mysql_query($query);
Note that using SQL in this way is HIGHLY insecure.
This should give you your desired effect, although this probably isn't the best way to go about doing it.

Categories