How to download silently with javascript - javascript

I am new in javascript and I have some trouble to complete an activity...
I need working, in the client side, with the information uploaded in a "special" server like this:
http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.json/0a635cdd-ccdd-4a1c-8c88-b53bea431458
I want load it in main memory, without the browser show the explicit download.
I try to use some solutions, but really I have no idea how to proceed to achieve it.
... Beforehand thank you very much
(I am not a native english speaker, I apologize if I do not write well)
[Solved]
I decided, for the moment, use the Whatever Origin services, that returns me something I can read with $.getJSON "Without download" the file.
Resulted:
<script type="text/javascript">
$.getJSON('http://whateverorigin.org/get?url=' + "http://www.uninorte.edu.co/documents/71051/11558879/ExampleData.json/0a635cdd-ccdd-4a1c-8c88-b53bea431458" + '&callback=?', function(data){
alert(data.contents);
});
</script>
Thank you for yours responses, really you gave me lights in order to solve it

Regarding silent part
Your browser is always aware of the network requests which are made from JS. Therefore, the user can always see all the requests and responses by opening developer tools.
Now coming to loading a remote json to the memory in the client
Since you mentioned you are relatively a newbie in JS, I am going to cover the very basic, so please bear with me if you already know it
You need to make an ajax call using an XMLHttpRequest as shown here
However, most people use some library like jQuery while working to abstract checking state of the request and other trivial tasks. This results in making an ajax call as simple as calling a method and providing a callback method to process the response.
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
You may find the example at below link.
http://api.jquery.com/jquery.getjson/
P.S.: Due the less reputation points, I can neither post any supporting images nor more than two links.

Related

How to return the response from a javascript file in JQuery .ajax()?

I'm totally new to jQuery and javascript. Not sure if this is a valid question or not. I was reading the source code for the website I'm currently maintaining. At some places in the code, I need to get the responses from users and send them to a PHP file for data processing and return the result. An example may be as below.
$.ajax({
type: "GET",
url: "get_date.php",
data: {month: $('#month').val(), year: $('#year').val()},
dataType: "json",
success: function(response) {
console.log(response.date)
}
....
})
In the get_date.php file I can write something like this:
...
echo json_encode($output)
Now I want to replace the get_date.php with another javascript file, but I don't know how to return a JSON object like what I did in the get_date.php file. I tried the following code but it doesn't work.
var output = JSON.stringify(js_object)
console.log(output)
Thanks for all the replies! The reason I want to use a js file here is I need to manipulate some HDF5 files specified by the users. As far as I know, php cannot handle HDF5 files easily, but javascript can. I hope this makes the problem clearer.
Any comments would be appreciated!
Okay, here's where you're stumbling:
"Now I want to replace the get_date.php with another javascript file"
You see, the $.ajax(...) construct in your source-code sends an asynchronous request to an external host, not "the same computer." Your computer will construct and send an HTTP(S) request to that computer, then proceed immediately with the next JavaScript statement in the program.
However, at some (unpredictable) future time, the host will send its reply. When it does so ... (hence: "asynchronously ..." the "A" in AJAX ...), and assuming that the request was 200 OK, your JavaScript program will execute the success: function.
The "new" scenario that you describe is fundamentally different from this – a JavaScript file runs on "your own" computer (therefore: "synchronously"), not "a different" one. And you simply can't swap one for the other. You'll have to re-think your design.
Of course, the community here will be happy to assist you. Tell us more ...
If you want to process files, stored on the client, with client-side JavaScript, then you need to be reading them with the file API and not involving Ajax at all.
If you want to run JavaScript server side, then you need to configure your server to run it (or replace the server with one designed to run JavaScript (Node.js + ExpressJS is a common choice)). You can't just submit an HTTP request to a JavaScript file that the server is configured to treat like any other static file for delivery direct to the client.

JavaScript Get Data From Other Site

I'm fairly new to JS and have a question. Would it be possible to pull data off from another website to use in your own? For example, say I have a JS web app that lets a user input their Twitter username and then the script goes to this username and looks for the follower count element and pulls that number off to display back in the web app. I'm sure there are APIs and such to do something like that specific Twitter example, but I'm getting more at the general idea of being able to access data on other sites. How can it be done? Surely there is a way if my browser can access all of that information, right? Would you have to put an invisible iFrame into the app and search through it with JS?
To put it in basic terms for a newbie, this is only possible if the website in question has an API, specifically designed to allow outside access. Sometimes they're pretty easy to understand and set up.
Accessing the content of an outside website in a way it wasn't really designed to support has happened, but it's usually what's known as "hacking". It's sometimes easy to do for very basic types of sites, but most sites that request login information forbid it. (Except through aforementioned APIs). The biggest concern is that if someone is already logged in to Twitter on their browser, an outside site of questionable origin could automatically post bad things to your account while you're not even apparently visiting Twitter.
Yes, it's possible.
The best approach is to use ajax (Asynchronous JavaScript and XML) with jsonp (Javascript Object Notation with Padding) datatype.
To use this method the server you are going to connect should be expecting the request so it can response with jsonp (it's just a json data wrapped by a callback function you defined when you make the request).
The process:
1) Your code make an ajax request to the other server adding a callback function to the url. It's very commom to use "callback" param name, but the server can define the variable name it prefers.
http://other-server-url.com/?callback=myFunction
A good and easy approach here is to use jQuery. If you define dataType:"jsonp" in your ajax call, jQuery handles the process of appending the callback and execute the right function when you get the response. It's a good idea to take a look at jQuery's ajax docs and read a little about jsonp cross domain requests.
$.ajax({
type: "POST",
dataType:"jsonp",
url: "http://other-server.com/",
data: { name: "John", location: "Boston" }
}).done(function( msg ) { // this function will be executed when you get the response
alert( "Data Saved: " + msg );
});
this jQuery method only works if the param name is callback. If it isn't, you should handle by your own, or take a deeper look at documentation to know how to do it with jQuery.
2) The server should be waiting for these "callback" param and response your request with a jsonp data format. It's just json data format wrapped by the function you passed as the callback. Like this:
myFunction({ json-data });
3) When you get the response, the myFunction function will be executed automatically, with the json data as the parameter:
function myFunction(myData) {
console.log(myData); // this will log the data on the browser console
}
I hope I have helped. Good coding.

how to get google results source code with jquery ajax

I want to get some google search results in my website,I know I can get with curl,php but its limited daily for same ip adress. and I dont want to use google search api because its also has limit. So I think I can get with jquery ajax but I m a bit new on that,I am fed up with this problem.
here is my code, its will be always error because of jsonp format, but maybe still there is a way for catch html source code. I see source code comes to my browser but I cant take it like object.I tryed xhr.responseText etc but its gives also SyntaxError, still I cant get.
if you can suggest to me any other ways or if you have any idea with below code please share with me.
Thanks before now
$.ajax({
url:"http://www.google.com.tr/search?q=ercan",
dataType: 'jsonp',
success:function(json){
// I know its wont never succes, because google gives source in html format
alert("Success");
},
error:function(xhr){
//I want to get source code html here, but its giving always parse end syntax error I cant get it
console.log(xhr);
},
});
I am afraid that your only choices are to use the API or server side bridge script. You cannot do cross domain AJAX calls if the server doesn't support JSONP or CORS. There's also a commercial version of the API which allows you to increase the limit of requests you could send.

read content from Twitter sample using Javascript

I'm pretty new to programming, and recently have been playing with Twitter API. From statuses/sample method, how would you read the content of following URL using Javascript?
https://stream.twitter.com/1/statuses/sample.json
Edit: perhaps I shall explain my intention. I'm trying to read the Twitter sample data, read the hashtags every 30 seconds, and then sort them ascendingly every 30 seconds the top 10 hashtags.
The problem is, I'm not even sure how to read the Twitter data in the first place..
Not looking for solutions, but definitely could use some ideas.. especially for getting started.
You should be able to utilize JSONP which is a special type of response back from the server.
It basically takes the response, wraps it in an anonymous function callback, and returns it to the client inside of a script tag thereby calling it when the response gets back to the browser.
​$.ajax({
type: 'post',
dataType: 'jsonp',
url: 'http://twitter.com/status/user_timeline/msdn.json?count=10&callback=?',
success: function (data) {
console.log(data);
}
});​
Inspecting the request url in Chrome's debugger you'll see the request...
https://twitter.com/status/user_timeline/msdn.json?count=10&callback=jQuery1706531336647458375_1335842234009&_=1335842234045
And the response back is...
jQuery1706531336647458375_1335842234009( /* data */ );
Then jQuery wraps the data in the script tag and appends it to the body.
Notice how the callback in the request matches the function call in the response.
Hope that helps!
You can't. Read up on cross site scripting.
Basically you're going to need to proxy your request through the hosting server.

