I need to update one dropdwonlist without reload the page, I mean, I have a form where I add the elements that I need, then I have another form where I have the dropdownlist conected to my database but if I do not have the element I need to select, I have to add it from the other form, but the problem is that i need to reload the page in order to the dropdownlist show the new element then I loose the data I was typing.
I wish to know a way to update the dropdownlist without reload the page.
Im using php and mysqli my code is simple:
<form action="edit_col_exe.php" method="post">
<p><label>Add Element:</label>
<input autofocus type="text" name="elemnt" class="input" required />
</p>
<table>
<tr>
<td><input type="submit" name="Save" value="Save" /></td>
</tr>
</table>
</form>
Form2:
Select Element
query("select * from Elements order by Element asc") or die("fail");
echo "Select an option";
while($reg=$con ->fetch_assoc()){
echo "";
echo $reg['Element'];
}?>
I hope someone can help me!
regards!
Use Ajax (I prefer jQuery) and remove your form.
JS
function addElement(){
// get new name
var name = $("#newElementsName").val();
// create ajax call
$.ajax({
type: "POST",
url: "edit_col_exe.php", // URL to php script
data: { // post data for php script (I use the data from your form (including the typo))
elemnt: name,
save: 'Save'
},
success: function(data){
// this function will be called when php script run successful (HTTP-Status 2xx)
// Clear the input filed
$("#newElementsName").val('');
// Add new name to dropdown
$("#elements").append("<option>"+name+"</option>");
}
});
}
HTML
<div>
<p><label>Add Element:</label>
<input autofocus type="text" id="newElementsName" class="input" required />
</p>
<table>
<tr>
<td><button type="button" onclick="addElement()">Save</button></td>
</tr>
</table>
</div>
<div>
<select id="elements" size="1">
</select>
</div>
I solved my problem and I want to share with you my solution, its simple:
setInterval(function(){
$('#searchelement').load('addelements.php');
});
<p><label>Element</label>
<select id="searchelement" name="element" required />
</option>
</select></p>
So everytime I add an element at 'addelements.php', I can search the new element in the select list.
Related
Improper Form Submission
For the below code snippet, I am not able to get any value for the input hidden field in my request.
In the form table created:
It is working fine, if I click the Approve button of the first row.
Issue is faced when Approve button of intermediate row is clicked.
There is no any value passed in the request for the id="hidinput";
<script>
function fetchID(){
var contentID = document.getElementById("testID").innerHTML;
document.getElementById("hidinput").value=contentID;
}
</script>
<%for (APPL_Testimonial_Txn testimonial_Txn : results) {%>
<tr>
<form action="<%=approve.toString()%>" method="POST">
<td id="testID"><%=testimonial_Txn != null ? testimonial_Txn
.getTestimonialId() : ""%></td>
<input type="hidden" name="rowId" id="hidinput" value=""/>
<td><button class="button-continue ContinueNew" type="submit"
onclick="fetchID()">APPROVE</button></td>
</form>
</tr>
<%}%>
Please find below screen capture of the table.
As per the code above, there is no way to figure out the row in which approve button was clicked. You can pass the testimonial Id to a fetchID function.
<script>
function fetchID(contentID){
document.getElementById("hidinput").value=contentID;
}
<script>
<tr>
<form action="<%=approve.toString()%>" method="POST">
<td><%=testimonial_Txn != null ? testimonial_Txn
.getTestimonialId() : ""%></td>
<input type="hidden" name="rowId" id="hidinput" value=""/>
<td><button class="button-continue ContinueNew" type="submit"
onclick="fetchID('<%=testimonial_Txn != null ? testimonial_Txn
.getTestimonialId() : ""%>')">APPROVE</button></td>
</form>
</tr>
<%}%>
Thanks for the suggestion.
I changed the position of form tags, means kept form tag outside the loop construct keeping form as unique and it worked. :)
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.
I have a form with text boxes and drop down menus. One of the drop down menus is Dependant on the value of another, e.g. InventoryUsage is dependent on the value in InventoryID.
So far I have done the entire site using PHP since I do not know JavaScript, though I found a JavaScript function that can get the value entered in InventoryID, but I cannot use that value in the PHP since PHP is server-side.
What I need to do is change the second dropdown options depending on that of the first dropdown. Then submit the data as I would with a normal form.
Edit:
I used ob_start and included the tpl page and sent all the variables to the page which were pulled from the database prior. All the variables have the same index meaning that InventoryID['0']=ID3456 corresponds to InventoryUsage['0']=60. Therefore when InventoryID is ID3456 i would like to display the Number located at InventoryUsage['0']. I hope this adds some context to the problem.
The index is determined by the php variable $i in my code snippet. The $i would be changed to match the index of the InventoryID field. Say the value of InventoryUsage is 20 then I want to display numbers 1 to 20.
Snippet of code below:
<label>TypeOfSurgery</label> <input type="text" name="TypeOfSurgery" size="35" value="" />
<label>CauseOfSurgery</label> <input type="text" name="CauseOfSurgery" size="35" value="" />
<label>AnaesthesiaUsage</label> <input type="text" name="AnaesthesiaUsage" size="35" value="" />
<label>SurgeryOutcome </label> <input type="text" name="SurgeryOutcome" size="35" value="" />
<label>RecoveryTime</label> <input type="text" name="RecoveryTime" size="35" value="" />
<label>Stages </label> <input type="text" name="Stages" size="35" value="" />
<label>EmployeeName </label> <p>
<select name="EmployeeName">
<option value=""></option>
<?php
for($i=0;!empty($EmployeeName[$i]);$i++)
echo '<option value="">'.$EmployeeName[$i].'</option>';
?>
</select><p>
<label>Cost</label> <input type="text" name="Cost" size="35" value="" />
<label>InventoryID</label> <p>
<select name="InventoryID">
<option value=""></option>
<?php
for($i=0;!empty($InventoryID[$i]);$i++)
echo '<option value="">'.$InventoryID[$i].'</option>';
?>
</select><p>
<label>InventoryUsage </label> <p>
<select name="InventoryUsage">
<option value=""></option>
<script type="text/javascript">
var model= document.getElementById('InventoryUsage');
</script>
<?php
//if inventory in
for($i=0;!empty($InventoryUsage[$i]);$i++)
echo '<option value="">'.$InventoryUsage[$i].'</option>';
?>
</select><p>
In order to populate the InventoryUsage dropdown you need to use JavaScript.
You can use the onChange event for the dropdown InventoryID then fetch the corresponding values via Ajax.
$('#InventoryID').change(function () {
var value =$(this).val(); // selected InventoryID option
//get InventoryUsage values
$.ajax({
method: "POST",
url: "myfile.php",
data: { data: value },
success: function(data){
// Populate new dropdown $("#InventoryUsage")
// this is an example without knowing what is the returned data
var Newoptions = [];
for (var i = 0; i < data.length; i++) {
Newoptions.push('<option value="',
data[i].someValue, '">',
data[i].someName, '</option>');
}
$("#InventoryUsage").html(Newoptions .join(''));
}
});
});
});
then in your PHP file you need to handle the $_POST['data'] , then query your database and return the drop-down options( Arrays ) that will be populated above...
edit :
If you are sure that this index matches the Inventory_Usage and that the InventoryUsage dropdown has previously been populated then
you could try to select the InventoryUsage option using the index of the InventoryID dropdown on change and load events...
try adding this function to you select :
<select name="InventoryID" onChange="set_inventory_usage()"></select>
then add this script to your page's HEAD section..
<head>
<script type="text/javascript">
function set_inventory_usage(){
// Change to getElementById if it is the ID not the name
var Inventory_ID = document.getElementsByName('InventoryID')[0];
var Inventory_Usage = document.getElementsByName('InventoryUsage')[0];
// returns the index of the selected option in the InventoryID dropdown
var InventorySelected = Inventory_ID.selectedIndex ;
// Sets the Usage dropdown to the same index as the Inventory selected option
Inventory_Usage.selectedIndex = InventorySelected ;
}
window.onload = set_inventory_usage ;
</script>
</head>
Option 1: Without JavaScript, the best option is to add an onchange to your first dropdwon list, and when a value is selected submit the form. Since the form is not complete, and only the dropdown value and elements before that are passed, you can set a condition to query the database, get values based on first drop down and reload the form with those options. IThere is nothing wrong with this solution if done properly but to be honest I perfer to do such things with Ajax, hence option 2 below.
Option 2: Learn some JavaScript and use Ajax (Use caution when using other people's scripts in your system)
Edit: Perhaps instead of wring Ajax code from scratch, use jQuery where most things are already done for you. Learning jQuery is very useful if you are going to do web development
I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}
I have an HTML table with dynamically generated rows (using MVC3's EditorFor). Users fill in the data in the table (row by row), then submit the form to the server (via MVC3 HTML form). Users can delete a row by pushing a button that calls $(tableRow).remove() on the TR element, and then calls an async server method that removes the row from the database.
I've found that if I have say 5 rows in my table and I delete the third one then submit, the server method receives rows 1 and 2, but looses the other rows (the original 4th and 5th rows).
I've tried searching online as to why the postback would receive the first two rows and miss the last two, but all the answers I could find revolved around JQuery posts, which I'm not using.
Any help or direction would be great, please let me know if I need to clarify anything.
EDIT: adding code from my project that applies to the question. if you need more code for context, let me know and I'll add it.
//////////////// VIEW ////////////////
// model info and initialization logic
#using (Html.BeginForm("EditTimesheet", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id = "editTimesheet" }))
{
#Html.ValidationSummary(true)
<fieldset>
<table width="100%">
<tr>
<td colspan="14" align="right">
// lots of code
</td>
</tr>
#Html.EditorFor(m => m.Rows)
<tr>
<td colspan="14" align="right">
// lots of code
</td>
</tr>
// closing statements
//////////////// EditorFor ////////////////
// model info and initialization logic
<tr class="timesheet-row">
<td>
<a href='#'>
<img src='#Url.Content("~/Content/Images/delete.gif")'
width='17' height='17' style='border: 0;'
onclick="DeleteRow(this, #Model.RowId)" />
</a>
</td>
// other td's
</tr>
//////////////// JS file ////////////////
function DeleteRow(box, rowId)
{
$(box).closest(".timesheet-row").remove();
// HACK: despicable, detestable HACK!
var url = deleteRowUrl;
url += '?rowId=' + rowId;
var ajaxData = {
type: "POST",
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: null,
success: null,
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
}
};
$.ajax(ajaxData);
}
When you delete a row you are creating holes in the indexes of the names in the collection and the default model binder stops working because you no longer respect the expected format.
So instead of having the following sequential values:
<input type="text" name="Items[0].Id" value="1" />
<input type="text" name="Items[1].Id" value="2" />
<input type="text" name="Items[2].Id" value="3" />
<input type="text" name="Items[3].Id" value="4" />
<input type="text" name="Items[4].Id" value="5" />
if you delete the third row with $(tableRow).remove() on the TR element you end up with:
<input type="text" name="Items[0].Id" value="1" />
<input type="text" name="Items[1].Id" value="2" />
<input type="text" name="Items[3].Id" value="4" />
<input type="text" name="Items[4].Id" value="5" />
See the problem?
Here's an article which illustrates how to solve this problem by using a custom helper called Html.BeginCollectionItem and which uses GUIDs in the names of the input fields for the collection instead of integer indexes. Also checkout Phil Haacks article about the syntax that the default model binder expects your fields to be named. There's a section towards the end which is called Non-Sequential Indices in which he covers how this could be done.
Sounds like part of your form is being deleted.
Inspect the DOM
find your form
delete a row and see what changes