using ajax to request information from MongoDB - ajax

Here's the thing. I decided to start learning Html/CSS/JS this summer and now that I already dominate Static webpages I'm trying to get over Dynamic webpages.
To learn it, I've decided to make a test website that will search (with some filters) books on a database. Since I don't need the database to be relational, I've decided to install MongoDB on my server and use AJAX to communicate with the server, but after some days reading tutorials and going further searching on google, I don't manage to get enough information to make a code that is able to read from the server.
First of all I added a simple JSON book on the database lets assume its url is something like 100.100.100.100:3000/library and the content is:
[
{
"_id":"book1",
"desc":"blablabladescription",
"cost":"15€"
}
]
and now I want to create a button on the html that calls a function to access the database. My general idea on how to do this is this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>mongoDB AJAX demo</title>
<script type='text/javascript' src='jquery-latest.min.js'></script>
<script type='text/javascript'>
function handler() {
var result;
$.ajax({
url: 'http://100.100.100.100:3000/library,
type: 'get',
dataType: 'jsonp',
jsonp: 'jsonp',
success: function (data) {
console.log('success', data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error', errorThrown);
}
});
return result;
}
</script>
</head>
<body>
<button type="button" onclick="handler()">click</button>
</body>
</html>
This code is a general idea I have on the structure on requesting from my server, but I know it's incomplete. I think I should make some new XMLHttpRequest(); variable.open("GET","something",true); variable.send() and also to use some callbacks to deal with async.
I hope you can help me with this doubts. I just need an explanation on how to do this or some website that has a deep tutorial, I've been using http://www.w3schools.com/ basically.
Thanks, bertri

Fortunately you can not access your database from your client-side application directly. You need to have a server-side application to access your MongoDB. Also see this post which is a near-duplicate: Client-side jQuery application with MongoDB
Based on what you feel most at home with (javascript?) the suggested choice for you would be Node.js. In Node.js you set up your connection to the database and a REST-interface to your client-application. If you want to make it really easy for yourself and just purely focus on the front-end I suggest you look into deployd.js on deployd.com. This sets up the whole back-end for you in a NoSQL database. Consequently you make ajax calls to your own API to persist, modify and retrieve objects.

Related

Django ajax response contains cloudflare script

I am learning Django by developing a web application. I have added the site to cloudflare CDN's free service. After a long learning curve i am able to send request to Django application using ajax, but strangely the response contains the script from cloudflare embedded as part of it.
Example ajax response:
<html><body>No arguments passed<script type="text/javascript">
//<![CDATA[
try{if (!window.CloudFlare) {var CloudFlare=[{verbose:0,p:0,byc:0,owlid:"cf",bag2:1,mirage2:0,oracle:0,paths:{cloudflare:"/cdn-cgi/nexp/dok3v=1613a3a185/"},atok:"b4c8a1a8481c9535dc367c9b4c8c52ab",petok:"e3070e55a3a1fceb44356d479cfa086f3dd56bbe-1429555139-1800",zone:"mydjango.in",rocket:"0",apps:{}}];CloudFlare.push({"apps":{"ape":"0c86dff90b5e1a63e6c69c775ca3d309"}});!function(a,b){a=document.createElement("script"),b=document.getElementsByTagName("script")[0],a.async=!0,a.src="//ajax.cloudflare.com/cdn-cgi/nexp/dok3v=7e13c32551/cloudflare.min.js",b.parentNode.insertBefore(a,b)}()}}catch(e){};
//]]>
</script>
</body></html>
The views.py code to return the response:
def send_response(request):
inpval = request.GET.get('inputval','')
if not inpval:
html = "<html><body>No arguments passed</body></html>"
else:
html = "<html><body> %s </body></html>" % inpval
return HttpResponse(html)
Can anyone help me understand how to remove this extra script from cloudflare?
Well, i figured out the issue, cloudflare is adding its own <script> tag just before </body>. So, instead of returning the result with html tags, just retrieved the values and processed them in the client.
Example:
if not inpval:
html = "No arguments passed"

Speed up Sinatra page load with Ajax?

I am using the Sinatra to develop a web application but I am running into long page load time issue.
The application goes through and display a lot of data so I am sure this is the cause but I was wondering if there was a way to have the main erb layout of the page load first and then after that load, the data loads on top of it.
My first thought was AJAX but I am not sure how I would implement this.
Thanks in advance.
You are correct, it may help. The old mantra of "separate that which changes from that which does not" is applicable in any part of programming.
Here's route that returns some data:
require 'json'
get "/time-now/?" do
content_type :json
{time: Time.now.to_s}.to_json
end
and here's some javascript (jQuery ajax) to call it:
$.ajax({
accepts: "application/json",
type: "GET",
url: "/time-now",
dataType: "json",
success: function(res, status, xhr) {
return [$("#time").html(res)];
},
error: function(res, status, xhr) {
return [$("#time").addClass("error")];
},
complete: function(res, status, xhr) {
return [$("#button1").show()];
}
});
(that bit of jQuery may be a little bit wrong, just warning you, it's a copy 'n paste job hacked to fit this example)
Perhaps you could stop serving user pages from Sinatra routes and use static (i.e. prebuilt) pages with javascript in them that make AJAX calls to Sinatra routes. Or a mixture of the two types. Then you've got the start of a web service data API. There are lots of javascript frameworks to help with this, (e.g. Ember, Backbone, Angular and many more) and plenty of API builders alongside Sinatra, like Grape and Weasel Diesel.

Allow my Tumblr blog's content to be accessed by another page

I'm attempting to copy all of the actual content from my Tumblr blog using a script I wrote on a different web page, but I'm having a bit of trouble with gaining access to the content. My ajax call is as follows:
$.ajax({
url: "http://solacingsavant.tumblr.com/",
dataType: 'jsonp',
success: function(data) {
var elements = $("<div>").html(data)[0].getElementsByTagName("ul")[0].getElementsByTagName("li");
for(var i = 0; i < elements.length; i++) {
var theText = elements[i].firstChild.nodeValue;
alert(theText); // Alert if I got something
// This is where I'll strip the data for the items I want
}
}
});
but as it is the console gives me an error of "Resource interpreted as Script but transferred with MIME type text/html" which I looked into here and changed the corresponding meta tag in the HTML of my blog to <meta http-equiv="Content-Type" content="application/javascript; charset=utf-8" /> with no success
I also tried using dataType: 'html' (which makes more sense to me) but I was getting a console error of "Origin is not allowed by Access-Control-Allow-Origin" which I also looked into and added a meta tag to my Tumblr blog with <meta Access-Control-Allow-Origin="*" />, but again didn't succeed
Here is a jsFiddle to work with
Does my approach not work because Tumblr as a whole does not allow changes to Access-Control? If so, how might I work around the issue? If not, what am I doing wrong?
MAJOR EDIT (based on mikedidthis's helpful comments)
It seems that I am not able to do this without a Tubmlr API, so I obtained an API key and now have access to the json results that the API sends out. I am able to get a jsonp object using the API key to in the console. My javascript at the moment:
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/info?api_key=APIkeyGoesHeRe",
dataType: 'jsonp',
success: function(results){
console.log(results);
// Get data from posts here
}
});
This SO post was helpful in understanding how I can change data on my Tubmlr page from the source and find out basic information about the site, but not about how to obtain actual data from individual posts. I tried looking through the results object and was unable to find any data related to posts, nor was I able to append the results to the jsfiddle. So my questions now are, "Can I copy data (say the written text in a post) from individual posts using this approach? If so, how? If not, what other approach should I use?"
A really quick answer
The tumblr API documentation really covers using the API well, however, to give you a little start, lets grab all your Text Posts.
First you need to query the API for any of your post that are of the type Text.
The documentation states (http://www.tumblr.com/docs/en/api/v2#posts) that we should use the following url and specifying the type which we you will set to text:
api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts[/type]
And below is an example based on the OP fiddle.
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/text?api_key=XXXXXXX",
dataType: 'jsonp',
success: function(data){
posts = data.response.posts
$.each(posts, function(i) {
console.log( posts[i].title, posts[i].body )
});
}
});
So for each query of the API, we will receive back an object. You will need to filter this object to get the data you want from it.
In context of the post queries, you can get directly at your posts using data.response.posts object.
To find out what data is available for each post type, the documentation has it covered: http://www.tumblr.com/docs/en/api/v2#text-posts
To the content for each of the Text post types, you need to loop through the posts object and then grab the value for the key named title and body.
Example here: http://jsfiddle.net/ZpFwL/
Bonus Time
It is possible to get posts for all types, by dropping the type from the URL:
http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/?api_key=XXXXXXX"
Remember this is a really, quick example and not for the real world.

ajax form submit cross server

I have several servers on an intranet. I am passing data from one server to be processed on another server. Attempting to use ajax but I am a noob.
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script type="text/javascript">
function print(oForm){
var toggle = oForm.elements["toggle"].value;
var ticket_type_id = oForm.elements["ticket_type_id"].value;
var printer_id = oForm.elements["printer_id"].value;
var store_id = oForm.elements["store_id"].value;
var data = oForm.elements["data"].value;
var dataString = "toggle="+ toggle+ "&ticket_type_id="+ ticket_type_id+ "&printer_id="+ printer_id+ "&store_id="+ store_id+ "&data="+ data;
$.ajax(
{
type:"POST",
url:"http://192.168.12.103/crowncontrol/backend/processes/print.php",
data:dataString,
success: function(data){
alert("successful");
}
}
);
}
</script>
The above URL does not work.
But if I make the url:
"../../../backend/processes/print.php"
Which is the same location, it works fine.
Also if I send it via Anchor Get it works fine:
href="http://192.168.12.103/crowncontrol/backend/processes/print.php?etc"
The reason I am using ajax is, I want my print.php script to run with out the user noticing. The reason I can't use url:"../../../backend/processes/print.php" is because I will be sending information from one server to another servers on my intranet.
Any help would be appreciated. I've spent far too long trying to get it to work on my own.
AFTER help from the answers below instead of the entire ajax code I used:
$.getJSON('http://192.168.12.103/crowncontrol/backend/processes/print.php?callback=?',dataString,function(res){
//alert('Success');
});
also:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript">
This is a result of the same origin policy. You can not perform a normal AJAX requests cross-domain requests for security reasons (see the link about same origin policy).
Fortunately for you jQuery includes JSONP request support which uses script tag injection instead of XMLHttpRequest.
Instead of creating and using an xhr object (XMLHttpRequest which is how ajax is done) it creates a script tag with an src attribute set to your URL. it should work.
Try changing your code to :
$.ajax(
{
type:"POST",
url:"http://192.168.12.103/crowncontrol/backend/processes/print.php?callback=?",
data:dataString,
success: function(data){
alert("successful");
}
}
);
(notice the ?callback=? part)
Here is a jsonp tutorial for jQuery
Here is some information about jsonp and some information about the same origin policy
Easy way to deal with this problem is to make a script file in your server and then route the requests through that server request.Use this logic below:
Instead of making the AJAX request directly to cross domain, make the AJAX request to a new script on your server.
In that script file, get the request and make the required call(to that cross domain address).
Then recieve the response from the cross domain server and send it to the client.
Receive the result from your own server which has required data.
This diagram shows:

Does JSONP require server modifications?

I understand that jsonp is a technique to get around the same origin policy. You basically refer to your json serving server endpoint in a script tag, because script tags are exempt from the SO policy.
My question is: Assuming a server has an endpoint that serves up json, are there any modifications necessary on the server to make use of jsonp in the client?
I think no, but want to be sure....
Yes, JSONP is slightly different when it renders, so your server needs to support it.
JSON looks like this:
{ "name": "value" }
Whereas JSONP looks like this:
functionName({ "name": "value" });
If whatever you're using supports it you're covered, but it's not the same as supporting just JSON. When the server gets a request, for example: http://example.com/json?callback=functionName, the above is what you should render, because how it looks in the page is this:
<script type="text/javascript" src="http://example.com/json?callback=functionName"></script>
This means something that runs needs to be returned, as an illustration, this is valid:
<script type="text/javascript">
functionName({ "name": "value" });
</script>
If your server didn't support JSONP it would effectively be this:
<script type="text/javascript">
{ "name": "value" }
</script>
...and you'll get syntax errors, since that's not valid JavaScript.

Resources