Ajax script only working in Firefox (not working in Chrome, Safari, Edge,...)

this code is working fine in Firefox, but in all other browsers I have tested I get the error "SyntaxError: JSON Parse error: Unexpected EOF" in line if (this.readyState == 4 && this.status == 200). The json-string looks like this:

[{"ID":"1","token":"1234","name":"Test Satio","matno":"11111","reg_date":"2017-10-24 00:00:00","last_active":"2017-10-24 00:00:00","user_id":"25"},{"ID":"3","token":"2232434","name":"Test Satio 2","matno":"44444","reg_date":"2017-10-23 00:00:00","last_active":"0000-00-00 00:00:00","user_id":"25"},{"ID":"5","token":"32233","name":"Test Satio 3","matno":"12","reg_date":"0000-00-00 00:00:00","last_active":"0000-00-00 00:00:00","user_id":"25"}]


 $(document).ready(function postData() {
    var id = localStorage.getItem('user-id');
    var token = localStorage.getItem('user-token');
    var vars = "id=" + id + "&token=" + token;
    var hr = new XMLHttpRequest();
    var url = "../php/getUsers.php";

      hr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {  //in this line I get the error
            var data = JSON.parse(hr.responseText);

            for(var i=0;i<data.length;i++){

                    var templateData = {
                        name: data[i].name,
                        id: data[i].id

                  var id=templateData['id'];

                  $.get('templates/user.htm', (function (templateData) {
                     return function(templates) {
                        var template = $(templates).filter('#user-template').html();
                        $('#user-container').append(Mustache.render(template,    templateData));

    hr.open("POST", url, true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


What do I need to change to get this code working in all browsers?

Thanks, Lukas

Answers 1

  • I don't think you need to fire off a request for the user template for each user, I think you can do it once and save it.

    I've simplified your code a bit and changed your outer ajax to use jquery.

     $(document).ready(function postData() {
          url: "../php/getUsers.php",
          data: {
            id: localStorage.getItem('user-id'),
            token: localStorage.getItem('user-token')
          dataType: 'JSON',
          success: function (data) {
            // now get the template
            $.get('templates/user.htm', function (templates) {
              var template = $(templates).filter('#user-template').html();
              // we have the template and userdata array
              data.map(function (el) {
                return {id: el.id, name: el.name};
              }).forEach(function (templateData) {
                 $('#user-container').append(Mustache.render(template, templateData));

Related Articles