I have some javascript that pulls some mysql data using xmlhttp.responsetext. I've been using it to populate form data for a drop down box and it has been working well. However, I have a need to add a second dropdown menu in the form and it is not working right.
What is happening is both dropdowns are populating with data from 2 different tables when each dropdown should only be getting its data from its respective table.
Could use some help figuring this out, thanks.
Here is the javascript code.
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement(div);
newdiv.innerHTML = "<table><tr><td>Line Item " + (++counter) + "</td></tr><tr><td width='190'>Item: <select name='item[]'>" + xmlhttp.responseText.split( "[BRK]" ) + "</select></td><td width='100'>Qty: <input name='quantity[]' type='text' size='2' /></td><td width='500'>Description: <input name='description[]' type='text' size='60' /></td><td width='150'>Amount: <input name='amount[]' type='text' size='6' /></td><td>Tax Rate: <select name='taxrate[]'>" + xmlhttp.responseText.split( "BRK" ) + "</select></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
And here is php.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
$result2 = mysql_query("SELECT * FROM salestax");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
echo "[BRK]";
while($row2 = mysql_fetch_array($result2)) {
echo "<option value=\"".$row2['amount']."\">".$row2['name']."</option>";
}
echo "[BRK]";
?>
When you split a string, you get an array. I suppose you want to do this:
var splitResponse = xmlhttp.responseText.split( "[BRK]" );
var firstDropdownContent = splitResponse[0];
var secondDropdownContent = splitResponse[1];
Then use the two new variables to build your HTML.
Related
My goal is to submit a set of variables to my AJAX function from with in a while loop in php. This is my first shot at using AJAX, so please excuse if it is messy, and not close to correct. I appreciate any assistance.
PHP FORM:
x=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['col1'];
$ad = $row['col2'];
cho '<form id="msu_form">';
echo "<tr><td>{$ad}</td>";
echo "<td>";
$query2 = "SELECT col1,col2 FROM table WHERE notes = 'x'";
$result2 = mysql_query($query2);
$count2 = mysql_num_rows($result2);
if($count2 > 0)
{
echo '<select class="Primary" name="primary" onchange=doAjaxPost()>';
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=".$row2['col1'].">".$row2['col2']."</option>";
}
echo "</select>";
}else
{
echo "Blah";
}
echo "</td>";
echo "<td>";
$query3 = "SELECT col1,col2 FROM table2 WHERE notes = 'y'";
$result3 = mysql_query($query3);
$count3 = mysql_num_rows($result3);
if($count3 > 0)
{
echo '<select class="Secondary" name="secondary">';
while($row3 = mysql_fetch_array($result3))
{
echo "<option value=".$row3['col1'].">".$row3['col2']."</option>";
}
echo "</select>";
}else
{
echo "Bah";
}
echo "</td>";
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
//echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>";
echo '</form>';
$x = $x+1;
}
So what happens is every time I change any of the "primary" select boxes on the screen, I get the value of the variables on the first line only. I want to receive the values of the form from the select box. I have tested it via a button, that submits the form it is commented out, but that button submits all the correct information to the page, but I don't want to submit the data every time. Is there a way to accomplish my goal?
Thanks - below the ajax if it helps with an answer.
<script>
function doAjaxPost() {
// get the form values
var primary = $(this).val();
var secondary = $(this).parent().next().child('.Secondary').val();
var hidden = $(this).parent().nextAll('.ID').val();
//var desc = $(this).parent().nextAll('#desc').val();
$.ajax({
type: "POST",
url: "functions/database_write.php",
data: $('#msu_form').serialize(),
//data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary,
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
First, in your php code change the following 4 lines (using id)
echo "<select id=Primary name=primary onchange=doAjaxPost()>";
echo "<select id=Secondary name=secondary>";
echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>';
to (using class) edited
echo '<select class="Primary" name="primary" onchange="doAjaxPost(this)">'; //added (this)
echo '<select class="Secondary" name="secondary">';
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
Then, in your javascript code, change
function doAjaxPost() {
var primary = $('#Primary').val();
var secondary = $('#Secondary').val();
var hidden = $('#ID').val();
var desc = $('#desc').val();
to edited
function doAjaxPost(sel) { // added (sel)
var primary = $(sel).val(); //changed to $(sel)
var secondary = $(sel).parent().next().children('.Secondary').val(); //changed to $(sel) and changed to children()
var hidden = $(sel).parent().nextAll('.ID').val(); //changed to $(sel) and changed to nextAll()
var desc = $(sel).parent().nextAll('#desc').val(); //changed to $(sel) and changed to nextAll()
If everything works fine when submitting normally, then probably you are generating the ajax data wrong, instead give your form an id:
echo '<form id="myform">';
Then serialize the form to get the correct data:
function doAjaxPost() {
$.ajax({
type: "POST",
url: "functions/data.php",
data: $('#myform').serialize(),
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
EDIT Ok you edit has cleared things up a bit, I didn't notice you have multiple forms.
Using the same doAjaxPost function as above, change the data property to:
data: $(this).parents('form').serialize();
I tried putting this code:
<script>
function myfunc()
{
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert(xmlhttp.responseText);
else
alert("Something went wrong!");
}
var tbl = document.GetElementByID("tbl_users");
var str="";
var tid;
var isActive;
for(x=0; x=tbl.rows[x]; x++)
{
tid=0;
isActive="true";
if(tbl.cells[1].checked)
tid=1;
else
tid=2;
if(tbl.cells[6].checked)
isActive="true";
else
isActive="false";
str="uid="+tbl.cells[0].value+"&tid="+tid+"&firstName="tbl.cells[2].value+"&lastName="+tbl.cells[3].value+"&userName="+tbl.cells[4].value+"&passWord="+tbl.cells[5].value+"&isActive="+isActive;
xmlhttp.open("POST", "save.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(str);
}
}
</script>
...inside the tags of a web page I'm making, as I only followed some tutorials which shows the same. Here's the code for my HTML:
Users
<!--JS codes above here-->
</head>
<body>
<form>
<table align='center' border='1' name='tbl_users'>
<tr>
<td>UID</td>
<td>Admin</td>
<td>First Name</td>
<td>Last Name</td>
<td>Username</td>
<td>Password</td>
<td>Active</td>
</tr>
<?php
while($row = mysql_fetch_array($table))
{
echo "
<tr>
<td><input type='text' name='uid' value='".$row['uid']."' disabled/></td>";
if($row['tid'] == 1)
echo "<td><input type='checkbox' name='tid' value='1' checked/></td>";
else
echo "<td><input type='checkbox' name='tid' value='2'/></td>";
echo " <td><input type='text' name='firstName' value='".$row['firstName']."' /></td>
<td><input type='text' name='lastName' value='".$row['lastName']."' /></td>
<td><input type='text' name='userName' value='".$row['userName']."' /></td>
<td><input type='text' name='passWord' value='".$row['passWord']."'/></td>";
if($row['isActive'] == 0)
echo "<td><input type='checkbox' name='isActive' value='true' checked/></td>";
else
echo "<td><input type='checkbox' name='isActive' value='false'/></td>";
echo "</tr>";
}?>
<tr>
<td colspan='7' align='right'><input type='button' value="Save" onclick='myfunc()'/></td>
</tr>
</table>
</form>
</body>
Now, I've read possible solutions for that like:
- putting it inside a $(document).ready() call
- putting the JS code inside the tag, just below the closing tag
But still, it won't work.
I have tried simple JS codes like:
<script> function myfunc(){alert("hello world!");} </script>
...with the same solutions, and only the 2nd method worked for this.
Any idea?
I see at least two problems:
JavaScript is case-sensitive, and var tbl = document.GetElementByID("tbl_users"); should be var tbl = document.getElementById("tbl_users"); (note the g and d in getElementById).
In this line:
str="uid="+tbl.cells[0].value+"&tid="+tid+"&firstName="tbl.cells[2].value+"&lastName="+tbl.cells[3].value+"&userName="+tbl.cells[4].value+"&passWord="+tbl.cells[5].value+"&isActive="+isActive;
...you're missing a + after "&firstName=" and before tbl.cells[2].value. Your console should be telling you that you have an Unexpected identifier.
The for(x=0; x=tbl.rows[x]; x++) should be for(x=0; x<tbl.rows[x]; x++).
You need a comparison operator in the 2nd section.
Here is a clean up version. Remember you should always use curly braces on the end of your if lines because the JS compiler likes to insert ; otherwise.
function myfunc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert(xmlhttp.responseText);
} else {
alert("Something went wrong!");
}
}
var tbl = document.getElementById("tbl_users");
var str = "";
var tid;
var isActive;
for (x = 0; x < tbl.rows[x]; x++) {
tid = 0;
isActive = "true";
if (tbl.cells[1].checked) {
tid = 1;
} else {
tid = 2;
}
if (tbl.cells[6].checked) {
isActive = "true";
} else {
isActive = "false";
}
str = "uid=" + tbl.cells[0].value + "&tid=" + tid + "&firstName="
+ tbl.cells[2].value + "&lastName=" + tbl.cells[3].value + "&userName="
+ tbl.cells[4].value + "&passWord=" + tbl.cells[5].value
+ "&isActive=" + isActive;
xmlhttp.open("POST", "save.php", true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send(str);
}
}
I'm working on an invoicing system. I'm using javascript to add line items as needed however the added line items are not posting when I click submit. I'm thinking it is probably an issue with div somewhere but I cannot seem to find it or get it to work. I'm posting my code for help. Thanks.
Here is my form.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
$result = mysql_query("SELECT company, first, last FROM customer") or die (mysql_error());
?>
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement('div');
newdiv.innerHTML = " Entry " + (++counter) + " <br /><table><tr><td>Item: <select name='item[]'>" + xmlhttp.responseText + "</select></td><td>Qty: <input name='quantity[]' type='text' size='5' /></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
<form id="createInvoice" method="post" action="docreateinvoice.php">
<table>
<tr><td>Customer</td><td><select name="company">
<?php while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['company']."\">".$row['company']." (".$row['first']." ".$row['last'].")</option>";
}
?>
</select></td></tr>
</table>
</div>
</div>
<div id="container">
<div class="content">
<div id="dynamicInput">
Entry 1<br /><table><tr><td>Item: <select name="item[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select></td><td>Qty: <input name="quantity[]" type="text" size="5" /></td></tr></table><br />
</div>
<br /><input type="button" value="Add Line Item" onClick="addInput('dynamicInput');">
</div>
</div>
<div id="container">
<div class="content">
<input type="submit" name="submit" value="Create Invoice" />
</form>
<?php
include $_SERVER['DOCUMENT_ROOT']."/includes/footer.php";
?>
This next piece of code is dropdownquery.php. This is what gets the dropdown box data in the javascript. Big thanks to #NickSlash for figuring this out in the javascript.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
And finally, this is my docreateinvoice.php which I post to.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$company = mysql_real_escape_string($_POST['company']);
foreach($_POST['item'] as $i => $item)
{
$item = mysql_real_escape_string($item);
$quantity = mysql_real_escape_string($_POST['quantity'][$i]);
//mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error());
print_r ($company);
print_r ($item);
print_r ($quantity);
}
//echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
You might notice in the form that the first entry is not javascript. This does indeed post, just not any additional line items generated from the javascript function.
Thanks for any help.
As I had said in the comments, it seems having divs for display formatting purposes has a negative effect when used within forms utilizing javascript.
I want to insert values from another form field in one text area. There are multiple fields, each placed in different forms with different submit buttons. Whenever the button is clicked, the values in that form should be inserted into the text area.
The fields are generated in an array. I have assigned the same id name for every field. This is to make every field's values belong to that textarea. My problem is, only the first field insert its value into the textarea when I click its button.Other fields not working. How could I fix this?
Here is the code:
<script type="text/javascript">
window.onload = function() {
btn1 = document.getElementById("btnInsertText1");
myText1 = document.getElementById("myTextArea1");
text1 = document.getElementById("textToInsert1");
btn1.onclick = function(){
insertAtCursor(myText1, text1.value);
}
}
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "
SELECT *
FROM reftext1_objective
WHERE projectid='$id'";
$refresult = mysql_query($ref);
while($row = mysql_fetch_array($refresult))
{?>
<form>
<input id="textToInsert1" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" id="btnInsertText1" value="<<" />
</form><br><?php
}
As stated in my comment on the question, the problem is due to the duplicated element ids in the loop in your PHP code. To fix it, try this:
<script type="text/javascript">
$(function() {
var textarea = document.getElementById("myTextArea1");
$(".button").click(function() {
var $parentForm = $(this).closest("form");
var text = $(".insert-text", $parentForm).val();
insertAtCursor(textarea, text);
});
});
function insertAtCursor(myField, myValue) {
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
}
else {
myField.value += myValue;
}
}
</script>
<textarea id="myTextArea1" name="update" cols="85" rows="22">
Testing. Values from another field will be inserted here.
</textarea>
<?php
$ref = "SELECT * FROM reftext1_objective WHERE projectid = '$id'";
$refresult = mysql_query($ref);
while ($row = mysql_fetch_array($refresult))
{ ?>
<form>
<input class="insert-text" type="text" value="<?php echo $row[$text];?>" readonly="true">
<input type="button" class="button" value="<<" />
</form><br>
<?php }
?>
Example fiddle
I have a code in which i am sending the values from a form to php page where the query lies and for sending the values i am using $.post of jquery everything is going good. I am resulting a table and a button now i want that button will work and 1 of the table column has the radio button list so i want that button will take the radio id of that perticular row on click but my button is not working so please guide me how i can do this my code is here
my javascript function
function searchDetail(searchName) {
var textName = searchName + "Text";
var inputText = $('#' + textName).val();
var formName = searchName + "Form";
if (inputText === "") {
$('#' + textName).css("border", "2px solid red").fadeIn(4000);
}
else {
$('#' + textName).css("border", "1px solid #8dd7f6").show(2000);
$('#searchBox').fadeIn(1000);
$.post('../search/delete' + searchName + '.php', $('#' + formName).serialize(), function(result) {
$('#searchBox').html(result);
})
}
}
my php code
if ($count == "0") {
echo "There is no data with $search = ".$searchKeyword;
} else {
$color = 2;
echo "<table cellspacing='0px' cellpadding='7px'><thead><tr><th>#</th><th>book Id</th><th>book Name</th><th>book Writer</th><th>book Price</th><th>Availability</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
$checkBook = $row['booktotal'] - $row['bookremain'];
if ($checkBook == 1) {
$status = "Yes";
} else {
$status = "No";
}
if ($color % 2 == 0) {
echo "<tr class='even'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = $color + 1;
} else {
echo "<tr class='odd'><td><input type=radio name=group1 value=".$row['bookId']."></td><td>".$row['bookId']."</td><td>".$row['bookName']."</td><td>".$row['bookWriter']."</td><td>".$row['bookPrice']."</td><td>".$status."</td></tr>";
$color = 2;
}
}
echo "</tbody></table><br><input type=button value=Delete id=deleteButton onclick='check()'> <script type=text/javascript> function check(){alert(Hello);}</script>";
mysqli_close($con);
}
?>
my html code
<body>
<div id="deleteFormTable">
<span id="headerFont">Enter Information to Delete Book</span><br><br>
<form id="bookSearchForm" name="bookSearchForm"><label>Search Book:</label> <input type="text" id="bookSearchText" name="bookSearchText"/> <select id="bookSearchOption" name="bookSearchOption"><option id="bookSearchId">Id</option><option id="studentSearchName">Name</option></select> <input type="button" value="Search" id="bookSearch" name="bookSearch" onclick="searchDetail(this.id)"></form>
</div>
<div id="searchBox">
<center><div id="searchLoadBox"><img src="../images/loadings.gif" alt="..."></div></center>
</div>
</body>
OK, I think I know what you are asking.
You have a list of items with radio boxes next to them, once the user clicks one and then clicks the button, you want the "value" tied to that radio button.
If that is the case, you can use this to find the value of the "Checked" radio group.
$("#deleteButton").click(function()
{
var bookId = $("input[#name='group1']:checked").val();
}