jQuery AJAX and Google Currency calculator - javascript

I have some code that performs an AJAX call to the google currency calculator. Which in theory should return a JSON array that i can ten use to get some exchange rate related data.
The Link is:
http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY
Going to the link shows
{lhs: "1 U.S. dollar",rhs: "6.49148317 Chinese yuan",error: "",icc: true}
My javascript code (I tired this with both POST and GET):
jQuery.ajax({
type: "GET",
url: "http://www.google.com/ig/calculator",
data: "hl=en&q=1USD=?CNY",
success: function(msg) {
var currency = $.parseJSON(msg);
alert (currency ['rhs'];);
}
});
Examining fire bug shows in red with an empty response
GET http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY 200 OK 255ms
What am I doing wrong?

You can't perform cross domain requests with jQuery. You need to use JSONP to perform this request. These links might help:
http://api.jquery.com/jQuery.getJSON/#jsonp
jsonp with jquery
JSONP requests are not subject to same-origin policy restrictions.

heard google has stopped services from iGoogle from Nov 1st..
the link no longer works.

As we know google has stopped services from iGoogle from Nov 1st/2013..
But we can use https://www.google.com/finance/converter to get the real time data.
Following example of jquery will work for you.
function CurrencyConvetor(amount, from, to) {
var result = '';
var url = "https://www.google.com/finance/converter?a=" + amount + "&from=" + from + "&to=" + to;
$.ajaxSetup({async: false});
$.get(url,
function (data) {
var startPos = data.search('<div id=currency_converter_result>');
var endPos = data.search('<input type=submit value="Convert">');
if (startPos > 0) {
result = data.substring(startPos, endPos);
result = result.replace('<div id=currency_converter_result>', '');
result = result.replace('<span class=bld>', '');
result = result.replace('</span>', '');
}
})
return result;
}

Related

How can I setup a cross-domain call in Tampermonkey to get a divs contents

I have been toying around with this for a few days now and I don't feel any closer to successfully gathering a string of data within a tampermonkey script. The closest I have gotten to a result was using this code http://jsfiddle.net/peterbenoit/N7avm/ that successfully loaded the webpage/data, but once I tried to add it as a tampermonkey script the familiar cross domain error occurred.
Refused to load the script 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where…t=xml%27&callback=jQuery21407879608951028498_1460047110140&_=1460047110141' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' http://steamcommunity-a.akamaihd.net/ https://api.steampowered.com/ http://www.google-analytics.com https://ssl.google-analytics.com https://www.google.com https://www.gstatic.com https://apis.google.com".
$(function() {
var container = $('#target');
var msg = $('#msg');
var url = 'http://peterbenoit.com';
$.getJSON("http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(url) +
"%22&format=xml'&callback=?",
function(data) {
if (data.results[0]) {
var data = filterData(data.results[0]);
msg.html('(ready.)');
container.html(data).focus().effect("highlight", {}, 1000);
} else {
msg.html('(error!)');
msg.addClass('error');
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg).focus().effect('highlight', { color: '#c00' }, 1000);
}
}
);
});
function filterData(data) {
// filter all the nasties out
// no body tags
data = data.replace(/<?\/body[^>]*>/g, '');
// no linebreaks
data = data.replace(/[\r|\n]+/g, '');
// no comments
data = data.replace(/<--[\S\s]*?-->/g, '');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
// no script blocks
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
// no self closing scripts
data = data.replace(/<script.*\/>/, '');
// [... add as needed ...]
return data;
}
So the jist of what I am trying to do is run a personal userscript that displays content on site A and I want it to gather one string of data from a div on site B (div class="preview k_wear_float") and display it on site a within var message. I have tried iframes, JSON, xmlhttprequests and currently not had any luck whatsoever in even accessing the data so if anyone can help point me in the right direction that would be good.
I have basic understanding of js but I am still a newbie so please explain slightly more than you would the average user if at all possible just so I can try and understand the process a bit better.
Try this
$.ajax({
type:'GET',
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22&format=xml'&callback=?",
async:false,
contentType: "application/json",
dataType: 'jsonp'
}).done(function(data){
console.log(data)
});

is it possible to redirect the user to same page after login using client side technology

