简体   繁体   中英

JSON related error: Unexpected token o

My database table :

TABLE `events` (
    `event_id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
    `event_title` VARCHAR(255) NOT NULL,
    `event_desc` TEXT,
    `event_location` VARCHAR(255) NOT NULL,
    `event_requirements` TEXT DEFAULT NULL,
    `event_date` DATETIME NOT NULL,
 PRIMARY KEY (`event_id`)

The goal : When an event is selected in a select drop down menu, I would like to show the rest of the database data, which belongs to the event in a div below.

The attempt to solve the problem (in a MVC architecture):

Controller

  function index()
  {
      $overview_model = $this->loadModel('Events');
      $this->view->events = $overview_model->getEventTypes();
      $this->view->render('events/index');
  }

Model

  public function getEventTypes()
  {
      $sth = $this->db->prepare("SELECT * FROM events");
      $sth->execute();

      $events = array();

      foreach ($sth->fetchAll() as $event) {
          $events[$event->event_id] = new stdClass();
          $events[$event->event_id]->event_id = $event->event_id;
          $events[$event->event_id]->event_title = $event->event_title;
          $events[$event->event_id]->event_desc = $event->event_desc;
          $events[$event->event_id]->event_location = $event->event_location;
          $events[$event->event_id]->event_requirements = $event->event_requirements;
          $events[$event->event_id]->event_date = $event->event_date;
      }

      return $events;
  }

View

    <!-- start event type selection --> 
   <div class="event-selection">
     <label>Choose an event:</label>
     <select id="select-event-type">
        <?php foreach ($this->events as $event) {
            // Using the event's ID as a value makes it easier for us to look up the selected event.
            echo "<option value='" .$event->event_id. "'>" .$event->event_title."</option>";
        }?>
    </select>

    <script>
        (function ($) {
            // Here we set the JavaScript variable 'events' to a JSON-encoded copy of the array we passed to the template, or null (if there are no events).
            var events = <?php echo (count($this->events) > 0) ? "JSON.parse(" .json_encode($this->events). ");" : "null"; ?>
            $(document).ready(function() {
                $('#select-event-type').change(function() {
                    if (events) {
                        var event = events[this.value];
                        $('#event-details').html(event.title);
                    }
                });
            });
        })($);
    </script>   

    <!-- Start event-details -->
    <div id="event-details"></div> <!-- /#event-details -->

</div><!-- /.event-selection -->

On the page nothing happens when I change the drop down selection.

Console output (in chrome):

        <script>
            (function ($) {
                var events = JSON.parse({"1":{"event_id":"1","event_title":"event1","event_desc":"event1","event_location":"eventlocation","event_requirements":"event1","event_date":"2022-07-20 15:00:00"},"2":{"event_id":"2","event_title":"event2","event_desc":"event2","event_location":"eventlocation","event_requirements":"event2","event_date":"2015-04-20 15:00:00"},"3":{"event_id":"3","event_title":"event3","event_desc":"event3","event_location":"eventlocation","event_requirements":"event3","event_date":"2019-11-20 16:00:00"}});             $(document).ready(function() {
                    $('#select-event-type').change(function() {
                        if (events) {
                            // Now we can get the event details from the selected value.
                            var event = events[this.value];
                            $('#event-details').html(event.title);
                        }
                    });
                });
            })($);
        </script>   

The error :

Uncaught SyntaxError: Unexpected token o

According to my research the line, producing the error is this one (in the view):

var events = <?php echo (count($this->events) > 0) ? "JSON.parse(" .json_encode($this->events). ");" : "null"; ?>

Is the JSON format correct in the console? Another thread suggested to rather use $.getJSON() than JSON.parse() but, since this is the first time I am using JSON, I am not quite sure how that would work in my situation.
I am very thankful for any kind of help!

var events = JSON.parse({"1":{"…

You are trying to parse a JavaScript object literal as if it was JSON.

Since you have to have a string in order to parse JSON, it gets converted into one giving you the equivalent of:

var events = JSON.parse("[object Object]");

That isn't JSON.

Just use the object literal directly:

var events = {"1":{"…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM