Using AJAX to handle updates to a specific entry in a list

Bit clunky as I’m in a hurry, but this is really just to remind me how to set this up when I do it next time.

So, imagine you have a list of div’s. Each div contains a visual representation of a task or a database entry that you’re showing to a user. You want to dynamically update content within each div depending on the selection made in a pulldown: –

JavaScript

The ‘onchange’ of the pulldown (select element) calls OnChange in the code below and triggers and update for the given index. sel is the select element and idIn is the index in the list of “div’s” (the 0 or 1 in “id=’div_0′”, “id=’div_1′” etc)

// ==========================================================================
// Use ajax to populate a div based on selection in a select element
// ==========================================================================
function OnChange(sel, idIn)
{
    xmlhttp = newXMLHttpRequest();
    xmlhttp.onreadystatechange = SubFunction(idIn); // Use a sub-function to handle the parameter passing

    // Pass in the selected index so we know which 'div' to replace
    var selected = sel.options[sel.selectedIndex].value;
    xmlhttp.open("GET", "./populate.php?s=" + selected, true);
    xmlhttp.send();
}

// ==========================================================================
// Handle the ajax callback
// ==========================================================================
function SubFunction(idIn)
{
    return function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var el = document.getElementById("div_" + idIn);
            el.innerHTML = this.responseText;
        }
    };
}
PHP
<!-- populate.php would be something like... -->
<?php

// Build content based as required here. This will be inserted into the innerHTML of the appropriate div

$id = $_GET['s'];
echo "here's some content: ".$id;
?>
HTML
…and the HTML is set up quite simply as: –
$string=<<<END
    <select onchange='OnChange(this, $id)'>
        <option value="0">Option 1</option>
        <option value="1">Option 2</option>
        <option value="2">Option 3</option>
    </select>
END;
echo $string;

The $id is the id of the current row in the div list (matches the div element id)

 

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: