In a table it has a checkbox along with information in each row. When checkboxes are selected, I want it to run php related to the button and within it to call a JS function.
It calls the JS fine, but after that, it does not return to where it was and pick it up again as I still need to use the information within it when the JS has been ran. It's losing the checkboxes that were selected, and jumping out of it, whereas it's needed to keep the checkboxes selected and stay where it was.
Any help would be hugely appreciated as I've spent a long time trying different combinations to do it but not had much luck, to the point where I've even tried calling the js straight from the button and then selecting checkboxes after
'renameFile' is called from
<input type="submit" value="Rename" name="renameFile"/><br>
Then the php
if(isset($_REQUEST['renameFile']))
{
//uses checkboxes from table
if(isset($_POST['checkbox']))
{
$checkedboxes = $_POST['checkbox'];
$count = count($checkedboxes);
if($count == 1)
{
foreach($_POST['checkbox'] as $selected)
{
echo "<script> renameFile(); </script>";
if($rename = $_GET['rename'])
{
echo $rename;
}
}
JavaScript function
function renameFile()
{
var rename = prompt("Please enter a new name", "");
window.location.href="MainHomescreen.php?rename="+rename;
}
Related
I have a form which asks for employment history, where you have applied to college etc. So for example for colleges they applied to I have one text box at first and there is a button below that calls a javascript function to add another text input right below it. When I first made this form I was doing that with a few different pieces of data then once they were submitted I would get them from $_POST and put them in arrays then add each element of the array to the corresponding table in my db. All of a sudden though, I can no longer submit my form and I get a message telling me that I have tried to get an unspecified index. However when i inspect the text inputs in my browser they are correctly named. I read that I should name them college[] so that they all go into an array, but that also did not work.... now what?
js:
var numcol = 1;
function addnewschool(){
numcol++;
var container = document.getElementById("collegecontainer");
container.appendChild(document.createTextNode(numcol));
var input = document.createElement("input");
input.type = "text";
input.name = 'applied'+numcol;
container.appendChild(input);
container.appendChild(document.createElement("br"));}
html:
<p class="text-dark mb-4">List the Colleges you have applied to:<br>
<div id="collegecontainer" name="collegecontainer">
<input type="text" name='applied1'><br>
</div>
<input type="button" id="addcollege" name="addcollege" value="Add College"
onClick="addnewschool()"><br>
</p>
php:
$applied = array();
foreach($_POST['applied'] as $value){
array_push($applied, $value);
}
Update: Ok so I changed it to another way and that didn't work so i decided to just copy an earlier version of it which was working and paste it into the correct layout. And that worked... SO now that it was fixed i continued adding to it. I added "required" to a few tags, changed some styling a bit, and changed my javascript file a bit. But now I'm having the same issues as before. All of my POST arrays only have the first value in them. What could I have added that changed this? Has anyone ever had any issues like this?
Your first additional input should have index "applied1", not "applied2"
look at:
var numcol = 1; // put this to 0
function addnewschool(){
numcol++; // or move this to the end of the function
You don't need to add a different name for each input. Just use applied[] in all input names.
To get the array in PHP, just use $_POST['applied'].
If you want to use each of them later, you could use a foreach, like
foreach ($_POST['applied'] as $value) {
// Do what you want. Retrieve the value using $value
}
Or any other method you prefer.
Name your text input field(s) applied[] and when you process the form the post value of $_POST['applied'] will be an array already filled for you with however many entries were completed.
To get the data into your table:
foreach ($_POST['applied'] as $id => $applied) {
$sql = "INSERT INTO Colleges(id, college) VALUES('$id','$applied')";
if($conn2->query($sql) === TRUE){
echo "New Record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn2->error;
}
} // end of foreach
I am pretty new to coding php and javascript but have manged to scrape my way through so far. However, I have hit a wall. I'm not 100% sure that what I'm trying to do can be done, or that I'm even attempting it in an effective way.
I have a dynamically filled table, made of rows from a SQL statement using php. On each row is a radio button, each one given a unique value based on the row number (a unique value in one of the database columns). I am attempting to program a button that enables the user to pass a selected radio button value to a separate php enabled page that will allow the user to edit the row information using the unique row value. Also, i used the confirm option, because I would also like to add an if else statement that allows the user to cancel, if the wrong row was selected (I haven't attempted that yet because I haven't been able to get the value to pass).
Page button
<input type="button" id="edit_order_button" value="Edit Order"></input>
JQuery page
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
var r = confirm("Confirm Order Number to edit: " + selected);
$.post("php/editOrder.php", {
selected1: selected
}, function(data,status) {
//alert("Data: " + data + "\nStatus: " + status);
window.open("php/editOrder.php","Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
});
});
});
PHP end destination
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
require('config.php');
$selected2= isset($_POST['selected1']) ? $_POST['selected1'] : ''; // Fetching Values from URL
echo "Selected Row number is ".$selected2.".";
mysqli_close($connection); // Connection Closed.
?>
I have tried a few things but have so far been unsuccessful in getting the new window to load with the value of the radio button passed. Currently, the window loads, but the new window only displays the echo text, no variable. When I run with the alert popup, the data shows me the value of the selected row but it does not seem to be posting to the new page prior to the window.open command. Any tips would be appreciated, or if i'm approaching the problem from a wrong angle, any insights would also be great. I have also tried debugging, thinking I was missing a parentheses or semicolon but I wasn't able to find anything. Thanks
Looks to me like you can get rid of the post statement altogether and just pass the selection to the newly opened window.
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
// only open window if order okayed
if ( confirm("Confirm Order Number to edit: " + selected) ) {
window.open("php/editOrder.php?selected1=" + selected,"Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
}
});
});
php/editOrder.php:
$selected2 = $_GET['selected1'];
echo "Selected Row number is $selected2.";
I have a large form spread over 3 tabs. The tabs are controlled by JS which simply changes the css property display: block to display:none depending what tab you click on.
This form also submits data to 3 different tables via php. When i submit my form at the end of the the 3rd tab some of my data is missing in a table that accepts multiple rows (the other two tables only accept a single row) In this section of the form I let the user add as many "Rooms" as they need. The rooms are just a few selection boxes, and the extra selection boxes are also added with JS. When i submit my form only the first "room" is added to the table.
I am positive every thing is working as if I remove the tabs it works perfectly or even if i add all three sections of the form to one tab it works. Below is the PHP that inputs the rooms and loops depending how many there are. Sorry this is a very large form so i dont want to just stick it all in, but it is all very simple and all working. Please let me know if I should add any other part of my code if that helps.
$level = $_POST['level'];
$room_type = $_POST['room_type'];
$width = $_POST['width'];
$length = $_POST['length'];
$num_rooms = count($level);
for($x=0;$x<$num_rooms;$x++)
{
$room_insert = mysqli_query($dbcon, "INSERT INTO listing_rooms (Listing_ID, Level, Type, Length, Width) VALUES ('$listing_id', '$level[$x]', '$room_type[$x]', '$length[$x]', '$width[$x]')") or die(mysql_error());
}
To trigger this I have an if(isset()) just above this. Thanks for any help.
This is the JS that shows and hides the tabs...
function showHideTab(tab_id) {
if (tab_id == 'details_tab'){
document.getElementById('listing_details').style.display='block';
document.getElementById('listing_info').style.display='none';
document.getElementById('photo_upload').style.display='none';
}else if (tab_id == 'info_tab') {
document.getElementById('listing_info').style.display='block';
document.getElementById('listing_details').style.display='none';
document.getElementById('photo_upload').style.display='none';
}
else if (tab_id == 'upload_tab') {
document.getElementById('photo_upload').style.display='block';
document.getElementById('listing_info').style.display='none';
document.getElementById('listing_details').style.display='none';
}
}
As I thought this was a very simple error. As i said I have 3 divs being shown or hidden by JS. My issue was I had my opening FORM tag inside my first div!
I still dont know why everything other then the array of "rooms" worked fine regardless of where the opening form tag was, and even the array held the first value?
I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];
So I'm trying to create a webpage where the user puts in there course information. There is an add button on the page, that adds another text field for them if they need more fields.
Once the Add button is pressed, the page is reset and all of the information that has been previously entered is gone. I could save the information in an array, and when or if the the add button is pressed save the information into an array, and re populate the fields using what was stored in the array.
My question is: Is there a way to refresh a page, and keep the information in the text fields, without taking the long process mention above, is there some attribute that I can use that will not delete information that has been previously entered into ?
If you code HTML5, you can use localStorage with a fallback to cookies. Also, if the information should be removed after session end, then you may use sessionStorage instead.
You can use ajax i think...it runs in background no page reload is done.
Assuming this HTML:
<form id="course-info-form" action="submit-course-info.php" method="post">
Professor name: <input type="text" name="professor"><br>
Additional info:<br>
<input type="text" name="additional0"><br>
<input type="submit" value="Submit">
</form>
<br>
<button id="add-button">Add Field</button>
<!-- Use jQuery for DOM manipulation -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
With JavaScript / jQuery:
var courseInfoForm = $('#course-info-form');
var addButton = $('#add-button');
// Keep track of how many fields there are, so each can have a unique "name" attribute
var additionalFieldsAdded = 1;
// Whenever "Add Field" is clicked, create another input field
addButton.on('click', function() {
var newInput = $("<input>", {
type: "text"
name: "additional" + additionalFieldsAdded
});
courseInfoForm.append(newInput, "<br>");
additionalFieldsAdded += 1;
});
I'm not very good at PHP. In your PHP script, make a while loop that checks to see if isset($_POST['additional0']), and additional1, additional2, etc, until you are sure that there were no more additional fields passed. Then store all those additional details into an array, and handle it how you see fit.
As for your original question, I recommend using my solution instead. It's better to avoid unnecessarily reloading the page, if all you're doing is simply adding a new form each time.
I suppose you could capture the information that was "tentatively-submitted" when the "Add Field" button is clicked, and then in your PHP script loop through all the additional fields and create 1 more input element each time another field is added, and set the value attribute of each "old" input element to whatever was "tentatively-submitted."
So, to answer your question, you can set the default value of an input field (server-side) with:
// add-course-information.php
<?php
$addingField = false;
// Check for the optional "?do=addfield" parameter
if (isset($_POST['do']) && $_POST['do'] == 'addfield') {
$addingField = true;
$fields = array();
$nextField = 'additional' . count($fields);
// Get each piece of POSTed field data
while (isset($_POST[$nextField]) && $_POST[$nextField] != '') {
array_push($fields, $_POST[$nextField]);
$nextField = 'additional' . count($fields);
}
}
?>
<!-- Silly HTML! -->
<?php
// If adding a field, recreate and repopulate all previous fields
if ($addingField) {
for ($i = 0; i < count($fields); i++) { ?>
<input type="text" name="additional<?= $i ?>" value="<?= $fields[$i] ?>">
<?php } ?>
<input type="text" name="additional<?php echo count($fields) + 1 ?>">
<?php }
// Otherwise, show the default additional field
else { ?>
<input type="text" name="additional0">
<?php } ?>
<!-- More awesome HTML! -->
That might work... (Currently untested.)
What that page is supposed to do (if it works) is:
On default, give the user his initial setup, with just 1 additional input field, "additional0".
When the user clicks "Add Field," ?do=addfield should be POSTed to add-course-information.php (you can write that part), and when this page receives the do=addfield parameter, then it knows to loop through all the submitted additional fields, and store them each into an array, and then afterwards output all the submitted data back into another loop's-worth of dynamically generated <input> elements.
But I think that that would be much more complicated, and unnecessarily increase the processing your server has to do. It could even be abused if someone was to hammer the "Add Field" button hundreds of thousands of times a minute, eventually making your for-loops iterate millions of times... (Unless you imposed a limit on the maximum number of fields, which would be easy.)
However, you might as well leverage the client's processing power if it's available.