开发者

jQuery and JavaScript AJAX Database Queries

开发者 https://www.devze.com 2023-03-07 12:25 出处:网络
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 t

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开发者_如何学Python(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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消