dropWizard
dropWizard

Reputation: 3538

Printing response to AJAX call

I am trying to query an endpoint on my server via an AJAX call

The server code:

@app.route('/predict')
def predict():
  return 'predict'

All I want to do is print "predict" in the console.

$.get({
  url: "http://url.com/predict",
  success: function(data) {
    console.log(data)
  }
})

However the response that I am getting is:

Object {readyState: 1}

I'm ver unfamiliar with Javascript & callbacks. What should I change to make this work?

Upvotes: 0

Views: 7745

Answers (2)

dropWizard
dropWizard

Reputation: 3538

Changed my Flask endpoint to:

@app.route('/predict')
def predict():
  resp = flask.Response("predict")
  resp.headers["Access-Control-Allow-Origin"] = "*"
  return resp

This now works:

$.ajax({
  url: "https://url.com/predict",
  success: function(data){
    console.log(data)
  }
})

Upvotes: 0

Leo
Leo

Reputation: 675

You could try something like this:

$.ajax({
      type: "GET",
      url: "http://url.com/predict",
      success: function(data) {
         console.log(data)
      },
      error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr.status);
        console.log(thrownError);
      }
});

Or you could instantiate XMLHttpRequest, and send a request this way:

function load() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(this.responseText);
    }
  };
  xhttp.open("GET", "http://url.com/predict", true);
  xhttp.send();
}

Upvotes: 1

Related Questions