Solved

populate dynamic drop down from a csv

Posted on 2016-11-04
3
38 Views
Last Modified: 2016-11-04
hello all,
i have a requirement  where a dynamic dropdown form has to be built from csv data.
for example:
Label_ID,PN,CUSTPN,SN,DC,DESC
A1234,123456,_Blank,,H1234,ALPHA
B1234,234567,876543,A1B2C3D4,J0987,_Blank
C1234,345678,,,_Blank,
D1234,456789,765432,,,BETA
E1234,567890,654321,B1C2D3E4,,GAMMA

What I am looking to do is to be able to chose A1234 from a drop down menu populated by the data under LABEL_ID. After selection, fields for PN,CUSTPN,SN,DESC would be available (appear) & populated with the associated data. any ideas how to implement this in php , ajax, or javascript.
any suggestions are appreciated,
thanks.
0
Comment
Question by:rishi vindya
3 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41874578
First the PHP bit.
<?php
$file = fopen('t1829.csv', 'rt');

$headers = fgetcsv($file);
$search = isset($_GET['search']) ? $_GET['search'] : false;
$result = false;
if ($search) {
  while($row = fgetcsv($file)) {
    if ($row[0] == $search) {
    $result = new stdClass;
        foreach($row as $i => $r) {
      $result->{$headers[$i]} = $r;
    }
    break;
    }
  }
}
die(json_encode($result));

Open in new window


Adjust $file to be where your CSV file is and then test the php script with the following url
http://server/getData.php?search=A1234
You should get something like this back
{"Label_ID":"A1234","PN":"123456","CUSTPN":"_Blank","SN":"","DC":"H1234","DESC":"ALPHA"}

Open in new window

Nearly there - just need to define the select and the ajax

HTML
<form>
<select name="search">
  <option value="">-- SELECT ONE -- </option>
  <option value="A1234">A1234</option>
  <option value="B1234">B1234</option>
  <option value="C1234">C1234</option>
  <option value="D1234">D1234</option>
  <option value="E1234">E1234</option>
</select>
PN <input type="text" name="PN" id="PN" /><br/>
CUSTPN <input type="text" name="CUSTPN" id="CUSTPN" /><br/>
SN <input type="text" name="SN" id="SN" /><br/>
DC <input type="text" name="DC" id="DC" /><br/>
DESC <input type="text" name="DEsC" id="DESC" />
</form>

Open in new window

Rudimentary but gets the job done.

Finally the AJAX
<script>
$(function() {
  // BIND TO THE onchange
  $('#LABEL_ID').change(function() {
    // MAKE THE AJAX CALL
    $.ajax({
      url: 'getData.php',
      data: {
        search: $(this).val()
      },
      type: 'GET',
      dataType: 'JSON'
    }).done(function(resp) {
      if (resp) {
        // SET THE DATA
        for(var i in resp) {
          $('#' + i).val(resp[i]);
        }
      }
    });
  });
});
</script>

Open in new window

Working sample here

EDIT
Note in the done() callback we loop over the returned object and use its keys to identify the controls we want to set. In this way you can add / rename fields in your CSV and as long as you have an input with the same ID as the Fieldname - this code will set it.
1
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 41874658
Test page : https://jsfiddle.net/a4bqsqbg/
<select id="Label_ID" name="Label_ID"><option>select something...</option></select>
<input type="text" id="PN" name="PN" />
<input type="text" id="CUSTPN" name="CUSTPN" />

Open in new window


We get the CSV with Ajax here :
var x = new XMLHttpRequest();
x.open("GET", "/path/to/your/csv", true);
x.onreadystatechange = function() {
    if(x.readyState === 4) {
        if(x.status === 200 || x.status == 0) {
          var csv = x.responseText;
          var rows = csv.split(/\n/);
          for(var i=1;i<rows.length;i++) {
            var row = rows[i];
            var columns = row.split(","); // , is the separator
            var o = new Option(columns[0],columns[0]);
            o.dataset.pn = columns[1];
            o.dataset.custpn = columns[2];
            document.getElementById("Label_ID").appendChild(o);
          }
          document.getElementById("Label_ID").onchange = function() {
            var pn = this.options[this.selectedIndex].dataset.pn;
            var custpn = this.options[this.selectedIndex].dataset.custpn;
            document.getElementById("PN").value = pn;
            document.getElementById("CUSTPN").value = custpn;
          }

        }
    }
}
x.send(null);

Open in new window

1
 

Author Comment

by:rishi vindya
ID: 41874867
thanks guys you were saviors..
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now