0

I seem to have no luck with these darn AJAX MySQL queries...

I'm trying to query the database when a selection from a drop-down menu is made, and fill a div with the results from the script. I've tried two different ways, with no luck either time.

METHOD 1

Javascript

var ajaxRequest;
var create_url = "create_script.php";
var process_url = "process.php";
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!");
        }
    }
}

function races(id)
{
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
            document.getElementById('race_info').innerHTML = ajaxRequest.responseText;
        }
    }
    var params = "mode=race&id="+id;
    ajaxRequest.open("POST", create_url, true);
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxRequest.setRequestHeader("Content-length", params.length);
    ajaxRequest.setRequestHeader("Connection", "close");
    ajaxRequest.send(params);
}

function classes(id)
{
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
            document.getElementById('class_info').innerHTML = ajaxRequest.responseText;
        }
    }
    var params = "mode=classes&id="+id;
    ajaxRequest.open("POST", create_url, true);
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxRequest.setRequestHeader("Content-length", params.length);
    ajaxRequest.setRequestHeader("Connection", "close");
    ajaxRequest.send(params);
}

the page body:

<div id="contentwrapper">
    <div id="contentcolumn">
        <div class="innertube">
            <?php
            if($step == 0)
            {
            ?>
            <form action="<?php echo $u_create; ?>" method="post">
                <h2>Races</h2>
                <select id="race_select" name="race_select">
                    <?php
                    $sql = 'SELECT * FROM '.RACES_TABLE;
                    $result = $db->sql_query($sql);
                    while($row = $db->sql_fetchrow($result))
                    {
                        echo '<option onfocus="races('.$row['race_id'].');" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
                    }
                    ?>
                </select>
                <h2>Classes</h2>
                <select id="class_select" name="class_select">
                    <?php
                    $sql = 'SELECT * FROM '.CLASSES_TABLE;
                    $result = $db->sql_query($sql);
                    while($row = $db->sql_fetchrow($result))
                    {
                        echo '<option onfocus="classes('.$row['race_id'].');" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
                    }
                    ?>
                </select>
                <br />
                <input type="submit" value="Select" name="submit" />
            </form>
            <br />
            <div id="race_info"></div>
            <br />
            <hr />
            <br />
            <div id="class_info"></div>
            <?php
            }
            ?>
        </div>
    </div>
</div>

METHOD 2

AJAX

$(document).ready(function() {
    $("#race_select").change(function() {
        var race = $("#race").val();
        $.ajax({
            url: 'create_script.php',
            data: 'mode=race&amp;id=' + race,
            dataType: 'json',
            success: function(data)
            {
                $("#race_info").html(data);
            }
        });
    });

    $("#class_select").change(function() {
        var class = $("#class").val();
        $.post("create_script.php", { mode: "class", id: class }, function(data) {
            $("#class_info").html(data);
        });
    });
});

The page body:

<div id="contentwrapper">
    <div id="contentcolumn">
        <div class="innertube">
            <?php
            if($step == 0)
            {
            ?>
            <form action="<?php echo $u_create; ?>" method="post">
                <h2>Races</h2>
                <select id="race_select" name="race_select">
                    <?php
                    $sql = 'SELECT * FROM '.RACES_TABLE;
                    $result = $db->sql_query($sql);
                    while($row = $db->sql_fetchrow($result))
                    {
                        echo '<option id="race" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
                    }
                    ?>
                </select>
                <h2>Classes</h2>
                <select id="class_select" name="class_select">
                    <?php
                    $sql = 'SELECT * FROM '.CLASSES_TABLE;
                    $result = $db->sql_query($sql);
                    while($row = $db->sql_fetchrow($result))
                    {
                        echo '<option id="class" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
                    }
                    ?>
                </select>
                <br />
                <input type="submit" value="Select" name="submit" />
            </form>
            <div id="race_info"></div>
            <hr />
            <div id="class_info"></div>
            <?php
            }
            ?>
        </div>
    </div>
</div>

None of the attempts have worked at all. I'm not sure what I'm doing wrong. There's not even a POST request being made on the select option change, according to firebug.

2 Answers 2

3

well for starters, in method two, all of your select options have the same ids. therefore, when querying:

var race = $("#race").val();

you will always get the first option.

instead, within the change function, this will refer to the selected element. so:

var race = $(this).val();

will get what you want

EDIT

Here is a simplified example using your code demonstrating your desired behavior in jsfiddle form: http://jsfiddle.net/7Xtqv/1/

hope that helps

1
  • I didn't see that one :D nice catch. Even if you're 100% wrong but that's a nice catch, there's something wrong with the IDs (see my post) Commented May 23, 2011 at 1:54
1

In your jQuery AJAX request, you're setting dataType to JSON. So jQuery attempts to parse the JSON once received. If it fails, nothing happens. Not even the request shown in Firebug.

If you're using html in your AJAX return, you should set the dataType to HTML.

EDIT

Oh and in the second request in your jQuery file, you're doing var class = $("#class").val();. You might want to avoid naming your vars with reserved names: http://www.quackit.com/javascript/javascript_reserved_words.cfm

EDIT2

As @pthurlow noticed, there's a big fail with your IDs names. You're trying to get #race select, but there's no race ID in your HTML. There's a #race_select but it's different from #race. It also fails with your #class stuff.

1
  • Ah jeez. i forgot to correct those when posting. I had originally had race_select as race. After a few tweaks, it works perfectly. Thanks to you both! Commented May 23, 2011 at 2:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.