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.
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);
});
});
Related
I am trying to scrape http://www.snapdeal.com/offers/deal-of-the-day which loads JSON data using an AJAX call to below page:
json_url = http://www.snapdeal.com/json/getProductById?*
The code block I am using is below, I get the log message Waiting for AJAX request:, but not the Waiting for AJAX request:, instead waitForResource times out
casper.options.onResourceRequested = function (casper, requestData){
// loop through our AJAX urls
// create list of AJAX urls to track
var ajaxUrls = [json_url];
ajaxUrls.every(function(ajaxUrl){
// does this request match an AJAX url
if(requestData.url.indexOf(ajaxUrl) !== -1){
// it matches, so we'll wait for it to return (with 10s timeout)
//console.log("Waiting for AJAX request: " + requestData.url);
// print_object(requestData);
casper.waitForResource(requestData.url, function(){
console.log("AJAX request returned: " + requestData.url);
}, function(){
console.log("AJAX request didn't return after wait period: " + requestData.url)
}, 10000);
}
});
}
To further debug, I logged events and the resource at url json_url was successfully received, but not sure why waitForResource times out.
casper.on('resource.received', function(resource) {
if (resource.url.indexOf('http://www.snapdeal.com/json/getProductById') != -1){
casper.echo('resource.received: ' + resource.url);
}
});
Log after run:
Waiting for AJAX request: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,1775140628,1822452791,439536 ,Range,2042952975,1472100667,899358889,643129681532,668235859588,&lang=en
resource.received: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,1775140628,1822452791,439536,Range, 2042952975,1472100667,899358889,643129681532,668235859588,&lang=en
resource.received: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,1775140628,1822452791,439536,Range, 2042952975,1472100667,899358889,643129681532,668235859588,&lang=en
AJAX request didn't return after wait period: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,17751406 28,1822452791,439536,Range,2042952975,1472100667,899358889,643129681532,668235859588,&lang=en Got page No Offeres Found thestartin: ~/Appli
What you need is:
casper.waitForSelector()
or
casper.waitFor(function() {
// test here something that return true when the page is loaded
})
I have set up a Go rest api. And on login I do this:
session, _ := store.New(r, sessionId)
session.Options.MaxAge = 12 * 3600
err := session.Save(r, w)
//treat error
and for checking the session i have smth like this:
session, err := store.Get(r, sessionId)
//treat error
if session.IsNew {
http.Error(w, "Unauthorized session.", http.StatusUnauthorized)
return
}
If I do the requests from postman it works fine, but when I do them from my client I get 401. Has any of you experienced something like this? The store is a CookieStore.
I already checked the id's, I replaced sessionId variable with a static string. Gorilla session uses gorilla context to register a new request and when I do the request from postman context.data[r] is not null, but from the client it is always null -> always a new session.
https://github.com/gorilla/context/blob/master/context.go - line 33
it is called in
https://github.com/gorilla/sessions/blob/master/sessions.go - line 122
wich is used in the CookieStore.Get function in
https://github.com/gorilla/sessions/blob/master/store.go - line 77
EDIT 1:
For the client I use polymer and I tried xmlhttp too.
Polymer:
<iron-ajax
id="ajaxRequest"
auto
url="{{requestUrl}}"
headers="{{requestHeaders}}"
handle-as="json"
on-response="onResponse"
on-error="onError"
content-type="application/json"
>
</iron-ajax>
and the handlers
onResponse: function(response){
console.log(response.detail.response);
this.items = response.detail.response
},
onError: function(error){
console.log(error.detail)
},
ready: function(){
this.requestUrl = "http://localhost:8080/api/fingerprint/company/" + getCookie("companyId");
this.requestHeaders = {"Set-cookie": getCookie("api_token")}
}
and the cookie successfully reaches the backend.
And xmlhttp:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
//do stuff
}else if(xmlhttp.status == 401){
page.redirect("/unauthorized")
}else{
page.redirect("/error")
}
}
}
xmlhttp.open("GET","http://localhost:8080/api/fingerprint/company/" + getCookie("companyId"),true);
xmlhttp.setRequestHeader("Set-cookie", getCookie("api_token"));
xmlhttp.send();
EDIT 2:
So I tried debugging with fiddler(thanks for the suggestion) and i found out that the request from postman has an bold entry Cookies / Login and the request from the client does not. Any idea how to get/set that value? It is somehow automatically set in Postman. In the authentication request I get a set-cookie header that has all the data that I need but I can't get it on the client. I get Refused to get unsafe header set-cookie.
The problem is that in the client the requests need to have withCredentials = true and after that the browser deals with everything. It gets the cookie from the set-cookie header and it sends the cookies via the cookie header. So, after all, it was not a gorilla sessions problem.
If anyone else is having the same problem I was having and you want to whitelist all domains/wildcards (or have a list of domains in an array you can scan through), you can do something like this.
domain_raw := r.Host
domain_host_parts := strings.Split(domain_raw, ".")
domain := domain_host_parts[1] + "." + domain_host_parts[2]
domains := getDomains() // stores a slice of all your allowable domains
has_domain := false
for _, d := range domains {
if d == domain {
has_domain = true
break
}
}
if has_domain == false {
return
} else {
w.Header().Add("Access-Control-Allow-Origin", "https://"+domain_raw)
w.Header().Add("Access-Control-Allow-Credentials", "true")
}
I love go
I am trying to check if the user name is available for use using ajax and codeigniter. I have problem to get the response from the codeingniter controller in my js. file but without success.
Here is the controller function, relevant to the question:
if ($username == 0) {
$this->output->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Rest assured that I do get 1 if username already exists in thedatabase and 0 if it does not exist.
I have the following js.file
// list all variables used here...
var
regform = $('#reg-form'),
memberusername = $('#memberusername'),
memberpassword = $('#memberpassword'),
memberemail = $('#memberemail'),
memberconfirmpassword = $('#memberconfirmpassword');
regform.submit(function(e) {
e.preventDefault();
console.log("I am on the beggining here"); // this is displayed in console
var memberusername = $(this).find("#memberusername").val();
var memberemail = $(this).find("#memberemail").val();
var memberpassword = $(this).find("#memberpassword").val();
var url = $(this).attr("action");
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: "json",
data: {memberusername: memberusername, memberemail: memberemail, memberpassword: memberpassword},
cache: false,
success: function(output) {
console.log('I am inside...'); // this is never displayed in console...
console.log(r); // is never shonw in console
console.log(output); is also never displayed in console
$.each(output, function(index, value) {
//process your data by index, in example
});
}
});
return false;
})
Can anyone help me to get the username value of r in the ajax, so I can take appropriate action?
Cheers
Basically, you're saying that the success handler is never called - meaning that the request had an error in some way. You should add an error handler and maybe even a complete handler. This will at least show you what's going on with the request. (someone else mentioned about using Chrome Dev Tools -- YES, do that!)
As far as the parse error. Your request is expecting json data, but your data must not be returned as json (it's formatted as json, but without a content type header, the browser just treats it as text). Try changing your php code to this:
if ($username == 0) {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Newbie to this - This code is works - in that the call to the script does what it is supposed to but returns the condition 500 and I can not see why. I am looking for any suggestions or changes that I should be making to make this work.
Thanks to all who respond.
function get_update_odometer(vehicle_key,odometer_value){
var url = "[%Catalyst.uri_for('/invoice/dispatch_util/get_update_odometer')%]";
new Ajax.Request(url, {
method: 'get',
parameters: {
key: vehicle_key,
ovalue: odometer_value
},
asynchronous:false,
onSuccess: successFunc,
onFailure: failureFunc
});
var return_v = $('rcontainer').innerHTML;
document.getElementById('odometer').value = return_v;
return true;
}
function successFunc(response){
if (200 == response.status){
var container = $('rcontainer');
var content = response.responseText;
container.update(content);
}
}
function failureFunc(response){
alert("Call has failed " + response.status );
}
Error code is coming from server side, and you provided the client part.
So have a look if your server script get_update_odometer is working, is callable by your web server and etc ...
I have the following node.js server set up listening to port 9001
var https = require('https');
var fs = require('fs');
var qs = require('querystring');
var options = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
console.log('Request Received!');
console.log(req.method);
if (true || req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
console.log(body);
var POST = qs.parse(body);
console.log(POST);
});
}
res.end("hello, world\n");
}).listen(9001);
and I am trying to get this server to respond to an AJAX call
function form_save()
{
console.log("submitted!");
var data_obj = {
data1: "item1",
data2: "item2"
}
$.ajax({
url: 'https://adam.testserver.com:9001/',
type: "POST",
dataType: "json",
data: data_obj,
success: function() {
console.log("success!");
},
complete: function() {
console.log("complete!");
}
});
}
There are two problems occurring with my arrangement. The first is that if I start the server and then click the button that triggers my form_save() the node server does not respond and I get the following error:
submitted!
OPTIONS https://adam.testserver.com:9001/ Resource failed to load
jQuery.extend.ajaxjquery.js:3633
$.ajaxjquery.validate.js:1087
form_savew_worksheet.php:64
confirm_deletew_worksheet.php:95
jQuery.event.handlejquery.js:2693
jQuery.event.add.handlejquery.js:2468
w_worksheet.php:73
complete!
At this point if I access that url directy (https://adam.testserver.com:9001/) I get the expected "hello, world" output as well as the console message "Request Received!
GET". From this point on if I click the button to trigger my AJAX call I get a new error.
submitted!
XMLHttpRequest cannot load https://adam.testserver.com:9001/. Origin
https://adam.testserver.com is not allowed by Access-Control-Allow-Origin.
w_worksheet.php:73
complete!
I don't understand why I get this message as both my form and node server reside on the same server. Thanks for taking the time to read, I appreciate any help I can get on this. I've been stuck for a while now!
You've run into the Cross-Origin Resource Sharing (CORS) specification.
Note the OPTIONS in your output. The OPTIONS HTTP Verb is used by the browser to query the web server about the URL, not to GET its contents or POST data to it.
Your server doesn't respond with the correct header data on a CORS request, so your browser assumes it has no rights to access the data, and refuses to GET or POST to the URL.
If you truly want to let any website in the world run that AJAX request, you can do something similar to the following:
function handleOptions(request, response) {
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "POST, GET, OPTIONS",
"Access-Control-Allow-Headers": request.headers["access-control-request-headers"]
});
response.end();
}
function server(request, response) {
if(request.method == "POST") {
handlePost(request, response);
} else if(request.method == "OPTIONS") {
handleOptions(request, response);
} else {
handleOther(response);
}
}
https.createServer(sslObj, server).listen(9001);
You can fill in the details and whether you should handle GET separately, and so on (handleOther should return an appropriate error code for each request method you don't support).