I have two text box which is storing in database using AJAX. But I want to return back the new added row in table structure.
I am using this concept in add product to sell . when I want to add an item then it will be display in a tabular grid format.
This is my AJAX code.
var xmlHttp
function newVendorGridInital()
{
//alert("HI");
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{alert ("Browser does not support HTTP Request"); return }
var item= document.getElementById('itemcode').value;
var url="ajax_NewVendorGrid.php"
url=url+"?itm="+item; // For multiple value send.
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=newVendorGrid
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function newVendorGrid()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("GridRuntimeData").innerHTML=xmlHttp.responseText;
> > > I didn't understand how to target the id field > > > GridRuntimeData
}
}
In my html page I have created a table structure i.e. head part.
In my PHP file I am returning the entire inserted row in a html row format using echo statement.
<?php
echo "<tr><td>".$item."</td></tr>";
?>
and my doubt is how to show that row in table. If I write entire table structure in php code then it will be working fine. But i don't want do all the time to return entire row.
Please Help me.
You can dynamically add rows to a table with Javascript like this:
var table = document.getElementById("mytable");
var td = document.createElement('td');
td.innerHTML = 'new row';
var tr = document.createElement('tr');
tr.appendChild(td);
table.appendChild(tr);
jsFiddle demo here
Related
There are probably other similar posts, but here goes nothing.
I am currently reworking on an existing site and some of the changes required involves column and row highlighting, like here (tutorial / demo).
Since there are several web pages to go through, I would like to have some kind of shortcut to dynamically add <colgroup></colgroup> like in the example without having to go through each page and table by hand.
I've considered php's preg_replace function, but I doubt that's the simplest way to go around it. In an optimal scenario, I would be able to verify if there is an existing <colgroup></colgroup> array for each column.
Using jQuery you could dynamically prepend the <colgroup></colgroup> to each table before your highlight script. Something like -
if($("table > colgroup").length == 0){ // If the table does not have <colgroup></colgroup>
var colCount = 0;
$('tr:nth-child(1) td').each(function () { // Get the count of table columns
if ($(this).attr('colspan')) { // if there is a <td colspan>
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
var colgroupList = '';
for (i=0;i<colCount;i++){ // Add a <colgroup></colgroup> for each <td>
colgroupList += '<colgroup></colgroup>';
}
$("table").prepend(colgroupList);
}
$("table").delegate('td','mouseover mouseleave', function(e) {
...
jsFiddle example http://jsfiddle.net/BGR22/1/
Edit
If you have multiple tables on a page, you need to add a selector to only get the parent table -
var $table = $(this).closest("table");
So now your $("table").delegate() would look like
$("table").delegate('td','mouseover mouseleave', function(e) {
var $table = $(this).closest("table");
if (e.type == 'mouseover') {
$(this).parent().addClass("hover");
$table.children("colgroup").eq($(this).index()).addClass("hover");
} else {
$(this).parent().removeClass("hover");
$table.children("colgroup").eq($(this).index()).removeClass("hover");
}
});
Updated jsFiddle - http://jsfiddle.net/BGR22/3/
and with 3 tables - http://jsfiddle.net/BGR22/4/
just a quick one im looking to populate three drop down boxes to filter data and each one of them is going to affect the next.
what i want is for
Drop down 1 has company
once drop down 1 is selected the second drop down is populated with the branches for that company
once selected the third drop down is populated by the staff members for that company in that branch then when i press search it should pull the data for that 1 staff member. all of the information is in one table
the table i have is called "stafflist"
the columns are "company", "branch" and "staffname" each staff member has an autonumber id field which i use as a lookup called "staffID"
Thank you for any help
Regards
Slowie
Lets take an easy example, This is a javascript solution. I'm using this and it works perfectly fine. This script work in case if you select a country it populates its corresponding cities in the second dropdown. You can take some idea and use this for your case where you can deal with three dropdowns respectively.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure. In your case you have to create tables for company, branches and employees.
Hope this helps.
Have you ever heard about AJAX() OR jQuery ? if not then refer those link first; actually for your task you need to use Ajax OR jquery based dropdown boxes. which can make your dream success. :)
refer below link for your solution.
If any help needed you can feel free to ask me..
EDIT As per your commnet :
Step-1:- "SELECT company_id,company_name from company_table WHERE $condition ";
Step-2:- Fill first drop down box with record of first query set.
Step-3:- call jquery.ajax function onchange event of first drop down box in which call one
php page i.e: getRecords.php.
Step-4:- In getRecords.php page you need to get all the Branches of that company by passing company id in ajax and return a record array as response.
Step-5:- Fill second drop down with these records and again onchange event call another jquery.ajax request for final drop down box and do all things same as Step-4.
I think its all steps what you need for. still have any issue let me inform.
Thanks.
I have two drop-down boxes. I want to populate second drop-down box on selection in the first drop-down box. My values are retrieving from database. Is this possible without using php or I need intermediate ajax and php file to get values from first drop-down and populate values file. Or this is possible without using php I mean only using Jquery. Please give me hint to do that.
Suppose I have 2 countries. First is INDIA and second is USA. ON first drop-down I am selecting countries and if first dropdown is selected than second dropdown populate its respective states.
if you encode your data into JSON format, then you can do something like this:
for HTML:
<select name='country' id='country'>
<option value='india'>India</option>
<option value='usa'>USA</option>
</select>
<select name='dates' id='dates'>
</select>
jQuery:
data = {
india: ['2011-03-11','2010-02-01'],
usa: ['2006-03-11','2009-02-01']
}
$('#country').change(function(){
var dateopts = ''
$.each(data[$(this).val()],function(i,v){
dateopts += "<option value='"+v+"'>"+v+"</option>"
})
$('#dates').html(dateopts)
})
Which when the country is changed, will build and populate the options for the second select box.
See the working example here: http://jsfiddle.net/xHxcD/
The above method requires all data to be sent to client side with the initial page request. If you have lots of data, it would be better to receive the data via AJAX. It would be simplest to do this by building an object in PHP with the same data structure as your client side, then use json_encode to convert it into as JSON string and echo it out.
Reading this into your client side would then be as simple as this:
$.ajax('myJsonData.php?country=india',function(jsonData){ data.india = jsonData })
You could do it either way. If you dont want to use ajax, just load every single option into an object. Then when you select something from select #1, populate #2 with the assoicated array of data from your object.
If I were doing it, I wouldn't do it with ajax unless there was a TON of data.
Yes you can do it without using php. For that you've to assign two different states list in Javascript array and base on the selection just change the options in the other select box. As simple as that.
You can assign the javascript array using your serverside scripting language while loading the page if you're using database to store the states.
But do not do this unless you've very small amount data. In your case you've only 2 countries so you can go ahead with it.
Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.
Reference to my answer: Cascade Dropdown List using jQuery/PHP
Hope this helps.
I have a HTML table with text in the cells like so:
<tr><td>HELLO</td></tr>
I then have a text area like so:
<input type="text" id="txt_message" name="txt_message"
I want to make it so that when you click inside the table cell, the data (in this case the word 'HELLO') is inserted into the text area (so the user does not have to type it).
I dont know if this is possible, but I am guessing it is and it is 'probably' something in JavaScript.
If anybody has any advice that would be great, Thank you :)
[Working demo]
var textbox = document.getElementById('textbox');
var table = document.getElementById('table');
// add one event handler to the table
table.onclick = function (e) {
// normalize event
e = e || window.event;
// find out which element was clicked
var el = e.target || e.srcElement;
// check if it's a table cell
if (el.nodeName.toUpperCase() == "TD") {
// append it's content to the textbox
textbox.value += (el.textContent || el.innerText);
}
}
Note: all the conditional assignments with || are for cross-browser compatibility.
Here is Working demo using jquery.
To get the value, use innerhtml and a span, more here: http://www.vbforums.com/showthread.php?t=339864
To update the textarea you should be able to do something like: document.getElementById ("text_message").value = x;
a simple jQuery snippet, assuming you have 1 textarea and multiple td's to click over
(function() {
var ta = $('#txt_message');
$('td').bind('click.addtextarea', function() {
var text = $(this).html();
ta.val([ta.val(), text].join(' ')); /* this add words */
/* ta.val(text); this print one word */
});
})()
I asked a similar question earlier here, and it got me down the right track, but I am little stumped still. However, now I know how to ask a more educated question.
I have a database I connect to, with a table name of PRODUCTS. Within PRODUCTS are the columns ID, STOCK, SHORTNAME, DESCRIPTION, PRICE and SHIPPING.
If the user clicks a button, I need to send a request to find all the rows in PRODUCTS. I believe the following file.php accomplishes that (DB connect code not show).
$query = "SELECT `ID` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
$num=mysql_numrows($result);
When the user clicks the button, and it gets $num, it then needs to create as many div elements as there are rows. I can do this with for() , but I am not 100% sure how to do it. Also, I am not sure how to do this in Jquery, instead of just JS.
function ajaxFunction(phpFunction){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
for (var i = 0; i < ajaxRequest.responseText ; i++)
//Create Div code here
}
}
var url = "file.php;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
So here are the final questions:
If a user clicks a specific div (#revealProductButton), how do I create as many divs as $num returns?
How do I make those divs that were created display STOCK, PRICE, and SHIPPING from the DB? Each div must display it's own information, not just one div that displays everything.
If the user then clicks one of the divs that were created, how do I then reveal the rest of the information in the DB (DESCRIPTION, etc), but only for the div that was clicked?
How to I write my file.php to work with all this?
The easiest way would be something like this:
function fetchData(){
var url = 'file.php';
// The jQuery way to do an ajax request
$.ajax({
type: "POST",
url: url,
data: "", // Your parameters here. (like "dummy=1&sort=description")
success: function(html){
// html contains the literal response from the server
$("#result").html(html);
}
});
}
The response of the php script will be written directly to #result.
Now on the php side you can just output html:
$result = mysql_query($myQuery);
while ($row = mysql_fetch_assoc($result)) {
echo '<div>'.$row['description'].'</div>';
}
This is just a quick 'n dirty approach. An alternative is to return a json object from the php script and process that further in javascript.
You can go something like this:
for (var i = 0; i < ajaxRequest.responseText ; i++)
{
var div = document.createElement("div");
var doc = document.getElementsByTagName("body")[0];
doc.appendChild(div);
div.setAttribute("id", "div_" + i);
// now some php code to get STOCK, PRICE, and SHIPPING through sql queries
// ...........................
// ...........................
// ...........................
// javascript again
document.getElementById("div_" + i).innerHTML = <?php echo $price, $shipping, etc in any way you want?>;
div.onclick = function()
{
// again php code to get more info like DESCRIPTION
//..................
document.getElementById("div_" + i).innerHTML += '<br /><br />' + <?php echo $description?>;
};
}
Hope that helps.
If the user clicks a button, I need to send a request to find all the rows in PRODUCTS
SELECT `ID` FROM `PRODUCTS`
Note, this query only retrieves the ID values from all records, not all record data. Is this what you want?
To answer your questions:
1) The PHP script should be returning a specfic format, e.g. XML or JSON (the latter is preferred, IMHO). The number of collections returned will dictate how many DIV elements you create, if your intent is to stick each resulting record into a new DIV. Example, a JSON response has a collection (array) with 10 elements. You loop through each element in the array and create N DIV elements based on the array size.
2) Are you sure you want to create a new DIV for these values? Not TR element in a TABLE?
3) You'd format the returning data in such a way that it was initially "hidden", and use an onclick handler for the main DIV element relating that record data to "reveal" the other data. It's all on the page, it's just hidden, you don't need to create a new XHR call.
4) There are many Ajax related tutorials online. Find one and start tinkering. In other words, it's a bit too complex to scratch out in a couple of lines here.
Although I don't normally jump on the JS library bandwagon, you may want to look at jQuery, it will make these tasks a snap. You should understand the underlying JS code and how the request is made, however.
Since you mentioned the jQuery framework, why not consider using javascript templating? It allows you to simply build the divs (and all of their children) in HTML and populate them with arbitrary data whenever you need them.
Go and take a look at http://aefxx.com/jquery-plugins/jqote, it's a jQuery plugin that allows you to do the above mentioned.
You would use it like this in jQuery:
<script type="text/html" id="template">
<![CDATA[
<div class="product">
Product ID: <%= this.id %>
</div>
]]>
</script>
<script type="text/javascript">
// Let's pretend your ajax call returns an array in json notation like so:
// [{"id": "1", "shortname": "Shoe"}, {"id": "2", "shortname": "Shirt"}]
$.ajax({
url: '/file.php',
....
success: function(data) {
$('#template').jqote(data).appendTo('#container');
}
});
</script>
This would give you to divs that are appended to an element with the ID "container" which are populated
with data returned from your database.
Hope I could help.
cheers