Our server is located in europe.
Now and then an american based user reports a problem when he uses the $.getJSON function.
His browser just displays the json response instead of catching it and passing it to javascript.
The ajax call just looks like:
$.getJSON(url, function(json_data){ ... });
Any ideas?
More info:
The the same user has the problem in FF and IE.
I use Ruby On Rails render :json. which response type is application/json.
Try using the $.ajax() method so you can handle errors and debug the success callback.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(json_data) {
// parse json_data object
},
error: function (xhr, status, error) {
// check for errors
}
});
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
Related
I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.
My Code is as below for Javascript
$.ajax({
type: "POST",
url: "page/rSales.aspx",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function (res) {
alert('Success');
},
error: function (res) {
alert('Fail');
}
});
I use http tracer tools to trace whether or not the parameter is passing on to my backend - and it is not. I have also tried adding contentType: 'application/json; charset=utf-8', adjust parameter by adding colon, but none of it is working.
My Backend code C# :
Request.Params["ListID"].ToString();
It always returns null, due to the parameter not passing on. I am wondering what is causing this problem and how should I resolve it.
The Request.Params collection does not support JSON requests, so you have to parse response body manually (or send it as form data).
https://msdn.microsoft.com/en-us/library/system.web.httprequest.params(v=vs.110).aspx says "Gets a combined collection of QueryString, Form, Cookies, and ServerVariables items."
For firefox you declare var event; before your ajax call this is very well known issue in firefox.
I'd like to create a google-docs add-on that sends an ajax call to a webhook.
I've tried the below, but I get the following error
Error
ReferenceError: "$" is not defined. (line 5, file "")
Code
function myFunction() {
var arr = 'data'
$.ajax({
url: 'webhook_url',
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function () {
alert('Success');
}
});
}
If ajax can't be used here is there any other way to make a request to a server-side resource
This is an OLD question, so I don't know if you still have the issue, but, from the error you're getting Jquery is either not added, or not available.
You could try doing it with vanilla js, see this link for a walkthrough: https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/
I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.
I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON