0

I am trying to retrieve multiple rows of data from my database. The number of rows that will be returned is unknown. It works for one row returned. But i also have scenarios where multiple rows are returned to the html page where the ajax function adds the corresponding value to the form.

What is the best way to handle unknown number of rows in an html form? Also is the form a good idea?

I was trying to figure out a way to have the php scipt build the html code and pass it back using ajax. But have been unable to find any sort of examples online.

In the function you can see that I take the data and equate it to the form. The form is predefined to have one entry. but i need to know how to modify the form to know how many records will be returned. I hope that makes sense. Thank you in advanced.

CODE:

function getFunction(){
    //browser support code
    var ajaxRequest; // The variable to create the ajax request
    try {
          // Opera 8.0+, Firefox, Safari Support
          ajaxRequest = new XMLHttpRequest();
    } catch (e){
          try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong with the browser support
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
          if(ajaxRequest.readyState == 4){
            // document.write(ajaxRequest.responseText);
            var response = JSON.parse(ajaxRequest.responseText);
            var pfullname=response.pfirstname + " ";
            var dfullname=response.dfirstname + " ";
            if (response.pmiddlename!=null) {pfullname = pfullname + response.pmiddlename + " ";}
            pfullname = pfullname + " " + response.plastname;
            document.info.name.innerHTML = pfullname;
            //document.info.address.value = ajaxRequest.responseText;
            document.info.dob.innerHTML = response.dob;
            document.info.address.innerHTML = response.paddress;
            document.info.phonenumber.innerHTML = response.phonenumber;
            document.info.sex.innerHTML = response.sex;
            document.info.occupation.innerHTML = response.occupation;
            if (response.dmiddlename!=null) {dfullname = dfullname + response.dmiddlename + " ";}
            dfullname = dfullname + response.dlastname;
            document.info.doctorp.innerHTML = dfullname;
            document.appointment.locationa.innerHTML = response.alocation;
            document.appointment.datea.innerHTML = response.adate;
            document.appointment.doctora.innerHTML = dfullname;
          }
        }
        //var testname = document.getElementById('testname').value;
        var healthid = document.getElementById('healthid').value;
        //var queryString = "?testname=" + testname + "&testpassword=" + testpassword;
        var queryString = "healthid=" + healthid;
        //document.write(queryString);
        ajaxRequest.open("POST", "getnum.php", true);
        ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxRequest.send(queryString);

}

PHP CODE:

query($sql)){ while($row = $result->fetch_object()){ echo json_encode($row); } } else{ //error occurred echo 'error:'.$con->error; } mysqli_close($con); ?>

HTML CODE:

    <h2>
      <span style="font-weight:bold;">Patient Information:</span>
      <form name='info'>
        Name:           <output type='text' name="name" id="name"> </output><br>
        DOB:            <output value='' type='text' name="dob" id="dob"> </output><br>
        Address:        <output type='text' name="address" id="address"> </output><br>
        Phone Number:   <output type='text' name="phonenumber" id="phonenumber"> </output><br>
        Sex:            <output type='text' name="sex" id="sex"> </output><br>
        Occupation:     <output type='text' name="occupation" id="occupation"> </output><br>
        Doctor:         <output type='text' name="doctorp" id="doctorp"> </output><br>
        Doctor Address: <output type='text' name="doctoradd" id="doctoradd"> </ouput><br>
      </form>
    </h2>
8
  • Where is your php code? Commented Dec 22, 2013 at 8:18
  • You can send multiple record in json format in responseText and iterate over them. Can you post your form html also Commented Dec 22, 2013 at 9:14
  • I have added the code for php and html. Problem is that my form is static but i need it to be dynamic so if there are more than one patient then i can list two sets of those forms with the returned php code with multiple rows. Commented Dec 22, 2013 at 21:24
  • Ok - so just to clarify - you want the form to be able to include as many patients as the query returns - but then do you also want to be able to change the form data and submit it again - with all the patients being submitted via the one form - or will each patient be edit and submitted via separate forms? Commented Dec 22, 2013 at 21:34
  • Well actually i am new to the whole thing. I have programmed it as a form but infact it is not really a form and this data will not be passed back to the server again. The id is used to grab data from the database and then have it displayed on the site. Commented Dec 22, 2013 at 21:39

2 Answers 2

1

If you return the data for the multiple rows as an array within your json reponse, eg. in your php:

json_encode(array( array("firstname" => "Bob", "lastname" => "Smith"),
                   array("firstname" => "Harry", "lastname" => "Jones")));

Then in your javascript you can then iterate over this array as Raunak suggests above with something like:

var rows = response.multiplerows

for (i = 0; i < rows.length; i++) {
    //add lines to form here by accessing array data with rows[i].firstname etc.
}

If you are going to do a lot of this sort of thing you may want to look at the likes of knockout.js observable arrays, which can generate the the rows for you based on an html template and the number of lines in the array - http://knockoutjs.com/documentation/observableArrays.html

If in fact you are not needing the data in a form for editing and further manipulation in the browser you may find it easier to return an html chunk to the browser rather than json, and just insert this in the doc, eg. in your php:

$patients = '<h1>List of patients</h1>';

while ($row = $result->fetch_assoc()) {
    $patients .= '<div class="patient-info">First name: '.$row["first_name"].'<br />Last name: '.$row["last_name"].'</div>'; //etc.
}

return $patients;

In your html you can then just have

<div id="patient-list"></div>

And your javascript then will be simply something like:

document.getElementById("patient-list").innerHTML = responseText;
Sign up to request clarification or add additional context in comments.

2 Comments

can i return it with ajax or would then ajax be irrelevant?
over to you - depends what else you are doing on the page - if you are wanting to load it based in selections a user makes then loading via ajax will give a smoother user experience than a traditional server round trip page load
0

I don't think you need to know how many rows will be returned, can you use a php foreach loop such as this:

foreach($arrayName as $row){
    //create the form here
}

Or check how many rows there are using:

 arrayLength = count($arrayName);

2 Comments

THank you for the comment. I also have an issue with how to make the form dynamic, because i have hardcoded it to accept only one entry. But if i have more than one entry returned then how can ajax and php handle and modify the html form to have multiple entries. or vice versa. just need to be pushed in the right direction. I only have had been able to find examples where one entry is returned and the form is static.
i have added the php and html code as well in the question at the top. Thank you in advance to everyone comment and help this is my first question.

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.