I have written a code in bottle in python which gets data from mongodb and when the user request the url http://localhost:8080/index/test from bottle it will return the json result from mongoDB. it works fine when I point my browser to that url, I can see all the result on the browser.
However when I try to send a request from jQuery ajax I always get error, and the request never succeeds.
Has anyone ever done anything similar who can share their approach with me?
MY general question is, what the best way to get data from MongoDB from client side, when using bottle as the server. I have seen some example in Node.js but I want to use python as the server.
I have used this code.
$.ajax({
type: "POST",
url: "http://localhost:8080/hello/test",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("success");
},
error: function (response){
console.log("failed");
}
});*/
And I have also tried this :
$.post( "http://localhost:8080/hello/test", d)
.done(function( response ) {
console.log("success");
});
no luck with any of these. I have also tried GET instead of post, but no luck.
This is kind of what I have in python side :
from bottle import route, run, template
#route('/hello/<name>')
def index(name):
return {'status':'online', 'something':'blah blah'}
run(host='localhost', port=8080)
Many thanks in advance.
First of all 'GET' is the better alternative since you are not passing any params to your DB.
Secondly on which port is your application running? You are adding 8080 to your request which lets me assume your app is running under a different port. JS is based on the Same Origin Policy that means if you want to access data from a different URL (different port = different url) it won't give you any repsponse data.
To make this work either make sure the python script is passing the information to your application directly or you have to implement Cross Origin Ressource Sharing.
To do this you have to add a header to the response of your python (port 8080) script with the following content
Access-Control-Allow-Origin: localhost:XXXX //replace XXXX with your application port
EDIT:
If you need to know how to activate COR check out this thread on stackoverflow:
PY Bottle enable COR
Related
I'm trying to use a certain service to check for proxies. They have a simple API from which they return JSON. I'd like to get this JSON on my server.
No matter what I do, I either get a CORS request problem or a SyntaxError: missing ; before statement message.
Here's my code:
<h1>Test Page</h1>
Test Button
<script>
function checkProxy() {
console.log("Checking...");
$.ajax({
url: 'http://api.ip2proxy.com/?ip=105.159.246.30&key=demo',
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
}
Clicking my 'button' calls the funtion, which returns the aforementioned syntax error. Changing the datatype to JSON gives me a CORS error.
The strange thing is, when I use a different URL -- example that I found in another StackOverflow thread: http://www.locationbox.com.tr/locationbox/services?Key=3430000202000191008400080609030X20201090060050260003069&Cmd=IlList -- it logs the data just fine.
I'd like to get this JSON on my server.
You'll need to write code that runs on the server to do that. The reason your code is failing is that you're running it on a browser, where the Same Origin Policy comes into play: Your page's origin isn't granted access by that API endpoint via CORS. Unless they allow you access, or they provide a JSONP endpoint you can use instead, you cannot directly query it from a browser.
I am running ajax without a server on my system, I have created one index.html with this.
JavaScript function:
function do_the_click(url)
{
alert('inside this method do_the_click');
$.ajax({
async: false,
url : url,
contentType: "text/html",
type : "GET",
dataType : "text/html",
success: function(data){
alert('data');
}});
}
My HTML body content is:
<a href="Java Collections.html" class="button" id="javacollections" onclick="do_the_click('this.href');"/>Java Collections</a>
I'm able to get the this message in alert window inside this method do_the_click but am not able to get the data in alert window, and so not able to get the page Java Collections.html in the index.html,
I have searched very much on Google re. how to load the data locally without using server in jquery.ajax but I didn't find any good solution, so I think that its good for others as well if it resides on Stack overflow.
You cannot do such thing. if you dont have a server you cannot send ajax it will be a cross browser issue. as the others says ajax will not work with file:// protocol you need a server to make an http:// call that ajax supports.
When you are making AJAX requests using stand alone html files, the HTTP request to the url is made by the browser. All you need to make sure is that you have included JQuery. Here is what you have to do.
Include Jquery:
<script src="js/jquery-1.10.2.min.js"></script>
The JQuery here resides in the js folder. This is included in the stand alone html file. Now to make the AJAX request use the following code.
$.ajax({
type: 'GET',
url: url,
success: function(data){
console.log(data);
},
async:false
});
AJAX creates an HTTP request that must be responded to by a server. If you don't have a server you can't use an AJAX request. You can run a server on your computer, but this is not the same as getting a file from the local filesystem.
I m able to run the ajax without webserver the problem was with my code the code written below that i had run on my filesystem u can use that as well.
function do_the_click(brl)
{
alert('inside this method do_the_click');
alert(brl);
var request = $.ajax({
async: false,
url: brl,
contentType: "text/html",
type : "GET",
dataType : "html",
});
request.done(function( msg ) {
alert(msg);
$( "#contentarea" ).load( msg, function() {
alert( "Load was performed." );
});
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
Java Collections
You won't be able to do this. If you don't have a server, you will violate the browser's cross-domain policy, as you won't have a domain!
AJAX won't work via the filesystem, you need a server.
This is an older thread but a browser doesn't need to run on a common OS like OSX/Windows/etc .. many people today are making their own browsers from WPE/Wayland or QT5Webkit where same origin policies don't apply.
Now in current scenario it depends upon where your server at. If the server is some place else, it will require CORS (cross origin request). So using file:// with CORS works perfectly.
I came to this question because I was searching for the reason, why I am able to make ajax request without using a web server. Got the answer Thanks!
I've got a simple python web server based on cherrypy. Its resources shall provide an API. THe server has the following code to provide CORS:
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == "__main__":
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
cherrypy.quickstart(PyCachedAdmin(), config={'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
the server is running on localhost:8080. Now I've got a HTML file, available on localhost (default port 80) which loads jquery 1.9. I open the browser console to try the $.ajax to execute any AJAX request to the cherrypy server. I've been trying:
$.ajax({
url:'http://localhost:8080/',
type: "POST",
dataType: "json",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.ajax({
url:'http://localhost:8080/',
type: "POST",
crossDomain: true,
dataType: "jsonp",
data: {command:"version"}
}).done(function(){
console.log('hej');
});
and
$.support.cors = true
and nothing worked. I'm getting either XMLHttpRequest cannot load http://localhost:8080/. Origin http://localhost is not allowed by Access-Control-Allow-Origin. or GET http://localhost:8080/?callback=jQuery19102827550224028528_1382823727186&command=version&_=1382823727187 404 (Not Found) when using jsonp (it's mysterious that it sends GET instead of POST). There is a few similar questions around, I tried them and these are my results (that something is still wrong).
PS the server is perfectly ok, since all curl tests pass. Something is wrong with the cross-domain stuff.
Are you activating the CORS tool?. You can use the tool by decorating the calling methods or set it on the configuration.
Given that the implementation of PyCachedAdmin is no expressed on the question I might guess that probably you are not enabling the tool, to do so you just need to change the config dictionary and make something like this:
cherrypy.quickstart(PyCachedAdmin(),
config={
'/': {
'request.dispatch':
cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True}})
Or if the methods that you are using on PyCacheAdmin has already been decorated or using _cp_config that extra configuration is not required and this answers will not help you.
I've been trying to interact with the Amazon DynamoDB via JavaScript using jQuery and an Ajax call but have been unsuccessful. After two days of research I am beginning to thing it may not be possible. I see that they have SDKs available for Java, PHP, and .Net, but nothing for JavaScript yet.
Amazon explains how to send a command to dynamo in this link:
http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/UsingJSON.html#JSONMajorExample
I've been able to do it with the PHP sdk and with node.js (https://github.com/xiepeng/dynamoDB), but no luck with a regular javascript ajax call or xmlHttpRequest call.
I have been able to get a valid aws signature, secret id, and session token, so I have hard coded those into the headers.
Here is my code:
$.ajax({
beforeSend: function(xhr) {
console.log("getting built");
xhr.setRequestHeader('host', 'dynamodb.us-east-1.amazonaws.com');
xhr.setRequestHeader('x-amz-date', 'Fri, 10 Feb 2012 20:44:00 GMT');
xhr.setRequestHeader('date', 'Fri, 10 Feb 2012 20:44:00 GMT');
xhr.setRequestHeader('x-amz-security-token', '**MYSECURITY TOKEN**');
xhr.setRequestHeader('x-amz-target', 'DynamoDB_20111205.PutItem');
xhr.setRequestHeader('content-type', 'application/x-amz-json-1.0');
xhr.setRequestHeader('content-length', 103);
xhr.setRequestHeader('x-amzn-authorization', 'AWS3 AWSAccessKeyId=**MY ACCESS KEY**,Algorithm=HmacSHA256,SignedHeaders=host;x-amz-date;x-amz-security-token;x-amz-target,Signature=**MY SIGNATIURE**=');
},
type: "POST",
url: "http://dynamodb.us-east-1.amazonaws.com",
dataType: "json",
data: '{"TableName":"Sample","Item":{"RecordId":{"S":"white"},"Square":{"S":"teess"},"circle":{"S":"eeerer"}}}',
error: function(XHR,textStatus,errorThrown) {
// alert ("XHR="+XHR+"\ntextStatus="+textStatus+"\nerrorThrown=" + errorThrown);
console.log(XHR);
console.log(textStatus);
console.log(errorThrown);
},
success: function(data) {
console.log("success");
}
});
When I run this I get a 404 Not found error, with the method showing as "OPTIONS" (as opposed to POST or GET)
Not very familiar with AWS Dynamo, but am very familiar with HTTP and XMLHttpRequest and Host is not a header that you can set via xhr. XHR pulls the host info from the url that is being requested. Not sure if $.ajax will ignore you trying to set that header or not, but I would try it without it.
Also, how are you calculating your content length? Your string there is 103 characters, but it is not necessarily 103 bytes (depending on encoding, charset, etc), which is how Content-Length is calculated. I would try it without that header as well.
Let us know how it goes!
UPDATE:
I think is falling victim to the 'Same-Origin Policy' that has been a part of Ajax since Microsoft made that decision for everyone. :-) You're going to have to code some sort of server-side proxy that resides on your domain, and make the Ajax requests to/from that.
Are you familiar with PHP? It looks like AWS has a lib for DynamoDB in PHP.
You are attempting to make a cross-domain request with AJAX. This is not something that necessarily works unless both your application and the service are setup for it. AWS does not currently allow requests via the CORS protocol. The OPTIONS header that you saw is your JavaScript making a pre-flight CORS request to AWS, which is being rejected. You will need to use a server-side proxy (which uses one of the SDKs provided by AWS) to make the actual service calls. Your JavaScript can talk to your proxy via AJAX since it will be hosted on the same domain.
I'm horrible at Javascript, so sorry in advance for what I'm going to go ahead and assume is an amazingly stupid question.
I'm simply trying to perform a GET request to GitHub's public repo API for a given user, and return the value as JSON.
Here's the function I'm trying to use:
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'json',
type: 'get',
success: function(data) {
alert('raw data: ' + data)
var json_response = $.parseJSON(data);
alert(json_response);
}
});
}
This is returning Null for data. And in the console, I see Failed to load resource: cancelled. I know the URL is correct, because if I run curl on the url, it returns the expected data.
jQuery's ajax function supports JSONP which allows cross-domain requests (which you need because you're trying to request data from github.com from another domain). Just change the dataType from 'json' to 'jsonp';
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'jsonp',
type: 'get',
success: function(data) {
var json_response = data;
alert(data);
}
});
}
UPDATE: It's import to note that the end pint (in this case github.com's API) has to support JSONP for this to work. It's not a guarnateed solution for ANY cross-domain request as pointed out in the comments.
JavaScript is subject to cross-domain restrictions when making requests on a different server.
Well, unless you run your code in the github.com domain, that won't work.
You can use simle ajax only in your domain.
One solution is to create a proxy for it. Make a page on your server that does one thing, gets your requested (out of domain) content with curl, and prints it. Then you call this proxy with ajax.
The XmlHttpRequest object (which $ajax uses) cannot download content from a different domain due to the same origin policy. You would need to use something such as JSONP to be able to do this from a browser.
As the others have said, you cannot execute ajax on a remote domain.
You will need to write a server sided script on your domain (such as php), that will do the dirty work retrieving the information needed from the github domain.
Then, use your ajax to query your server side script for the information.
I know the URL is correct, because if
I run curl on the url, it returns the
expected data.
Use that idea to get your ajax working. Create a proxy page on your site that uses curl to retrieve the data you want, then have your "the_url" variable point to that page on your site. Cross-domain restrictions prevent you from being able to use ajax in the manner you attempted.