0

I have a form that has a dynamic drop down select that when a value is selected it auto populates two other form fields, short and long description. I am trying to use Ajax to retrieve the short and long desc based on the value of the drop down select. I can receive the xmlhttp.responseText data and display it back on the form page but I am unable to parse the responseText out to the respective form fields.

You can see the responseText displayed above "Add New Record" title. It might be hard to read so here it is again: (I was thinking I might have the wrong format)

{"Stitl":"CHF STAFF","Ltitl":"Chief Of Staff"}

enter image description here

HTML file:

<form id="addForm" method="post"  action="units_add.php">

 <legend>Add New Record</legend>
     <label for="titleOrg" class="control-label">Title Org</label>
          <select class="form-control" name="titleOrg" id="titleOrg" onChange="populate(this.value)">
               <option value=" "></option>
               <?php
                  while ($rowl1l5s = $l1l5Result->fetch_assoc()) {
                       echo "<option value=". $rowl1l5s['l1l5']. ">";
                       echo $rowl1l5s['l1l5'] . "&nbsp&nbsp&nbsp&nbsp" .$rowl1l5s['Ltitl']; ;
                       echo "</option>";
                  }?>
          </select>

     <label for="shortDesc" class="control-label">Short Desc</label>
          <input name="shortDesc" class="form-control" id="shortDesc" type="text" readonly="readonly">

     <label for="longDesc" class="control-label">Long Desc</label>
          <input name="longDesc" class="form-control" id="longDesc" type="text" readonly="readonly">

     <button type="submit" class="btn btn-default" id="save"><i class="glyphicon glyphicon-ok glyphicon-white"></i> Save</button>

     <a href="FDMAMaint_V10.php"
          <button class="btn btn-default"  id="cancel"><i class="glyphicon glyphicon-remove"></i> Cancel</button>
    </a>
</form>

Then the user selects a value from the dynamic drop down it executes this JS function:

function populate(str)
{
     if (str=="")
     {
          document.getElementById("shortDesc").innerHTML="";
          return;

      }

      // Create an object 
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
           xmlhttp=new XMLHttpRequest();
      }

      else
      {// code for IE6, IE5
           xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }


      xmlhttp.onreadystatechange=function()
      {

          if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {

              data = xmlhttp.responseText;

              document.getElementById("messages").innerHTML=xmlhttp.responseText;
              document.getElementById("shortDesc").value=xmlhttp.responseText.shortDesc
              document.getElementById("longDesc").value=xmlhttp.responseText.second;

          }
       }
              xmlhttp.open("GET","getl2l5.php?q="+str,true);
              xmlhttp.send();
 }

I know that the following code (see below) doesn't work because it's being referenced wrong, plus it hasn't been parsed yet. I was just throwing that in there for reference as to why the form fields are "undefined"

document.getElementById("shortDesc").value=xmlhttp.responseText.shortDesc
document.getElementById("longDesc").value=xmlhttp.responseText.second;

Then the JS function goes out to the getL2L5 PHP script:

<?php

    define('DBHOST','**************');
    define('DBUSER','********');
    define('DBPASS','**********');
    define('DBNAME','**********');

    //Connect to database
    if (!$db = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME)) die("Can't connect to database");

    // Retrieve the value from the title org drop down select 
    $q = $_GET['q']; 

    // Pull the Ltitl and Stitl based on the drop down value
    $sql="SELECT Stitl, Ltitl FROM tl2l5 WHERE l1l5= '".$q."'";

    // Execute the query 
    if (!$result = $db->query($sql))
    {
            die("There was an error running the query [" .$db->error. "]");
    }

    $data = array();
    // Step through the query result and fetch the values
    while ($row = $result->fetch_assoc()) {

            $Stitl = $row['Stitl'];
            $Ltitl = $row['Ltitl'];
            $data = array( 'Stitl' => $Stitl, 'Ltitl' => $Ltitl);
    }
    echo json_encode($data);
?> 

UPDATE: Thank you @TimSPQR for the JSFiddle. This helped me get on the right track. I realized my issue was of my own doing. I used your JSFiddle to alert the value of var mydata and it displayed this:

enter image description here

then I went to my code to alert my variable and got this:

enter image description here

SOLUTION: Once I marked the html comments as php comments I was able to use JSON.parse on the xmlhttp.responseText and populate the two form fields referencing their correct field titles (ex: data.Stitl)

klm10
  • 277
  • 1
  • 12
  • 24
  • Why are you treating `xmlhttp.responseText` as if it's an object? It's just a string. Also, if your problem is PHP and JavaScript, it usually isn't: either the JavaScript is broken, and then PHP is irrelevant, or the JS works fine, and it's a PHP problem with irrelevant JS. Treat any "PHP + JS" problem as two possible problems, and debug accordingly. – Mike 'Pomax' Kamermans Aug 18 '14 at 19:47
  • I'm able to get the data and it comes back in this format `{"Stitl":"CHF STAFF","Ltitl":"Chief Of Staff"}` but I don't understand how to reference the Stitl/Ltitl values to display in the input form fields. My JS/PHP is working fine I just was wanting to know how to parse out the values. – klm10 Aug 18 '14 at 19:54
  • Then I must question whether you googled for this, because "javascript parse JSON" will pretty much be pages and pages of results that tell you to use `JSON.parse`... – Mike 'Pomax' Kamermans Aug 18 '14 at 20:10
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Mike 'Pomax' Kamermans Aug 18 '14 at 20:11
  • 1
    This fiddle may get you started - http://jsfiddle.net/timspqr/c1a82wop/ – TimSPQR Aug 18 '14 at 21:00
  • 1
    Is there really that much content in short/long descriptions to where you don't just preload all that data into a javascript object on page load (or on first dropdown change event)? Why have AJAX call every time to retrieve two relatively short strings? – Mike Brant Aug 19 '14 at 20:02
  • @MikeBrant I am new to all of this so I didn't know of any other way to do it besides through Ajax but I appreciate the suggestion. I will look into it as an alternative! Thanks! – klm10 Aug 20 '14 at 14:36

0 Answers0