gourav
gourav

Reputation: 177

how to retrieve the data from go api using ajax?

I'm retrieving the data using ajax from golang api but in ajax success function the response is not returning the user data while golang will returning it. Below is the ajax I'm using:

$(document).ready(function(){
    $.ajax({
        url:"/api/v1/customer/:id",
        type: "GET",
        success: function(results){
            console.log(results) //it will not retrieving the data
        }
    });
});

Output of ajax

//nothing

here is the golang router:

Route{"GetFullCustomer", "GET", "/customer/:id", controller.GetCustomer}
// when I will hit this url then the function GetCustomer will run.
v1 := router.Group("/api/v1") // there is also grouping

Here is the function which is retrieving the user:

func GetCustomer(c *gin.Context) {
  t, _ := template.ParseFiles("index.html")
  t.Execute(c.Writer, nil)
  customerIdString := c.Param("id")  //taking the id from url
  customerId, err := strconv.Atoi(customerIdString)
  mongoSession := config.ConnectDb()
  collection := mongoSession.DB("customer").C("customercollection")
  pipeline := []bson.M{
    bson.M{"$match": bson.M{"_id": customerId}},
    bson.M{"$lookup": bson.M{"from" : "address", "localField" : "_id", "foreignField": "user_id","as": "address" }},
    // bson.M{"$project":bson.M{"_id":0}}
  }
  pipe := collection.Pipe(pipeline)
  resp := []bson.M{}
  err = pipe.All(&resp)
  if err != nil {
     fmt.Println("Errored: %#v \n", err)
  }
 c.JSON(200, gin.H{"data": resp})
}

by hitting the url of localhost http://localhost:8080/api/v1/customer/1 Output of terminal is:

[GIN] 2018/05/04 - 12:40:11 | 200 |   11.200709ms |             ::1 | GET      /api/v1/customer/1
[map[$match:map[_id:0]] map[$lookup:map[from:address localField:_id foreignField:user_id as:address]]]
[]
[GIN] 2018/05/04 - 12:40:11 | 200 |    6.986699ms |             ::1 | GET      /api/v1/customer/Person.png
[map[$match:map[_id:0]] map[$lookup:map[foreignField:user_id as:address from:address localField:_id]]]
[]
[GIN] 2018/05/04 - 12:40:12 | 200 |    1.619845ms |             ::1 | GET      /api/v1/customer/:id

Issue is that while golang url hit show above the golang will take the /:id dynamically and matches the data but the ajax don't take this id dynamically. So how I will resolve my problem.

Upvotes: 0

Views: 769

Answers (1)

Andrew
Andrew

Reputation: 1621

It may be silently failing. You need to check the Developer Tools in your browser. In Chrome there is a Network tab which shows info about each AJAX request. It is likely that the AJAX call is failing for some reason and you need to get find out what the error is. You'll probably see it in the Console tab as well.

Also, just noticed that dataType is set to "html", which seems incorrect based on the output format you described. It should probably be "json".

You should handle failures in your AJAX requests so that the user knows there is a problem. Here is some code to get you started:

$(document).ready(function(){
    var promise = $.ajax({
        url:"/api/v1/customer/:id",
        type: "GET",
        dataType: 'json'
    });

    promise.done(function(data) {
        console.log(data);
    });

    promise.fail(function(jqXHR, textStatus, errorThrown) {
        console.log("Request failed. jqXHR.status=" + jqXHR.status + ", textStatus=" + textStatus + ", errorThrown=" + errorThrown);
    });
});

Upvotes: 2

Related Questions