tags:

views:

88

answers:

4

Hello,

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:

  1. If a user clicks a specific div (#revealProductButton), how do I create as many divs as $num returns?
  2. 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.
  3. 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?
  4. How to I write my file.php to work with all this?
A: 

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.

bdl
A: 

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.

Sarfraz
I didn't realize I could put PHP within javascript like that? I suppose I can just wrap it in <?php ?> tags though...
Jared
@Jared: you can put php just about anywhere in your document, it will be there since it is server-side language.
Sarfraz
A: 

Hi Jared.

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">
            <a href="...">Product ID: <%= this.id %></a>
        </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

aefxx
A: 

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.

Yorick Sijsling