0

Hoping this is my last question for this form I made. My php works fine and is getting the correct data. I've created variables for the indexes and now want to pass them to my js/ajax so the values fill the html textboxes. Not sure code is correct or not as there are not a lot of examples of what I am doing out there.

Am I calling the array indexes correctly in the ajax portion of this page? Not sure if I should be using 'innerHTML' or the value attribut. If i'm way off please explain how this can be done. If you need to see my php I can edit. Thanks!

 <script type="text/javascript">
function queryStudent() {
    var ajaxRequest;

    try {
        ajaxRequest = new XMLHttpRequest;
    }catch(e) {
        //IE Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Browser not compatible");
                    return false;
                }
            }
    }   


     ajaxRequest.onreadystatechange = function() {
        if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {

            document.getElementById("studentID").value = output1;           
            document.getElementById("stuName").value = output2;
            document.getElementById("email").value = output3;
            document.getElementById("GPA").value = output4;

        }
    };
    var student_ID = document.getElementById('studentID').innerHTML = ajaxRequest.responseText; 

    var queryString = "?studentID=" + student_ID;
    ajaxRequest.open("GET", "search_single.php"+ queryString, true);
    ajaxRequest.send(); //Return value from function 
}
</script>   
<h2>Search for Students by studentID</h2>
<br>
<form name="myForm" action="search_single.php" method="post"> <!--no action or post as it is posted to same page-->
<label>Student ID:</label>
<input type="text" id="studentID">
<br>
<br>
<input type="button" onClick="queryStudent()" value="Search">
<h2>Student information will be displayed in the textboxes below:</h2>
<br>

<table id="outuput">
<tr>
    <td>Student ID:</td>
    <td><input type="text" id="studentID" value="" readonly></td>
</tr>
<tr>
    <td>Student Name:</td>
    <td><input type="text" id="stuName"  value="" readonly></td>
</tr>    
<tr>
    <td>Email:</td>
    <td><input type="text" id="email" value="" readonly></td>
</tr>
<tr>
    <td>GPA:</td>
    <td><input type="text" id="gpa" value="" readonly></td>
</tr>
<br>
</table>
</form>

PHP Code:

if(!isset($studentID)) {
$studentID = filter_input(INPUT_GET, 'studentID', FILTER_VALIDATE_INT);
    if($studentID == NULL || $studentID == FALSE) {
        $studentID = 1;
    }
}
//prepare query 
$query = 'SELECT * FROM student
          WHERE studentID = :studentID';
$statement = $db->prepare($query);
$statement->bindValue(':studentID', $studentID);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);

//var_dump($result); //check indexes

$output = "";
$output1 = $output.$result['studentID'];
$output2 = $output.$result['name'];
$output3 = $output.$result['email'];
$output4 = $output.$result['GPA'];

?>

7
  • I apologize but I have to leave for a couple hours to work. look forward to reading help. Commented May 7, 2016 at 22:02
  • I've created variables for the indexes...without your PHP code, it's all guesswork. Please update the question with your PHP code. Commented May 7, 2016 at 22:04
  • What are output1,output 2 etc.? and your line starting with var student_ID is suspecious. What do you mean by two = signs? Commented May 7, 2016 at 22:09
  • I would suggest you use an existing ajax library, such as comes with jQuery, at least until you learn the concepts better. But if you want to figure it out for yourself (which could help you learn better), then please read this documentation. If you do, I would suggest you start by copying their code exactly, getting it to work on your page, then modify it to your needs. Then, once you understand ajax well, use an existing library since the only reason to re-invent the wheel is to learn how wheels work. Commented May 7, 2016 at 22:17
  • var studentID is input the query will use as an id to return the records for that id. Commented May 7, 2016 at 22:43

1 Answer 1

2

There are several errors in your code, such as:

  • id attribute of

    <input type="text" id="studentID"> 
    

    and

    <td><input type="text" id="studentID" value="" readonly></td>
    

    is same. Change one of the id attribute to make them distinct.

  • You're getting the studentID from input field in the wrong way,

    var student_ID = document.getElementById('studentID').innerHTML = ajaxRequest.responseText; 
    

    It should be,

    var student_ID = document.getElementById('studentID').value;
    
  • On the server side, in your PHP code

    $output = ""; $output1 = $output.$result['studentID'];... 
    

    you're just concatenating the values with an empty string and assigning it to another variable, which by the way won't do any good to your code. Instead, take the result row from the result set and encode it using json_encode() function. And on the client side, parse this json object and fill the appropriate input fields.

So your code should be like this:

HTML:

<h2>Search for Students by studentID</h2>
<br>
<form name="myForm" action="search_single.php" method="post">
    <label>Student ID:</label>
    <input type="text" id="studentID" />
    <br>
    <br>
    <input type="button" onClick="queryStudent()" value="Search">
    <h2>Student information will be displayed in the textboxes below:</h2>
    <br>

    <table id="outuput">
    <tr>
        <td>Student ID:</td>
        <td><input type="text" id="stuID" value="" readonly></td>
    </tr>
    <tr>
        <td>Student Name:</td>
        <td><input type="text" id="stuName"  value="" readonly></td>
    </tr>    
    <tr>
        <td>Email:</td>
        <td><input type="text" id="email" value="" readonly></td>
    </tr>
    <tr>
        <td>GPA:</td>
        <td><input type="text" id="gpa" value="" readonly></td>
    </tr>
    <br>
    </table>
</form>

JavaScript:

<script type="text/javascript">
    function queryStudent() {
        var ajaxRequest;

        try {
            ajaxRequest = new XMLHttpRequest;
        }catch(e) {
            //IE Browsers
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e){
                        // Something went wrong
                        alert("Browser not compatible");
                        return false;
                    }
                }
        }   

         ajaxRequest.onreadystatechange = function() {
            if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
                var data = JSON.parse(ajaxRequest.responseText);
                if(data['status']){
                    document.getElementById("stuID").value = data['studentID'];
                    document.getElementById("stuName").value = data['name'];
                    document.getElementById("email").value = data['email'];
                    document.getElementById("gpa").value = data['GPA'];
                }else{
                    alert("You have passed an invalid student ID");
                }
            }
        };

        var student_ID = document.getElementById('studentID').value;
        var queryString = "?studentID=" + student_ID;
        ajaxRequest.open("GET", "search_single.php"+ queryString, true);
        ajaxRequest.send();
    }
</script>   

PHP:

<?php

    if(!isset($studentID)){
        $studentID = filter_input(INPUT_GET, 'studentID', FILTER_VALIDATE_INT);
        if($studentID == NULL || $studentID == false) {
            $studentID = 1;
        }
    }

    // Your PDO connection code

    $result = array(); // To hold the result array
    $query = 'SELECT * FROM student WHERE studentID = :studentID LIMIT 1';
    $statement = $db->prepare($query);
    $statement->bindValue(':studentID', $studentID);
    $statement->execute();
    if($statement->rowCount()){
        $result = $statement->fetch(PDO::FETCH_ASSOC);
        $result['status'] = true;
    }else{
        $result['status'] = false;
    }
    echo json_encode($result);

?>
Sign up to request clarification or add additional context in comments.

1 Comment

your method worked. Fantastic! I haven't studied json or jquery methods yet but understand those methods are the way forward. I look forward to learning and developing. Much appreciative of the help.

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.