I have searched quite a lot regarding my problem and I couldn't find any relevant tutorial. Moreover, I am not even sure if it is possible using client side technology.
Problem statement: For e.g I have many pages in my web app and if a user switch from index page to page 1 and then page 2. Now the user decides to login to my web site. I want to redirect the user to page 2 once the login is successful.
Current outcome: Once the login is successful user always seems to get redirected to the index page.
Desired outcome: Once the login is successful the user should stay on page 2.
Is it possible using client side technology? In PHP we could use sessions and all. But I am confined on using client side technology to achieve that.
Here is my login function
function login(params) {
if(checkEmpty("loginEmail") && checkEmpty("password")) {
var emailField = $("#loginEmail").val(),
passwordField = $("#password").val(),
data = "login=" + emailField + "&password=" + passwordField;
for (var key in params) {
data += "&" + key + "=" + params[key];
}
// Hide errors as default
$("#loginErrorWrapper").hide();
// Try to launch the "normal" submit operation to make browser save email-field's value to cache
$('#loginSubmitHidden').click();
// Send data to server and refresh the page if everything is ok
$.when(loginPost(data)).done(function(map) {
if(!hasErrors(map)) {
var lang = map.language;
if (lang != "") {
changeLanguage(lang)
}
else {
lang = 'en';
}
redirect("/" + lang + "/");
} else {
if (map.errorCode == "155") {
$.fancybox({
href : '#termsAcceptancePopup',
title : '',
beforeLoad : function() {
$('#acceptTermsButton').attr('onclick','javascript:login({policyChecked:true});$.fancybox.close();');
},
helpers : {
overlay : { closeClick: false }
}
});
} else {
var errorString = getErrorMessage(map);
$("#loginErrorWrapper").show();
$("#loginErrorWrapper").html(errorString);
}
}
});
}
}
Ajax request
function loginPost(data) {
return $.ajax({
url: "/some-api/login",
type: "POST",
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: true,
data:data
});
}
P.S -> I am not using PHP at all. I am working on a Java based web app.
So I have tried all the methods suggested in the comment section and all of them worked.
1) Using location.reload()
Once the user is logged in it just refresh the page.
2) Saving the last URL in a cookie
Calling the below function before calling redirect.
createCookie(value1, value2, value3);
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
3) Removing redirect("/" + lang + "/"); from my function since I am using ajax for login. However this method is not useful because once the user is logged in he/she will never know whether everything went fine or not unless he/she refresh the page manually or go to another page.
I am not certain which method is better (performance and loading time) - method 1 or method 2.

Call MVC action method by javascript but not using AJAX

I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>

Get Vimeo thumbnail for video using jQuery

I've found similar questions but none of the answers show clearly and easily how to get a thumbnail for a vimeo video using jQuery and JSON. If anyone can help that would be great, here is what I've got but it shows nothing at the moment.
var vimeoVideoID = '17631561';
var videoCallback = 'showThumb';
$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=' + videoCallback,
function(data){
$(".thumbs").attr('src',data[0].thumbnail_large);
});
Thanks in advance.
I believe you're having the "same origin policy" issue. You should consider writing a server side script using something like "file_get_contents" or "fopen", enabling you to grab the data from vimeo, translate it to json, and output to your javascript with a nice ajax call.
If you would like to avoid using a server-side script you may use the data type JSONP.
var vimeoVideoID = '17631561';
$.getJSON('https://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=?', {format: "json"}, function(data) {
$(".thumbs").attr('src', data[0].thumbnail_large);
});
Notice the URL is a bit different from how you are using it. The callback which you defined as a var is unnecessary. You're attaching the getJSON to a function directly, so you'll call the 'callback' in the url '?'. This informs the getJSON function to pass the successful data return to the supplied function.
You can test my code here. Hope it helps!
With the updated API, it would be...
$.getJSON('https://vimeo.com/api/oembed.json?url=https://vimeo.com/' + id, {format: "json"}, function(data) {
$(".thumbs").attr('src', data.thumbnail_url)
});
You can use this function which supports all types of Vimeo links & sizes:
function get_vimeo_thumbnail(url, size, callback)
{
var result;
if(result = url.match(/vimeo\.com.*[\\\/](\d+)/))
{
var video_id = result.pop();
if(size == 'small'){
var video_link = encodeURIComponent("https://vimeo.com/" + video_id + "?width=480&height=360");
$.getJSON('https://vimeo.com/api/oembed.json?url=' + video_link, function(data) {
if(data && data.thumbnail_url){
if (typeof(callback) !== 'undefined') {
callback(data.thumbnail_url);
}
}
});
}
else
{
$.getJSON('http://vimeo.com/api/v2/video/' + video_id + '.json', function(data) {
if(data){
if (typeof(callback) !== 'undefined') {
var thumbnail_src = data[0].thumbnail_large;
if(thumbnail_src){
callback(thumbnail_src);
}
}
}
});
}
}
}
To use it:
// Available sizes: large, small
get_vimeo_thumbnail('https://vimeo.com/475772381', 'large' function(url){
alert(url)
})
Please check out this page; Vimeo has a new method call oEmbed as Vimeo is now pushing it's new oEmbed technology.
The method above, will fail on IE (no thumbs will be shown).

