0
votes

I am trying to create a short form in HTML consisting of a list box, a comment box and a submit button. The form allows a person to select up to 7 items from the list box and then leave a comment about his/her selection. The items of the list box themselves come from a XML file that is located on the same server as the html, php, js, and css files are.

Populating the list box from the XML file and the rest of the form work fine. But I run into an issue as soon as I try to use the list box in combination with selectize.js. Selectize.js itself is working and I can alter the list box, define the maximum of items which can be selected etc. But the options of the list box are missing all of the sudden. It is as if the items of the XML file are not loaded correctly anymore. And as soon as I disable selectize.js, the options are back.

I apologize in advance if this is a very basic or even repeated question. I am not very good with jQuery and scrambled the code together from various sources. I also tried to find help by googling similar issues for about a day but so far had no luck. So any help is greatly appreciated.

Here's my code.

index.php

<?php
     if($_POST['submit'] == "Submit") {

     $errorMessage = "";
     if(empty($_POST['select-songs'])) {
          $errorMessage .= "<li>You forgot to select a song!</li>";
     }

     $log = "";

     foreach ($_POST['select-songs'] as $song) {
          $log .= $song . ",";
     }

     $log .= $_POST['comment'];

     // $songs = $_POST['select-songs'];
     // $comment = $_POST['comment'];

     if(!empty($errorMessage)) {
          echo("<p>There was an error with your form:</p>\n");
          echo("<ul>" . $errorMessage . "</ul>\n");
     } else {
          $fs = fopen("mydata.txt","a");
          fwrite($fs,$log . "\n");
          fclose($fs);
          header("Location: thankyou.html");
          exit;
     }
 }
 ?>

 <html>
      <head>
           <title>Fav5 Song Selector</title>
           <meta charset="UTF-8">
           <!-- jQuery libraries -->
           <script src="libraries/jquery-3.2.0.min.js"></script>
           <script src="libraries/selectize.min.js"></script>

           <!-- scripts -->
           <script language="javascript" type="text/javascript" src="ui.js"></script> <!-- include the reload.js file -->

           <!-- stylesheets -->
           <link rel="stylesheet" href="style.css">
           <link rel="stylesheet" href="selectize.css">
      </head>

      <body>
           <h1>Fav5 Demo UI</h1>
           <form action="index.php" method="post">
                <select id="songLib" name="songLib[]" class="demo-default">
                     <option value="" disabled selected hidden>Select a maximum of 7 songs from your playlist</option>
                </select>

                </br>

                <textarea name="comment" rows="5 "cols="25"></textarea>

                </br>

                <input type="submit" name="submit" value="Submit" />
           </form>
      </body>
 </html>

ui.js

 $(document).ready(function(){
      $.ajax({
           type: 'GET',
           url: 'songs.xml',
           dataType: 'xml',
           success: function(xml){
                $(xml).find('song').each(function() {
                     $('#songLib').append(
                     '<option>' +
                          $(this).find('title').text() +
                     '</option>'
                );
           });
      }
      });

      $('#songLib').selectize({
           delimiter: ',',
           persist: false,
           maxItems: 7
      });
 });
1

1 Answers

1
votes

Okay, I have found a solution to my problem.

I couldn't get selectize.js work together with the jQuery/AJAX from my original question. But it turns out selectize.js does have its own way of importing data into a list box. And instead of providing my data in XML I had to use JSON.

Here's the code in case anyone is having the same issue.

HTML

<?php
    if($_POST['submit'] == "Submit") {
        $errorMessage = "";
        if(empty($_POST['songLib'])) {
            $errorMessage .= "<li>You forgot to select a song!</li>";
        }
        $log = "";
        foreach ($_POST['songLib'] as $song) {
            $log .= $song . ",";
        }
        $log .= $_POST['comment'];
        if(!empty($errorMessage)) {
            echo("<p>There was an error with your form:</p>\n");
            echo("<ul>" . $errorMessage . "</ul>\n");
        } else {
            $fs = fopen("mydata.txt","a");
            fwrite($fs,$log . "\n");
            fclose($fs);
            header("Location: thankyou.html");
            exit;
       }
    }
