Jub
Jub

Reputation: 41

Ajax request to php file to output mysql data

I am trying to output the row in the database which matches the forename and surname of the student from the dropdown list. i've got the function storing the first name and surname in the variable clickeditem. I must be going wrong in the Ajax/php side of things, possibly the way in which accessing the variable? When I click a name in the dropdown list nothing is occurring at all. Also I am echoing out the 'result' in the php file, how do I change that so the ajax can deal with the 'success'? The code with html and ajax:

    <script 

        $.ajax({
                type: "POST",
                url: "out.php",             
                data: {item : item},              
                success: function(data){                    
                    $("#result").html(data); 
                    //alert(response);
                }

                });
    });
</script>

I have used explode to separate the first name and surname from the string as it obviously will be all in one.

Upvotes: 1

Views: 481

Answers (2)

Jay Blanchard
Jay Blanchard

Reputation: 34426

You've set up a test which will cause the rest of your code to fail:

$student = isset($_POST['clickeditem']);

$student will be either 'true' or 'false', not the string containing the first and last name. At this point your code will fail. Change the line to this:

$student = $_POST['clickeditem'];

Now $student is set properly and the rest of your code should work as you expect.

You also have an error in the query itself ( comma where an AND should go ):

WHERE student_forename=:forename, student_surname=:surname');

should be:

WHERE student_forename=:forename AND student_surname=:surname');

One last thing: you cannot echo $result; because it is an array in this section of your code:

if($result['count'] == 1){
    echo $result;
}

You must either echo $result['count']; or echo $result[0]; or convert the array to another format which will be returned by your AJAX request.

Upvotes: 1

user4798623
user4798623

Reputation:

Looks like there's missing $ sign before fname and sname, so it should be $fname and $sname instead of fname and sname.

    <?php

    session_start();
    $student = isset($_POST['action']);    
    $studentnospace = explode(" ", $student);
    $fname = $studentnospace[0];// Add dollar sign before each variable
    $sname = $studentnospace[1]; // Add dollar sign before each variable
    $pdo=new PDO('mysql:host=localhost; dbname=thename', 'root', 'root');
            $st = $pdo->query('SELECT COUNT(*) AS count FROM students WHERE student_forename=:forename, student_surname=:surname');
            $st->execute(array('forename' => $fname, 'surname' => $sname));
            $result=$st->fetch();
            if($result['count'] == 1){
                echo $result;
            }

?>

Upvotes: 0

Related Questions