Is it possible to ping a server from Javascript?

I'm making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 entries, it will scale linearly with more).
I decided to go the route of pinging on the user's end. This way, I can load the page and just have them wait for the "server is online" data while browsing my content.
If anyone has the answer to the above question, or if they know a solution to keep my page loads fast, I'd definitely appreciate it.
I have found someone that accomplishes this with a very clever usage of the native Image object.
From their source, this is the main function (it has dependences on other parts of the source but you get the idea).
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.
Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.
Update 2: #trante was nice enough to provide a jsFiddle.
http://jsfiddle.net/GSSCD/203/
Update 3: #Jonathon created a GitHub repo with the implementation.
https://github.com/jdfreder/pingjs
Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.
Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:
function ping(host, port, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host + ":" + port, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}
you can try this:
put ping.html on the server with or without any content, on the javascript do same as below:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
You can't directly "ping" in javascript.
There may be a few other ways:
Ajax
Using a java applet with isReachable
Writing a serverside script which pings and using AJAX to communicate to your serversidescript
You might also be able to ping in flash (actionscript)
You can't do regular ping in browser Javascript, but you can find out if remote server is alive by for example loading an image from the remote server. If loading fails -> server down.
You can even calculate the loading time by using onload-event. Here's an example how to use onload event.
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}
Update: this solution does not work anymore on major browsers, since the onerror callback is executed even if the host is a non-existent IP address.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.
The problem with standard pings is they're ICMP, which a lot of places don't let through for security and traffic reasons. That might explain the failure.
Ruby prior to 1.9 had a TCP-based ping.rb, which will run with Ruby 1.9+. All you have to do is copy it from the 1.8.7 installation to somewhere else. I just confirmed that it would run by pinging my home router.
There are many crazy answers here and especially about CORS -
You could do an http HEAD request (like GET but without payload).
See https://ochronus.com/http-head-request-good-uses/
It does NOT need a preflight check, the confusion is because of an old version of the specification, see
Why does a cross-origin HEAD request need a preflight check?
So you could use the answer above which is using the jQuery library (didn't say it) but with
type: 'HEAD'
--->
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
Off course you can also use vanilla js or dojo or whatever ...
If what you are trying to see is whether the server "exists", you can use the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This will return a true/false indication whether the server exists.
If you want response time, a slight modification will do:
function ping(url) {
var encodedURL = encodeURIComponent(url);
var startDate = new Date();
var endDate = null;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
if (data.query.results != null) {
endDate = new Date();
} else {
endDate = null;
}
},
error: function(){
endDate = null;
}
});
if (endDate == null) {
throw "Not responsive...";
}
return endDate.getTime() - startDate.getTime();
}
The usage is then trivial:
var isValid = isValidURL("http://example.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Or:
var responseInMillis = ping("example.com");
alert(responseInMillis);
const ping = (url, timeout = 6000) => {
return new Promise((resolve, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&##/%?=~_|!:,.;]+[-A-Za-z0-9+&##/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => resolve(true))
.catch(() => resolve(false));
setTimeout(() => {
resolve(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
use like this:
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;
if you run this with node it would console log 200 as long as google is not down.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
just replace
file_get_contents
with
$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) {
echo "no!";
}
else{
echo "yes!";
}
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
You could try using PHP in your web page...something like this:
<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php
$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');
echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";
?>
This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

Categories

Resources