Here is my problem.. I have some JavaScript that I want to run, however I need it to be unique each time it gets inserted. I tried adding a variable to it that would change it, however it only changes it on the first call/display. Here is the script:
<script type=\"text/javascript\">
function validate_f( )
{
var x=document.forms[\"fill\"][\"textfield\"].value
if (x==null || x==\"\")
{
alert(\"Field cannot be empty\");
return false;
}
}
</script>
The actual form code is:
echo "<td width=\"10%\">
<form method=\"POST\"action=\"$actual_link\" id=\"fill\" onsubmit=\"return validate_f( );\">
<input type=\"hidden\" value=\"{$data['id']}\" name=\"id\">
<input type=\"text\" size=\"20\" class=\"BUTTON_INPUT\" name=\"url\" value=\"\" id=\"textfield\">
</td>
<td width=\"1%\">
<input type=\"Submit\" class=\"BUTTON_FILL\" name=\"fill\" value=\"\">
</form>
The problem is that form gets echoed multiple times with different links, but the script will only work the first time. So my only solution I could think of was to have the JavaScript echoed along with the form and have the function name changed on both the script & the form.
I hope what I'm trying to do makes sense, so basically I need "function validate_f( )" & "onsubmit=\"return validate_f( );\"" to change with each repeat/echo ..
if your text field is in every form you can use only one generic function like this that will work for all forms no matter their id
function validate_f() {
var x = this['textfield']
if (!x || !x.value) {
alert("field cannot be empty")
return false
}
return true;
}
I came up with a solution for this, and thought I would share it in case someone comes across this. But basically the form that is being echoed/repeated did get unique data on each time it repeated.. So basically I took that unique value and put it as the function & the form id.. It is pretty simple now that I look back at it, I just had to think really hard about how to get something unique that changed. Hope this helps someone..
Related
I have a MySQL database with auto-increment column "line numbers." In the form that is being submitted to the script, there are check boxes. I don't know how many check boxes there are, because each Customer has a different number of services that they're allowed to access. When the check box is clicked, they've used a service and the integer in column Available for that row needs to decrease by one. Sometimes, the user can say that multiple services were used and more than one row needs to be affected.
Where I'm becoming stuck is on two things: how the check boxes are named, and if I name them by the line number, how to access them with PHP.
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='" . $cell['line_item'] . "'>";
}
The above code is how I'm making the check box. Probably the biggest part of the question is how I could better name it so that I can predict what names to look for ($_POST[name]) when the form is submitted (instead of a random number).
The other part I'm getting stuck on is, if I do decide to keep the naming strategy, how to fetch it. What I've thought of is to use a loop to extract the true/false data that's carried, but I don't know how to execute that. Sure, I can write a for or while loop, but I don't know how to extract the name of the object.
Is there any way I could carry extra data to a PHP script, other than the name?
Is there a better way I could name the check box so that I'm not stuck having to figure out a complicated way of finding the data, retrieving the name, etc.
I'm sort of a beginner when it comes to PHP. I know how to get my way around with for loops, while loops, basic commands such as echo... but I'm really lacking
while($cell = mysqli_fetch_array($service_details_query)) {
echo "</br>";
echo "<input type='checkbox' name='checkboxname[]' value ='".$cell['line_item']."'>";
}
It should do a $_POST array with the name checkboxname inside that array, you find the values.
You can find it threating $_POST['checkboxname'] as an array.
Try name it like: "checkbox_" . $cell['line_item'] so you can do something like this:
foreach($_POST as $name => $value)
{
if(substr($name, 9) == "checkbox_"){
//USE the value
}
}
or you could name like this:
echo "<input type='checkbox' name='services[]' value='" . $cell['id'] . "'>";
and get it as an array like this: $services = $_POST["services"];
Alright. Since you wanted to be able to add extra data, I thought I'd start over complicating stuff a lot! But it does the job. Explanation can be found in the codes comments.
First the HTML and Javascript part:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
// First we need to get our form
var myForm = document.getElementById("myForm");
// Next we're adding an event listener to the form submit so we can catch it
// and use a function to do some stuff before sending it over to the php file
myForm.addEventListener("submit", function(event){
// Now we need to temporarely stop the form from submitting
event.preventDefault();
// Next we need to get all our checkboxes
var checkBoxes = document.getElementsByClassName("myCheckbox");
// Now we need some arrays for all the data we're going to send over
// Basicly you make one for each data attribute
var lineNr = [];
var someThing = [];
// Lets loop through all checkboxes
for (var i=0; i<checkBoxes.length; i++) {
// Catch the ones checked
if (checkBoxes[i].checked) {
// Push the data attribute values to the arrays
lineNr.push(checkBoxes[i].dataset.linenr);
someThing.push(checkBoxes[i].dataset.something);
}
}
// Now we to JSON encode these arrays to send them over to PHP
var jsonLineNr = JSON.stringify(lineNr);
var jsonSomeThing = JSON.stringify(someThing);
// Since we cannot directly add these variables to our form submit,
// unless we use Ajax, we need to add them to our form in some
// hidden fields
myForm.innerHTML += "<input type='hidden' name='jsonLineNrs' value='"+ jsonLineNr +"' />";
myForm.innerHTML += "<input type='hidden' name='jsonSomeThings' value='"+ jsonSomeThing +"' />";
// All done, now we submit our form
myForm.submit();
}
</script>
</head>
<body>
<form method="POST" action="your_php_file.php" id="myForm" accept-charset="utf-8">
<input type="checkbox" class="myCheckbox" data-linenr="1" data-something="value1" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="2" data-something="value2" />
<br />
<input type="checkbox" class="myCheckbox" data-linenr="3" data-something="value3" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</form>
Next the PHP part:
<?php
// First we need to decode the JSON strings so we can use them
$jsonLineNrs = json_decode($_POST['jsonLineNrs']);
$jsonSomeThings = json_decode($_POST['jsonSomeThings']);
// Now both of those variables are arrays that contain all the data you wanted
// You can loop each of them to do stuff like
foreach($jsonLineNrs as $jsonLineNr){
echo $jsonLineNr; //Will echo out each line number
}
// Or if you want to loop through both simultaneously so you can
// keep each checked box data values together:
for($i=0; $i<count($jsonLineNrs)-1; $i++) {
echo $jsonLineNrs[$i].' - '.$jsonSomeThings[$i];
}
?>
Now before I finish this answer, one last warning: I didn't sanitize the user input in the Javascript part. It would make this answer even a lot more complicated and way to long. Be sure to do this, as you can NEVER EVER trust user input! Even if it's only checkboxes, POST data can be changed before it's submitted!
I would prefix the names depending on context, for example:
<input type='checkbox' name='service_" . $cell['line_item'] . "'>"
This way, if the checkbox represents a service, you could identify it by the prefix.
The issue I have been experiencing deals with input from HTML which was generated using PHP echo statements. Here is the function I have that outputs the form:
function confirm_recipients()
{
echo "<form action = ' ' name ='email_options' method='post'>";
echo "<input type='submit' name='sendRecipients' value='Yes, I want to send the emails' >";
echo "</form>";
}
Later on in the same PHP page, I call the function and then check to see if the submit button was set.
confirm_recipients();
if (isset($_POST['sendRecipients']))
{
//perform actions
}
However, this code is not functional seeing as even when the submit button is set (clicked by the user), the if statement block is never executed. Perhaps there is an issue with posting from the same file I want to "read in" from? Thanks for any advice.
Updates
Thank you for such immediate response. Sadly none of the suggestions have worked (removing the space in the action value or the suggestion made by user623952). No errors have been reported, the button is just failing to be set. I am looking for other places in the file that might have errors, perhaps in the order I call the function.
This works fine for me:
<?php
print "<pre>".print_r($_POST,true)."</pre>";
confirm_recipients();
function confirm_recipients() {
echo "<form action = ' ' name ='email_options' method='post'>";
echo "<input type='submit' name='sendRecipients' value='Yes, I want to send the emails' >";
echo "</form>";
}
if (isset($_POST['sendRecipients']))
{
print "<br/>sendRecipients is set!<br/>";
}
?>
I think your problem might be somewhere else in the code.
It's okay to POST the form data to the same script that contains the form. Change the action attribute to the URL of the script, do not set it to whitespace, which is what you did.
I don't think the value of a submit input is sent as part of the POST. Try using an input type="hidden" with the name 'sendRecipients'.
I might be on the wrong path (tiredness..) for the moment but i have passed 4 hours or something similar to debug my code. I have a form that is auto submitted when I click on a radio button, once clicked the next form appear and let me input the customer information. But when the page reload for displaying the other form, my variable $CustomerType is set and correct and, when i complete the input form (the second one) the php check if everything in it seems correct and it does, but it says my variable $CustomerType is missing then reload the page and ask me again to set the type.
I can't paste all my code out here (~300 lines) but here is the core :
<?php $_POST['CustomerType']="SOMEONE"; ?> // Ok so this was the trick, it solved the main bug but it now fix my choice to SOMEONE only. Can't change to another type
<form method="post" action="<?php echo escaped_html($_SERVER['PHP_SELF'],'URL');?>">
<?php
$array=show_enum("customer", "CustomerType");
$checked="";
foreach($array as $CustomerType)
{
$checked="";
if(isset($_POST['CustomerType']))
{
if($_POST['CustomerType']==$CustomerType) $checked="checked";
}
echo "<input type='radio' name='CustomerType' value=".$CustomerType." ".$checked." onClick='this.form.submit()'>".$CustomerType."</input>";
}
?> </form>
EDIT Ok there is some news : by modifying the top who was : <?php $_POST['CustomerType']="SOMEONE"; ?>
TO
if(!isset($_POST['CustomerType'])) $_POST['CustomerType']="SOMEONE";
It seems to solve the second problem of the form, which couldn't let me change the type (auto-rollback to SOMEONE). But now, on form submit my choices are always rolling back to [CustomerType] => SOMEONE instead of SOMEBODY (and i checked SOMEBODY).
It means that i can't hold the value $_POST['CustomerType'] on page reload for submitting.
For example : This one which seems identical except that it's submitted with "save" button instead of onsubmit is working fine.
$array=show_enum("customer", "Language");
foreach($array as $Language)
{
$checked="";
if(isset($_POST['Language']))
{
if($_POST['Language']==$Language) $checked="checked";
}
else if($Language=="FR") $checked="checked";
echo "<input type='radio' name='Language' value=".$Language." ".$checked." />";
string2languagepic($Language);
}
Picture of the problem *OnSubmit = onClick='this.form.submit()
After looking at your code a little more I think I have spotted your problem, try the following and see if it works.
echo "<input type='radio' name='CustomerType' id='CustomerType' value='$CustomerType' $checked onClick='this.form.submit();' >"
If that fails you could always add a hidden field, and when clicking on the radio button it adds a value to it and then submits the form.
I have a web based tool. There is a login where username, loggedin and authorised are stored in session variables.
There is one particular page where I have a form that has multiple buttons, I wish to disable one button based on what the users authorisation level is. So if authorised is 0 (user) the button is disabled, else it's enabled as I've only got two authorisation levels, 0 & 1.
I've attached what I've done below, and to me it looks right, obviously it's not!
Here is the JQuery function:
$(function disable(){
$('#signBtn').attr('disabled', true);
});
Here is the PHP code:
if($_SESSION['authorised'] == '0')
{
echo "<SCRIPT LANGUAGE='javascript'>disable();</SCRIPT>";
}
Here is my HTML code:
<input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" />
If there is anyone out there that can see what my problem is I would really appreciate it...this is my last piece of the puzzle and I'm presenting this today (Software Intern).
So basically if the level is 0 call the function.
Regards,
Gary
No warranty because I don't have all the code
Change the static JavaScript Code to this
var disableSingoff = function () {
$('#signBtn').attr('disabled', true);
}
In your original code, you execute the disable() function right when the DOM is ready by wrapping it in $().
Change the PHP code to this
if($_SESSION['authorised'] == '0') {
echo "<script>$(function () { disableSignoff(); })</script>";
}
It might be easier to simply set the value in the HTML if possible
if($_SESSION['authorised'] == '0'){
echo '<button type="button" disabled="disabled">Click Me!</button>';
}else{
echo '<button type="button">Click Me!</button>';
}
This would work before the page even starts loading.
The other option would be to hook the window on load function.
window.onload = (function(){ [...] }
is the <input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" /> being echoed from a php statement? if not you can get rid of all the '\'s. they are not necessary when writing strictly html.
To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>