Access javascript DOM objects in PHP - php

I have a javascript code helping me to dynamically create row after row in a table and to delete a row from that table.
each row has four cells. cell 1 for instance contains a text zone.
to differentiate cell1 from row 1 with cell1 from row 2, I rename my cell 1 like that cell1.name= cell1.name + '_' + row.rowIndex.
I create a submit button so that I could read data entered by a user in the rows of the table and I try to print $_GET. but there is nothing inside. How could I access to my DOM objects in PHP?
I am grateful for your help.
my HTML + PHP code
<body >
<?php
if (isset($_GET['Enter'])){
print_r($_GET);
}
?>
<h1> Create an Item </h1>
<form method="GET" action="func.html">
<table align="center" border = "2" cellspacing ="0" cellpadding="3" id="table">
<tr><td><b>Functionality Name:</b></td> <td><b>Description:</b></td> <td><b>Status:</b></td> <td><input type="button" Name= "Ajouter" Value="Ajouter" onclick="go()"></td></tr>
</table>
<input type="submit" name="submit" value="Enter">
</form>
</body>
and my Javascript code:
<script>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox and others
xhr = new XMLHttpRequest();
else if(window.ActiveXObject){ // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest not supported by your browser
alert(" Your browser does not support XMLHTTPRequest objects...");
xhr = false;
}
return xhr
}
/**
* method called when the user clicks on the button
*/
function go(){
var xhr = getXhr()
// We defined what we gonna do with the response
xhr.onreadystatechange = function(){
// We do somthing once the server's response is OK
if(xhr.readyState == 4 && xhr.status == 200){
var body = document.getElementsByTagName("body")[0];
// Retrieve <table> ID and create a <tbody> element
var tbl = document.getElementById("table");
var tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell_1 = document.createElement("td");
var cell_2 = document.createElement("td");
var cell_3 = document.createElement("td");
var cell_4 = document.createElement("td");
// Create the first cell which is a text zone
var cell1=document.createElement("input");
cell1.type="text";
cell1.name="fname";
cell1.size="20";
cell1.maxlength="50";
cell_1.appendChild(cell1);
// Create the second cell which is a text area
var cell2=document.createElement("textarea");
cell2.name="fdescription";
cell2.rows="2";
cell2.cols="30";
cell_2.appendChild(cell2);
// Create the second cell which is a combo box
var cell3 = document.createElement("div");
cell3.id="rs";
cell3.innerHTML=xhr.responseText;
cell_3.appendChild(cell3);
// Create the fourth cell which is a button
var cell4=document.createElement("input");
cell4.type="button";
cell4.value="Delete"
cell4.onclick=delRow;
cell_4.appendChild(cell4);
// add cells to the row
row.appendChild(cell_1);
row.appendChild(cell_2);
row.appendChild(cell_3);
row.appendChild(cell_4);
// add the row to the end of the table body
tblBody.appendChild(row);
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// Rename cells with the row index
var ind=row.rowIndex;
var liste_fname = row.getElementsByTagName("input");
for(i=0; i < liste_fname.length; i++)
{
if(liste_fname[i].name == "fname")
{
liste_fname[i].name = liste_fname[i].name + "_" + ind; //give fname_1, fname_2, fname_3, ...
}
}
var fd = row.getElementsByTagName("textarea");
fd[0].name = fd[0].name + "_" + ind;
var cd = row.getElementsByTagName("div");
cd[0].id = cd[0].id + "_" + ind;
var selectname = row.getElementsByTagName("select");
selectname[0].name = selectname[0].name + "_" + ind;
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 1;
tbl.setAttribute("border", "1");
}
}
xhr.open("GET","fstatus.php",true);
xhr.send(null);
}
function delRow(){
var i= this.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(i);
}
</script>
Best regards,
Billy

Because PHP is server side and Javascript is Client side you can't directly access elements on the page.
In order to access elements you need to post back to the server via a FORM or some AJAX.
You might look into jQuery to help you do this since it makes it easier to call your PHP programs and manipulate the DOM.

I'm going to second the use of jQuery. It'll be tidier and keep you neatly in a single paradigm during this particular task.
One way to do this with PHP would be to dump your DOM object into JSON and then use PHP's JSON support. Depending on your purposes, you can roll your own class to process the JSON data or just grab it from the array you get from json_decode(). Another way would be to dump the object into its representative HTML and pass that to your PHP script rather than the DOM object. You can then reparse it using The Simple HTML DOM Parser, an easy-to-use, freely available DOM parser for PHP.
Of course, you should note that you're adding two processing steps here. If you can do the processing you need to do without switching languages, you're saving time and a bit of sanity.

Well... for starters you want to see if $_GET['submit'] is set not $_GET['Enter'] because $_GET['submit'] should have the value of 'Enter'.
Also, each of your textarea's need to have a different name from the rest, so they don't overwrite each other ( Or they need to have a name that ends in [] (square brackets) and then php will turn them into an array).
And once the html is submitted... the DOM doesn't exist anymore so PHP can't really access it except through ajaxy kinf of stuff.

your cell name should not named like that ... it should be like this
<input type='text' name='username[]' value=''/>
<input type='text' name='username[]' value=''/>
<input type='text' name='username[]' value=''/>
.....
<input type='submit' name='submit' value='submit'/>
so you can access from php as array of username
$_GET[username][0] for example will display the first username etc ...
btw, try to use prototype or jquery (javascript framwork) it will simplify your life a lot.
to post data using jquery using ajax:
var url = 'your.server.com/post/fstatus.php';
var data = $('#myform_id').serialize();
$.post(url, data , function(result){
//... if the data was alright or submited ...
alert(result);
},"json");
isn't it easier ? :)
to append a simply type:
var newfield="<div id='rs'><textarea name='mytextarea'></div>"; $('#your_target_id').append(newfield);
in your php type
<?php print_r($_GET); ?>
and you will see what i mean :)

I cannot stress enough - use jQuery. Your life will be an order of magnitude simpler.

Related

Values not passing to php with ajax

I have the following script :
<script type="text/javascript" >
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val();
var first_lastname = $(".first_lastname", this).val();
var second_firstname = $(".second_firstname", this).val();
var second_lastname = $(".second_lastname", this).val();
var TeamName = $(".TeamName", this).val();
var dataString = 'first_firstname='+ first_firstname + '&first_lastname=' + first_lastname +
'&second_firstname=' + second_firstname + '&second_lastname=' + second_lastname + '&TeamName=' + TeamName;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
success: function(){
window.setTimeout(function(data)
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
});
</script>
And the following php that generates a number of forms on a page using mysql database
<?php
echo '<table class="greensmalltbl" cellspacing="10px" cellpadding="5px"><div id="propspectDiv"></div>';
for ($i=1, $o=$totalEntrants; $i<=$half; $i++, $o=$o-1) {
$formid = $i;
echo "<div style='border:3px;'><form action='' method='post'>
<tr><td><input type='text' name='first_firstname' id='first_firstname' value='$firstName[$i]' />
<input type='text' name='first_lastname' id='first_lastname' value='$lastName[$i]' />
Skill Level : ".$skill[$i]."</td></tr>";
echo "<tr><td>WITH</td></tr>";
echo "<tr><td><input type='text' name='second_firstname' id='second_firstname' value='$firstName[$o]' />
<input type='text' name='second_lastname' id='second_lastname' value='$lastName[$o]' /> Skill Level ".$skill[$o]."</td></tr>";
echo "<tr><td>Enter Team Name : <input type='text' name='TeamName' id='TeamName' value='' />
<input type='submit' name='submit' value='Submit'></form></td></tr>";
}
echo '</table>';
?>
I want to update the db table with the TEAM NAME in each form
The problem is only the first forms input is passed all other forms do nothing
I have tried a number of variations to the ajax code but none have worked.
Can anyone find the problem here
This line will not return the form.
var parent = $(this).parent('form');
because your submit button is wrapped inside tr and td tags. Either get rid of those tags (they are invallid anyway, because your are not using them in a table), or update your code to:
var parent = $(this).closest('form');
closest() searches its way up to all the ancestors of an element, and will return the first match of the selector.
Check out the documentation here: http://api.jquery.com/closest/
Or, if you only have a single form in your page, you could just go:
var parent = $('form');
:: EDIT ::
OK. Forget all of the above. Seems like you are not even using the parent variable later in the code.
A more important problem is that even though you are catching the Click event on the form submit button, what you probably really want to do is catch the submit-event of the form.
So change your first line of code to this:
$('form').on('submit', function() {
Also, in your HTML, your code is invalid.
<form action'' method='post' id='$formid'>
action'' should be action = ''
Chances are this doesn't really fix your problem, because there might be more errors. Next time, try to validate your code before posting a question.
:: EDIT ::
Last edit, I promise. I quickly went trough your code again, and it seems you will have multiple forms. this means, that you will get elements in different forms with the same id's. An id should be unique for troughout the page. So when you try to get a value like this $("#second_firstname").val(); that won't work. because jQuery doesn't know what element you mean, so all elements that can appear multiple times in a page need to have a class and CAN NOT have an id.
You could then loop trough your forms by changing things to:
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val(); // . instead of # and use 'this' as context
// and so on..
// the rest of your code here.
}
});
table with forms can be seen here

MySQL Query Within JavaScript

I am working on a form whereby JavaScript is used to add another line item. The purpose is to add line items to an invoice. I have successfully got this to work ok when using text boxes in my form, but am stuck on how to get this to work with a dropdown box that makes a call to mysql to get the dropdown box data.
Here is what I have.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
?>
<script type="text/javascript">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><select name='myInputs[]'><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>";
document.getElementById(divName).appendChild(newdiv);
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><select name="myInputs[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>
So here is some info on what is going on. Right now, the JavaScript code above shows the MySQL query in it. This kills the add line item functionality. If I simply remove the query but leave the other php in, the add line item begins to work again, but of course there is no data in the drop down.
In the form itself, it gets the first line item from the database without using javascript and this is working ok.
I feel like I am getting close, but don't know where to go from here.
Thanks in advance.
EDIT:
Thanks to Nick, I got this working. Here is the code.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
?>
<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><select name='myInputs[]'>" + xmlhttp.responseText + "</select>";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "update_text.php", false);
xmlhttp.send();
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><select name="myInputs[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>
</div>
<input type="button" value="Add" onClick="addInput('dynamicInput');">
</form>
Then the update_text.php
<?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 here is my php post into the database which is not working for the javascript add line item, only for the original entry that is created from the form. (I have other fields besides the dropdown).
<?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());
}
echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
Thanks, please let me know if I can clean this up better.
Sadly the way you'r trying to do it wont work due to the nature of PHP.
When a client requests your page from the server ALL the php is executed.
So the php block inside your javascript function is actually just the static result of your php.
You'll need to use XMLHttpRequests/Ajax to request the new data from the server.
Here's a quick (and probably fairly bad) example!
Modification to your javascript function:
var counter = 1;
function addInput(div) {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var d = document.getElementById(div);
d.innerHTML=d.innerHTML +"<div>Entry " + (++counter) + " <br><select name='myInputs[]'>" + xmlhttp.responseText + "</select></div>";
}
}
xmlhttp.open("GET", "updated_list.php", false);
xmlhttp.send();
}
A new php file on your server: (updated_list.php)
<?php
// you'll need to include stuff to connect to your database here
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
update
I did say it was a bad example :) my original code overwrote the contents of your div instead of adding to it, which ive updated. this was only an example, you should read up on AJAX and how to request data from the server.
You cannot use server code inside a javascript function after the page is load.
The server side code is like it's name - code that runs on the server. so after the page finish loading it "get back" to the client and only client code (javascript) can run now.
so your line
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><select name='myInputs[]'><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>";
is a bit mistake.
what you can do is to return the data from the database to the javascript (using json will be the best option) and then build the select box dynamically using the raw data that came from the server that is now a javascript data.
so let's say your data is
var data = [{name:'n1'},{name:'n2'},{name:'n3'}];
You can run this data using javascript and build your combo:
var newSelect = document.createElement('select');
for(var i=0;i<data.length;i++){
var name = data[i].name;
newSelect.options[newSelect.options.length] = new Option(name,name);
}
This is a classic example for AJAX (Asynchronous Javascript And XML) - the basic concept is that when an action is carried out (e.g. a button clicked to show content), some JavaScript calls a PHP (asynchronously), the PHP runs, returns an XML file (although this can actually be any file format you want, some people now prefer to use JSON because it's easier to parse), and the contents of the this XML / JSON are displayed, also using JavaScript.
Although the example above is displaying content, there's no reason why any action where you need to run on the server (e.g. inserting data to a database) can't also be done asynchronously.
SO is not a place for code to be written for people - so now I've given you a hint as to where to start, and as an exercise for the reader ( / question asker!), have a look at some AJAX tutorials, make sure you understand the concept, write some code, and come back if still can't get it working!
Good luck :)

Getting a record row in php using javascript

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

Jquery / Ajax used on PHP page in a for loop

I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
http://api.jquery.com/attribute-starts-with-selector/
http://api.jquery.com/delegate/

How to I use ajax and PHP to create and populate div elements?

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

Categories