RDAxRoadkill
RDAxRoadkill

Reputation: 464

Ajax Select, getting data out of database with select

How do I get the value out of an database using the following: A user selects id (i.e 1) within a <select> function then the data is displayed in a <p> tag I have the following and I am able to change the text with the <p> but I can't get the data out of the database for some reason

Select Code

<p id="dbinfo" >Data comes here</p>


<select id='slct'>
    <option value='empty'>select a number</option>
    <option value='1'> 1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
    <option value='5'>5</option>
</select>

<script>     
    document.getElementById("slct").onfocus = function()
    {
        alert(document.getElementById('slct').value);

        var xmlhttp = new XMLHttpRequest();
        var text = "";
        xmlhttp.onreadystatechange = function()
        {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                var dbText = xmlhttp.responseText;
                var obj = JSON.parse(); 
                var text;
                var i;
                for(i =0; i < obj.records.length; i++)
                {
                    text += "<option value='" +obj.records[i].id+ "'>" + obj.records[i].id + "</option>";
                }
                document.getElementById('dbinfo').innerHTML = dbText;

            }            
        }
        xmlhttp.open("POST", "http://localhost/somemaps/data.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send();

        document.getElementById("slct").onchange = function(){
            var id = this.children[this.selectedIndex].value;
            document.getElementById("dbinfo").innerHTML = "text has changed: " +id;

            xmlhttp1 = xmlhttpRequest(); 
            xmlhttp.send("id="+id);         
        }
    }


</script>

Data Code

<?php
    //Haal de gegevens uit de database en echo ze naar dit scherm.
    $servername = "localhost";
    $username = "root";
    $password = "";
    $databasename = "blok-1-am1a";

    if(isset($_POST['id']))
    {
        $extra = "WHERE ".$id. " = ".$_POST['id'];
    }
    else
    {
        $extra = "";
    }

    try
    {
        $connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db-name` ".$extra);


        $statement->execute();

        $result = $statement->setFetchMode(PDO::FETCH_ASSOC);

        $data = "";
        foreach($statement->fetchAll() as $key => $value)
        {
            $data .= $value['id']." | ".$value['firstname'];
        }

    catch(PDOException $e)
    {
        echo "Dit is een PDO foutmelding, de volgende fout heeft plaatsgevonden : ".$e->getMessage();


    }

    echo $data;


?>

I was thinking that I should add a value to return? but this does not seem to work so what could be the problem? Any tips/anwsers are welcome (:

Edit

After cliffs response and changing my code to his this is the result:

Page as is

And after selecting this happens:

After select

So as said all the data from the database just shows instead of the selected id

Upvotes: 1

Views: 7226

Answers (2)

Cliff Burton
Cliff Burton

Reputation: 3744

There are three problems I've found in your code:

  • There is a typo on line 9 of the PHP code you posted:
    I think that $extra ="WHERE ".$id=$_POST['id']; should be $extra ="WHERE ".$id."=".$_POST['Id']; note the equal sign = enclosed in double quotes.

  • On line 32 still in the PHP code $data .= $value['id']." | ".$value['firstname']"; remove the last double quote before the semicolon like so:
    $data .= $value['id']." | ".$value['firstname'];

  • The event you are looking for to make an AJAX call when user selects id within a <select> is the onchange, in jQuery .change().
    So listen on its event on line 14 of your JS code too: instead of onfocus use onchange like so document.getElementById("slct").onchange = function()

Then, since you tagged your post with jQuery, you can use the AJAX methods of jQuery which is faster and easier to use.

I would suggest the jQuery.ajax() method:

$("#slct").change(function() {
    var idVar = $(this).val(); // The jQuery version of this.children[this.selectedIndex].value
    $.ajax({
        url:"http://localhost/somemaps/data.php",
        type:"post",
        data: {id: idVar},
        async:true,
        success: function(data) {
            //  Code to be executed if the request succeeds eg:
            $("#dbinfo").html(data);
            //  The data variable contains the content returned from the server
            },
        error: function() {
            //  Code to be executed if the request fails
            }
    });
});

Upvotes: 2

SYNCRo
SYNCRo

Reputation: 470

$sth = $connection->prepare("SELECT `id`, `firstname`, FROM `db-name` WHERE ".((isset($_POST['id'])) ? "`id`" : ":id")." = :id");
$sth->execute(array(":id" => (isset($_POST["id"])) ? $_POST["id"] : 0));
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

Upvotes: 0

Related Questions