0

I am trying to get this function to work, I am new to javascript and am doing this for a homework assignment. I attempt the code below however nothing appears as a result. I am pretty sure I am doing something wrong, due to the fact that this is my first time obtaining data from an API. Any tips or help is greatly appreciated.

Code:

function getStudentsInCourse() {
    $.get("http://web.cs.somecollege.edu/~doej/web/api/student/getStudents/")
    .done(function (data) {
        return data;
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
    console.log("Error calling Student/getStudentsInCourse: " + errorThrown);
    });
}

call:

var course []
course = getStudentsInCourse();

note:.coursenum referenced from the API itself.

Parameters coursenum - string; unique identifier for a Course

Returns JSON array of objects

Sample data from API:

[
    {
        "id": "3",
        "name": "Jax",
        "level": "Junior",
        "owner": "public",
        "photo_filename": "",
        "active": "1"
    },
    {
        "id": "4",
        "name": "Ashe",
        "level": "Junior",
        "owner": "public",
        "photo_filename": "",
        "active": "1"
    }
]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
NinjaZ
  • 25
  • 7

2 Answers2

1

There is get is asynchronous. In your case you can not get any data. Because you call is synchronous.

function getStudentsInCourse(cb) {
   $.get("http://web.cs.somecollege.edu/~doej/web/api/student/getStudents/")
   .done(function (data) {
       cb(null, data);
    })
   .fail(function (jqXHR, textStatus, errorThrown) {
       cb(errorThrown);
   });
}


getStudentsCourse(function (err, data) {
  //your code is here
});
Isabek Tashiev
  • 1,036
  • 1
  • 8
  • 14
0

I like Isa Bek's answers but a solution with Promises is more elegant.

var courses = [];

function getStudentsInCourse() {
    return $.get("http://web.cs.somecollege.edu/~doej/web/api/student/getStudents/");
}

function successHandler(response) {
    courses.push(response);
}

function failHandler(jqXHR, textStatus, errorThrown) {
    console.log("Error calling Student/getStudentsInCourse: " + errorThrown);
}

getStudentsInCourse().then(successHandler, failHandler);
Starmetal
  • 740
  • 6
  • 14
  • OP will need to pass in the `json` argument to the `$.get` - `$.get("someurl", "json")` - http://jsfiddle.net/gy2trdhm/6/ in order to use the response data if it is in json format – Michael Doye Nov 15 '15 at 10:44
  • 1
    He can pass whatever options he wants. Btw, Using `$.when` in your example it's overkill. The jQuery response already implements `then`. Use `$.when` when you have chained promises, tho I don't really like the interface jQuery has when comes to promises. – Starmetal Nov 15 '15 at 10:47