Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <title>Dynamically populate select by AJAX result - jsFiddle demo</title>
- <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
- <link rel="stylesheet" type="text/css" href="/css/normalize.css">
- <link rel="stylesheet" type="text/css" href="/css/result-light.css">
- <script type='text/javascript' src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
- <style type='text/css'>
- </style>
- <script type='text/javascript'>//<![CDATA[
- $(window).load(function(){
- // The data that the service should return
- // JSFiddle will echo it back for us on that URL
- var doctors = {
- success: true,
- doctors: [
- {
- id: 71,
- name: "George"
- },
- {
- id: 72,
- name: "James"
- }
- ]
- }
- var doctors1 = {
- success: true,
- doctors: [
- {
- id: 71,
- name: "Georgess"
- },
- {
- id: 72,
- name: "Jamessss"
- }
- ]
- }
- var doctors2 = {
- success: true,
- doctors: [
- {
- id: 71,
- name: "Samm"
- },
- {
- id: 72,
- name: "MArk"
- }
- ]
- }
- // This is what your JSON from PHP should look like
- // Bind change function to the select
- jQuery(document).ready(function() {
- jQuery("#services").change(onServiceChange);
- });
- function onServiceChange()
- {
- var serviceId = jQuery(this).val();
- if(serviceId=='1'){
- var jsonDoctors = JSON.stringify(doctors);
- console.log(jsonDoctors);
- }else if(serviceId=='2'){
- var jsonDoctors = JSON.stringify(doctors1);
- console.log(jsonDoctors);
- }else{
- var jsonDoctors = JSON.stringify(doctors2);
- console.log(jsonDoctors);
- }
- $.ajax({
- url: '/echo/json/',
- type: 'post',
- data: {
- serviceId: serviceId,
- json: jsonDoctors // jsFiddle echos this back to us
- },
- success: onServicesRecieveSuccess,
- error: onServicesRecieveError
- });
- }
- function onServicesRecieveSuccess(data)
- {
- // Target select that we add the states to
- var jTargetSelect = jQuery("#doctors");
- // Clear old states
- jTargetSelect.children().remove();
- // Add new states
- jQuery(data.doctors).each(function(){
- jTargetSelect.append('<option value="'+this.id+'">'+this.name+'</option>');
- });
- }
- function onServicesRecieveError(data)
- {
- alert("Could not get services. Please try again.");
- }
- });//]]>
- </script>
- </head>
- <body>
- <select id="services">
- <option>Click to select a service</option>
- <option value="1">Service 1</option>
- <option value="2">Service 2</option>
- <option value="3">Service 3</option>
- </select>
- <hr>
- <select id="doctors">
- </select>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement