2

I have a php script that works correctly when executed directly: The PHP:

<?php
    header('Content-Type: application/json');
    $fileName = "../appfiles/Courses.json";
    if (file_exists($fileName)) 
      {
    $json = json_decode(file_get_contents($fileName), true);
        echo json_encode($json);
      } 
    else 
      {
        echo "The file $fileName does not exist";
      }
    ; 
?>

Running

http://localhost/RickVideos/php/getRegCourses.php

, I get:

[{"coursecode":"ACCTD_001","cflag":"Y","pflag":"Y","dateregistered":"08\/11\/14","timeregistered":"12:55 pm."},{"coursecode":"LWPRG1_004","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:30 pm."},{"coursecode":"LWPRG2_005","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:32 pm."}]

Trying to run the php from jquery ajax, what returns seems to be the text of the script rather than the json data.

JavaScript:

// registered courses

var registeredCourses = {

init: function () 
    {
        $.ajax(
            {   
                type: 'POST',
                dataType: "JSON",
                url: "php/getRegCourses.php",
            }
        )

        .done(function(data) 
            { 
                $.each(data, function(index, element) 
                    {
                        $('#registeredCourses').append(
                        $('<option value="' +   index + '">' + this['coursecode'] + '</option>')
                        );
                    }
                );      
                $('#registeredCourses').val('0');
                $("#registeredCourses").trigger('chosen:updated');
                registeredCourses.getSelected();    
            }
        )
        .fail (function(jqXHR, textStatus, errorThrown )
            {
                alert('request failed :'+errorThrown);
                alert ('textStatus :'+textStatus);
                console.log(jqXHR);
            }
        );
    },

getSelected: function () 
    {
        $.ajax(
            {
                type: 'GET',
                url: "getSelCourseInfo.php",
                data: 
                    {
                        course: $("#registeredCourses option:selected").text() 
                    }
            }
        )

        .done(function( data ) 
            {
                $("#courseCode").val($("#registeredCourses option:selected").text());
                $("#courseTitle").val(data.Title);
                $("#projectManager").val(data.ProjectManager);                         
                $("#initRegDate").val (data.LastModDate + ' at ' +  data.LastModTime);

                var tasks = [ ];
                $.each(data.ProjectTasks, function(i, item) 
                    {       
                        $("#projectTasks").append(
                            '<tr>' +
                            '<td>' + this + '</td>' +
                            '</tr>'
                        );
                        tasks[i] = this;
                    }
                );

                var projectMems = [ ];
                $.each(data.ProjectMembers, function(i, item)
                    {       
                        $("#projectMembers").append(
                            '<tr>' +
                            '<td>' + this.PersonName + '</td>' +
                            '<td>' + this.EmailAddress + '</td>' +
                            '</tr>'
                        );
                        projectMems[i] = this.PersonName;
                    }
                );

                $("#selectedCourseData").find("tr:gt(0)").remove();
                $.each(data.Chapters, function(i, item) 
                    {
                        $("#selectedCourseData").append(
                            '<tr>' +
                            '<td>' + this.label + '</td>' +
                            '<td>' + this.title + '</td>' +
                            '<td>' + registeredCourses.makeList('Sciptwriter1', i, projectMems, this.ScriptWriter) + '</td>' +
                            '<td>' + registeredCourses.makeList('Recorder1', i, projectMems, this.Recorder) + '</td>' +
                            '<td>' + registeredCourses.makeList('Status1', i, tasks, this.Status) + '</td>' +
                            '<td>' + registeredCourses.makeList('Assignedto1', i, projectMems, this.Assignedto) + '</td>' +
                            '</tr>'
                        );
                    }
                );

            }
        ); 


    },

    makeList: function (cname, num, array, selected) 
        {
            var string = '<select class="' + cname +'">';
            if (selected== " " && array[0] != " ") 
                {
                array.splice(0, 0, " ");
            };
            for (var i=0; i < array.length; i++) 
                {
                    if (array[i]==selected) 
                        {
                            string = string + '<option value="' + array[i] + '" selected>' + array[i]  + '</option>';
                    }
                    else 
                        {
                            string = string + '<option value="' + array[i] + '">' + array[i]  + '</option>';
                    };
            };

            string = string + '</select>';
            return string;
        }

};

The first alert shows:

request failed :SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

The second alert shows:

textStatus :parsererror

And the response text for the jqXHR object shows:

"<?php header('Content-Type: application/json'); $fileName = "../appfiles/Courses.json"; if (file_exists($fileName)) { $json = json_decode(file_get_contents($fileName), true); echo json_encode($json); } else { echo "The file $fileName does not exist"; } ; ?> "

Why is the text of the script showing rather than the json data?

user1424917
  • 47
  • 2
  • 6
  • It's especially weird, since you mention directly calling the file works correctly.. perhaps here you can find something: http://stackoverflow.com/a/5121589/2433843 If not, check your network window in your browser where you can see if the headers and responses etc are correct. – Francesco de Guytenaere Aug 24 '14 at 21:08
  • Check the first answer on this question: http://stackoverflow.com/questions/16012815/jquery-ajax-200-ok-json-parseerror. Also, I noticed in the code you posted you have an unenclosed string: "+ /option>')". It should be: " + '/option')" – Andrew Briggs Aug 24 '14 at 21:15
  • I reposted the code including the missing functions. – user1424917 Aug 24 '14 at 22:44
  • I reran the code after eliminating the dataType from the ajax call and now get this as the first alert result:request failed :Error: Invalid XML: – user1424917 Aug 24 '14 at 22:55

2 Answers2

0

Not sure if this helps or not but the following code works for me. Set up a directory with your json, your php, and an html file for basically just populating the select menu. This works fine for me and when taking a look at your code there were some js errors:

$('<option value="' + index + '">' + this['coursecode'] +/option>') is missing the '< before the option close tag

Also missing a } after you ) at the end of fail. After fixing those files your code worked for me as far as populating the dropdown, though you get js errors because registeredCourses.getSelected(); doesn't exist. Which makes me wonder if the above code is complete?

If all that doesn't help then have you looked at teh raw html that is output when you go directly to your php file, like viewing the source?

`bonk.php`
<?php
    header('Content-Type: application/json');
    $fileName = "courses.json";
    if (file_exists($fileName))
      {
    $json = json_decode(file_get_contents($fileName), true);
        echo json_encode($json);
      }
    else
      {
        echo "The file $fileName does not exist";
      }
    ;
?>

`courses.json`
[
    {
        "coursecode": "ACCTD_001",
        "cflag": "Y",
        "pflag": "Y",
        "dateregistered": "08/11/14",
        "timeregistered": "12:55 pm."
    },
    {
        "coursecode": "LWPRG1_004",
        "cflag": "Y",
        "pflag": "Y",
        "dateregistered": "08/18/14",
        "timeregistered": "3:30 pm."
    },
    {
        "coursecode": "LWPRG2_005",
        "cflag": "Y",
        "pflag": "Y",
        "dateregistered": "08/18/14",
        "timeregistered": "3:32 pm."
    }
]

`html file`
<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>

    var registeredCourses = {
      init: function (){
        $.ajax ({
          type: 'GET',
          dataType: "JSON",
          url: "bonk.php",
        })

        .done(function(data){
          $.each(data, function(index, element){
            $('#registeredCourses')
              .append($("<option></option>")
              .attr("value",index)
              .text(this['coursecode']));
          });
        })

        .fail (function(jqXHR, textStatus, errorThrown){
          console.log(errorThrown, textStatus, jqXHR);
        })
      }
    };

    registeredCourses.init();
  </script>
  </head>
  <body>
    <select name="test" id="registeredCourses"></select>
  </body>
</html>
Mark Hayden
  • 515
  • 4
  • 13
  • I reposted the js code including the missing functions. The js errors mentioned were introduced as I was trying to edit the code in posing the question. – user1424917 Aug 24 '14 at 22:50
  • Viewing the HTML source when accessing the php file directly looks just like the display - there's nothing additional. – user1424917 Aug 24 '14 at 22:53
  • What version of php are you using? – Mark Hayden Aug 24 '14 at 23:08
  • Current PHP version: 5.4.24 – user1424917 Aug 25 '14 at 01:16
  • I got an error running your code that $ isn't defined. I changed the first script to point to js/jquery-1.11.1.min.js and added a $(document).ready(function () { as the first line of the second script and a }); at the end. In firebug, the console shows: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data ...SON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,funct... – user1424917 Aug 25 '14 at 01:40
0

I coverted both the php file and the Courses.json file to utf-8 and it now runs.

user1424917
  • 47
  • 2
  • 6