?>

<html>
    <head>
        <title>Fav5 Song Selector</title>
        <meta charset="UTF-8">
        <!-- jQuery libraries -->
        <script src="libraries/jquery-3.2.0.min.js"></script>
        <script src="libraries/selectize.min.js"></script>
        <!-- scripts -->
        <script language="javascript" type="text/javascript" src="ui.js"></script>  <!-- include the reload.js file -->
       <!-- stylesheets -->
       <link rel="stylesheet" href="style.css">
       <link rel="stylesheet" href="selectize.css">
    </head>

    <body>
        <h1>Fav5 Demo UI</h1>
        <form action="index.php" method="post">
            <select id="songLib" name="songLib[]" class="demo-default" placeholder="Select a maximum of 7 songs from your playlist"></select>
            </br>
            <textarea name="comment" rows="5 "cols="25"></textarea>
            </br>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

JS

$(document).ready(function(){
    $('#songLib').selectize({
        valueField: 'title',
        labelField: 'title',
        searchField: ['artist','title'],
        options: [],
        maxItems: 7,
        preload: true,
        plugins: ['remove_button', 'restore_on_backspace'],
        delimiter: ',',
        sortField: [
            {
                field: 'artist',
                direction: 'asc'
            },
            {
                field: '$score'
            }
        ],
        load: function(query, callback) {
            $.ajax({
                url: 'songs.json',
                type: 'GET',
                dataType: 'json',
                data: {
                    title: query,
                    artist: query,
                },
                error: function() {
                    console.log("fail");
                    callback();
                },
                success: function(res) {
                    console.log("success");
                    console.log(res);
                    callback(res);
                }
            });
        },
        render: {
            option: function(item, escape) {
                return '<div>'
                + escape(item.artist) + ' - '
                + escape(item.title)
                + '</div>';
            },
            item: function(item, escape) {
                return '<div>'
                + escape(item.artist) + ' - '
                + escape(item.title)
                + '</div>';
            }
        }
   });
});

JSON

[
    {"artist": "Simon & Garfunkel","title": "Mrs. Robinson"},
    {"artist": "Simon & Garfunkel","title": "The Boxer"},
    {"artist": "Crosby, Stills, Nash & Young","title": "Almost Cut My Hair"},
    {"artist": "Queen","title": "Another One Bites the Dust"},
    {"artist": "Queen","title": "Don't Stop Me Now"},
    {"artist": "CCR","title": "I Heard It Through the Grapevine"},
    {"artist": "Iggy Pop","title": "The Passenger"},
    {"artist": "Roy Orbinson","title": "In Dreams"},
    {"artist": "Scorpions","title": "Wind Of Change"},
    {"artist": "CCR","title": "Lookin' Out My Backdoor"},
    {"artist": "The Who","title": "Behind Blue Eyes"},
    {"artist": "Dexys Midnight Runners","title": "Come On Eileen"},
    {"artist": "Neil Young","title": "Heart Of Gold"},
    {"artist": "Neil Young","title": "Old Man"},
    {"artist": "Buffulo Springfield","title": "Stop Children What's That Sound"},
    {"artist": "Pink Floyd","title": "Wish You Were Here"},
    {"artist": "Leatherbag","title": "On Down the Line"},
    {"artist": "Negative Lovers","title": "Faster Lover"},
    {"artist": "Crowded House","title": "Take the Weather With You"},
    {"artist": "Crowded House","title": "Don't Dream It's Over"},
    {"artist": "Townes Van Zandt","title": "Dead Flowers"},
    {"artist": "Polo And Pan","title": "Canopee"},
    {"artist": "Polo And Pan","title": "Plage Isolee"},
    {"artist": "Polo And Pan","title": "Dorothy"},
    {"artist": "Polo And Pan","title": "Rivolta"}
]