What is AJAX and how does it work? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How does AJAX work?
Note: This is a community wiki post
I've often heard of AJAX being used for providing a user with dynamic content. What is it and how does it work?
AJAX, or (A)synchronous (J)avascript (A)nd (X)ML (which interestingly enough tends to use JSON more these days), is a system in which Javascript uses a browser object to communicate with a remote server. The general use case of this is to be able to update a client's interface without needing to go to another page. Before we begin though, a few words of caution.
Ajax is not recommended for login authentication and posting forms
Users can turn off Javascript, or may be restricted from running Javascript due to IT policies
With this in mind it is advised that you do not use AJAX as the sole solution for critical user functionality! Always have a fallback!
Note: This community wiki post uses JQuery to show the example AJAX calls. It's recommended for newcomers as it hides the browser compatibility issues of making AJAX calls. Please check the JQuery website for more information on JQuery.
Note: The examples use communication with a PHP server, but any server side language will work.
AJAX Callbacks
First we have an AJAX call. In the AJAX call you setup callback handlers for the different types of events that can occur. A common misconception can be shown in the following code:
// Incorrect!
function makeAjaxCall() {
var result = $.ajax({
url: 'ajax/test.html'
});
return result;
}
The problem here is that when your browser makes an AJAX request, it can either come back successful, or as a failure. For example if you try an access a page that doesn't exist, or if the server has an internal error. To keep things as organized as possible, AJAX requires that you create callback functions to handle the data request. The correct way is as follows:
// Correct!
function makeAjaxCall() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
alert('Horray the AJAX call succeeded!');
},
error: function(xhr, error) {
alert('Holy errors batman!');
}
});
}
The Nature of AJAX Calls
AJAX calls can be either Asynchronous or Synchronous. Asynchronous means that the browser will make the AJAX request and continue doing other things. Synchronous means the browser will stop what it's doing until the AJAX call completes. Here is an example of the differences in the two code wise:
// An asynchronous call
// This is the default
$.ajax({
url: '/server.php',
success: function(data) {
alert('Horray the AJAX call succeeded!');
},
error: function(xhr, error) {
alert('Holy errors batman!');
}
});
// This will get called right away
myFunction();
Now for a synchronous call:
// A synchronous call
$.ajax({
url: '/server.php',
async: false, // set the property here
success: function(data) {
alert('Horray the AJAX call succeeded!');
},
error: function(xhr, error) {
alert('Holy errors batman!');
}
});
// This won't get called until the AJAX returns!
myFunction();
WARNING: Synchronous calls make it so the browser can't do anything until the browser completes the call. This could potential lock up the browser! Only use this if you REALLY KNOW WHAT YOU'RE DOING! 99% of the time you want asynchronous AJAX calls.
Note: Synchronous calls don't mean you can get out of not setting callback handlers. You still have to deal with the results using callbacks.
The Client->Server Communication Path
This image illustrates how AJAX is used to communicate with a remote server. First the AJAX code interfaces with a browser object, which makes the actual call to the server. The server then processes the request and sends the result back to the browser, which then looks at the result of the call to determine if it needs to call the success handler, or the error handler. However, there is one issue that can prevent communication at all, which is commonly known as the same origin policy.
Note From the perspective of the server, the AJAX call will look as if the client had made the request manually. That means the server can utilize things like sessions and other client specific data.
Same Origin Policy
The same origin policy basically means that if your AJAX call is from a page hosted on http://www.mysite.com, you can't make a call to http://www.othersite.com as illustrated here:
One way that you can get around this is through a proxy service. This is where you interface with a script on the same server, which in turn interfaces with the site you wish, through CURL calls for example. The following illustrates this proxy method in question:
WARNING Note that the third party server will not see the request as coming from the client, but as coming from the server. Some servers frown upon the same IP making many calls to their servers. This could get you blocked, so verify that the site in question is okay with this setup.
Note: There are some instances where same origin policy doesn't apply, such as Google Chrome extension calls (you have to set permissions for each site though), certain Greasemonkey calls, and Adobe Air.
Now the final concept to go over is how the server returns data for the client to interact with.
AJAX Data Return
Since it's a very popular option, we'll use JSON, or (J)ava(S)cript (O)bject (N)otation, to pass back the data. JSON basically looks like this:
{
color: "red",
value: "#f00"
}
This string can be turned into a JavaScript object, providing easy access to the server results.
WARNING Since this is valid JavaScript, many people use eval() to quickly create js objects. Please don't do this. It opens you up to security issues if the result has malicious code in it. Always use a JSON parser that checks for secure data!
Using the previous example, we can access the different values like so:
$.ajax({
url: '/server.php',
// It's a good idea to explicitly declare the return type
dataType: 'json',
success: function(json) {
alert("The color is: " + json.color + " and the value is: " + json.value);
},
error: function(xhr, error) {
alert('Holy errors batman!');
}
});
Notice how easy it is to access the values of the return. Another popular option is to retrieve HTML from a server and inject it into a <div> or other element. Here is an example of this:
$.ajax({
url: '/server.php',
// It's a good idea to explicitly declare the return type
dataType: 'html',
success: function(html) {
$("#mydiv").html(html);
},
error: function(xhr, error) {
alert('Holy errors batman!');
}
});
// Some JS/HTML here
<div id="mydiv"></div>
In the case of a successful return, the contents of the <div> will be populated with the return HTML.
TODO: Dealing with securing against malicious HTML injection?
Conclusion
This concludes the community wiki post on AJAX. I hope it will be useful in helping you understand AJAX, or as an easy way to answer common questions about it.

Categories