0

I'd like to query a database and upload entries from that database into fields on a webpage. However, the only way I currently know to do that is create a webpage in PHP that performs the query, prints it onto a page in a readable fashion, and then load that page with ajax and parse through the HTML. That seems like a very roundabout way of doing it-- so is there anything I can do which is more direct?

To be clear: I have a dropdown menu:

<select name="items" id="items" size=[php variable] onChange="javascript:updatePage()">
    <option value="[database entry ID]">[php variable]</options>
    <option value="[database entry ID]">[php variable]</options>
<textarea name="stuff" id="stuff">
</textarea><br>

And then later on I'll have:

<script src="jquery.js"></script>
<script>
    function updatePage()
    {
        var itemToLoad = $('#items').val();
        $.ajax({
            type: "POST",
            url: 'updatepage.php',
            data: "itemtoload=" + itemToLoad,
            success: function(data) {
                var stuff = data;
                stuff = parseWhatINeed(stuff);
                $('#stuff').text(stuff);
            }
        });
    }
</script>

And updatepage.php does a MySQL query, and the parseWhatINeed function parses what I need from the html in the data variable. Is there a better way of going about this?

mavix
  • 2,488
  • 6
  • 30
  • 52
  • 1
    Nope, you have hit the nail on the head using AJAX. There is a post here that talks about what you're trying to do: http://stackoverflow.com/questions/2256310/directly-accessing-server-database-via-ajax-without-php-or-some-other-intermedi – Jay Blanchard Mar 16 '12 at 21:52

2 Answers2

0

Why don't you try to create a JSON object from the data you've fetched from your database and send 'em back as a response of the Ajax call, then use your javascript to create/input these values into the HTML. It's faster and reduces traffic.

Rocky
  • 327
  • 1
  • 9
0

Rather than render the page using PHP. Have PHP output a JSON string which you can then interpret using jquery. Using JSON you can return an object which will store all of the data that you need. This method is usually better because it will take fewer resources and bandwidth to transfer a JSON string than it would if you were to transfer rendered HTML.

VictorKilo
  • 1,839
  • 3
  • 24
  • 39