YQL JSON script not returning? - javascript

I have a script here, copied pretty much directly off this. Why doesn't the code, listed below, return anything?
ajax.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cross-Domain Ajax Demo</title>
</head>
<body>
<div id="container">
<form>
<p><label>Type a URL:</label><input type="text" name="sitename" id="sitename"/></p>
<p><input type="submit" name="submit" id="submit" value="Make Cross Domain Ajax request"</p>
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
$('form').submit(function() {
var path = "www.google.com";
requestCrossDomain(path, function(results) {
$('#container').html(results);
});
return false;
});
</script>
</body>
</html>
cross-domain-requests.js:
// Accepts a URL and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no URL was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided URL, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
(I'm relatively new to scripting and Ajax, so I apologise in advance if I do anything stupid.)

Try changing the callback in var yql to callback=? and the select statement to 'from xml' like this:
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

Related

How can show message while processing a javascript function?

I writing a html page run from file:// (not use webserver)
I want display a message [Loading.....] in div while Page processing create a data
This is my code demo:
before get data i set:
$("#msg").html("Loading.....");
and after get data i set:
$("#msg").html("Done!");
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script type="text/javascript">
function search() {
$("#msg").html("Loading.....");
getData();
$("#msg").html("Done!");
}
function getData() {
var html = "";
for (var i = 0; i < 200000; i++) {
html += i + "<br>";
}
$("#data").html(html);
}
</script>
</head>
<body>
<input type="button" id="btnSearch" value="Search" onclick="search(); return false;" />
<div id="msg">Message</div>
<div id="data"></div>
</body>
</html >
How can show message while processing a javascript function?
i try use ajax:
function search() {
$("#msg").html("Loading.....");
$.ajax({
success: function () {
getData();
$("#msg").html("Done!");
}
});
}
But it occuring error:
Access to XMLHttpRequest at 'file:///C:/Users/dt/Desktop/HTMLPage1.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Actually, there are two problems with this code.
1. Trying to make AJAX request over file:// protocol
That's where you get the error from. Doing this is incorrect because of security of the users.
Imagine, that you visit a random website on the Internet, and it can see all of your files on your computer, without even asking for permission or letting you know what it does. In that case, those who use the Internet could say goodbye to private life!
So, instead:
If this file will be on your server, and you're just testing, then do it on a localhost server.
If you want to let the user grant access to one of his/her files, use a filepicker (<input type="file">).
If you want to access users' files without permission, then... look for alternative solutions (web pages cannot do this).
2. Synchronous data processing
Once you've somehow solved to get the files, your example will work. But you'll be unable to update the display during processing. That's why your first example doesn't work.
It will also don't let other rendering, or asynchronous JS code to run. Usually, this isn't a problem, as long as your code doesn't take long time to execute.
But if it does, you'll need to let some scheduled code to execute, during the processing.
You have 2 options:
Use a Web Worker to do heavy synchronous operations without freezing the site
//your HTML file
<script>
async function search() {
$("#msg").html("Loading.....");
await getData();
$("#msg").html("Done!");
}
function getData() {
return new Promise((rs,rj) => {
const worker = new Worker('./worker.js')
worker.onmessage = rs
worker.onerror = rj
})
.then(data => $("#data").html(data));
}
</script>
//worker.js
var html = "";
for (var i = 0; i < 20000; i++) {
html += i + "<br>";
}
self.postMessage(html)
Put setTimeout(..., 0) in your processing code to make it asynchronous and the site usable while processing
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src=" https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script type="text/javascript">
async function search() {
$("#msg").html("Loading.....");
await getData();
$("#msg").html("Done!");
}
async function getData() {
var html = "";
for (var i = 0; i < 20000; i++) {
html += i + "<br>";
if(i % 10 === 0)
//On every 10th iteration, wait some...
await new Promise(rs => setTimeout(rs, 0))
}
$("#data").html(html);
}
</script>
</head>
<body>
<input type="button" id="btnSearch" value="Search" onclick="search(); return false;" />
<div id="msg">Message</div>
<div id="data"></div>
</body>
</html >
Good question!
AJAX and XMLHTTP requests send messages over HTTP Protocol. HTTP is a protocol for sending messages over the internet. You must use a webserver, or at least call to localhost, in order to make a HTTP request from your clientside code.
If you really want to just show a "loading" message, sending your request to localhost will at least allow you to "SEND" your HTTP request. Just know that your request will always fail unless you set up a webserver on localhost to answer it. You could write your "Done!" in an ajax fail function in that case:
$.ajax({
success: function () {
getData();
$("#msg").html("This will never show up until you set up a webserver that you called from localhost");
}
fail: function () {
getData();
$("#msg").html("Done! (This is showing because you called from localhost)!");
}
});

Redirect after processing a POST request in Apps Script

I have had an issue with getting the google scripts page to redirect back towards my custom URL. The script currently executes but I cant get it to redirect back to its previous page after it is finished executing.
Heres the script.gs code:
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
var name= String(mailData.name);
var message= String(mailData.message);
var email= String(mailData.email);
var all= ("Name: "+name+"\nReply address: "+email+"\nMessage: "+message);
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
MailApp.sendEmail({
to: String(sendEmailTo),
subject: String(mailData.subject),
replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
body: String(all)
});
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="2;url=xxxxxxxxxx.com" />
<base target="_top">
</head>
<body>
Click here to go back.
</body>
</html>
What would be the best way to make the script open the index.html page so I could easily redirect back to the custom URL?
Here's a working example of redirecting after processing a POST request.
Code.gs
var REDIRECT_URL = "http://www.stackoverflow.com";
function doPost(e) {
Logger.log("POST request");
Logger.log(e)
return redirect();
}
function doGet() {
Logger.log("GET request");
var template = HtmlService.createTemplateFromFile("form");
template.url = ScriptApp.getService().getUrl();
return template.evaluate();
}
function redirect() {
return HtmlService.createHtmlOutput(
"<script>window.top.location.href=\"" + REDIRECT_URL + "\";</script>"
);
}
form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form action="<?= url ?>" method="post">
<input type="text" name="test_field" value="test data">
<button type="submit">Submit form</button>
</form>
</body>
</html>
Usage
When I visit the published web app (i.e. using a GET request), I'm presented with the simple form.
Submitting that form (i.e. using a POST request), I'm immediately redirected to http://www.stackoverflow.com.
This output is captured in the script log:
[18-06-19 10:39:04:731 PDT] POST request
[18-06-19 10:39:04:732 PDT] {parameter={test_field=test data}, contextPath=, contentLength=20, queryString=, parameters={test_field=[test data]}, postData=FileUpload}
Regarding your code sample, you have:
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
That doesn't make sense as you're not doing anything with the results of doGet(). In order to make the doGet() call useful, replace the above with the following:
return doGet();

YouTube API -- extracting title and videoId attributes to build hyperlink

The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See link to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'clapton'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.

Form data not visible in new page - PHP + Javascript

I have a page containing a set of hyperlinks. Clicking on any of the hyperlinks should take the user to a new page with the url sent as POST data.
What I am able to do:
1. Open the new page.
What issues I am facing:
1. In the new page, I am trying to access the url that was sent across as data. The url is not visible. Where am I going wrong?
The code I have so far:
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function takeMeHome(obj) {
var URL = obj.getAttribute("href");
//alert("Url = " + URL + " with id = " + obj.id);
console.log("URL = " + URL);
$.ajax({
type: 'POST',
url: './bbCloud.php',
data: {'tgt_url': URL},
success:function(data) {
console.log("Function invoked. It seems posting data was a success");
window.location = URL;
//alert('This was sent back: ' + data);
}
});
return false;
}
</script>
</head>
<body>
<p>
Choose one of the links below to access content:</p>
<p>1. Email Etiquette</p>
</body>
</html>
bbCloud.php:
<?php
//the function below displays data from bbMainPage javascript.
function getDataFromLibrary() {
$tgt_url = $_POST["tgt_url"];
echo "Data received = " . $tgt_url . "<br/>";
return $tgt_url;
}
?>
<html>
<head>
<style>
.hlight{background-color:#ffcc00;}
textarea {
width:100%;
height:100%;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://myDomain/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
//mention all global variables here.
console.log("this is the start of javascript");
//get all data from the previous script.
var tgtURL = "<?php getDataFromLibrary(); ?>";
console.log("URl obtained = " + tgtURL);
</script>
<body>
<div>
<audio id="playText" src="" controls></audio>
</div>
</body>
</html>
try dynamically creating and submiting a form instead of trying to ajax it:
<script type="text/javascript">
function takeMeHome(obj) {
var URL = obj.getAttribute("href");
$('<form>', {
"html": '<input type="text" name="tgt_url" value="' + URL + '" />',
"action": URL
}).appendTo(document.body).submit();
}
</script>
Hmm, if I recall correctly, what is happening is that your $.ajax does indeed send the POST data to your php file. The problem is, that it sends the post data, the php file is executed, and a response is sent back, but its sent back to the $.ajax call itself. You THEN redirect to the php file (and thus run it again), but without the post data coming along. Also, something along the lines of $.('a').click(function(event) { event.preventDefault(); } might be a good idea. I'll try and make a better answer for you when I get home (currently on my phone, shouldn't be long).

How to solve Javascript error: "Error occurred, no handler for data"?

I'm experimenting with OData and I'm trying to capture all "Categories" in the requested link below. Each Category will be displayed in a div. When I try to check the page it gives me the following error message: Error occurred, no handler for data. It just gives me a blank page. How to solve this problem?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1"); // 1.5.2
</script>
<script type="text/javascript" src="datajs-1.0.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
OData.defaultHttpClient.enableJsonpCallback = true;
OData.read("http://services.odata.org/Northwind/Northwind.svc/Categories",
function(data, request) {
var html = "";
for (var i = 0; i < data.results.length; i++) {
html += "<div>" + data.results[i].Name + "</div>";
}
document.getElementById("Categories").innerHTML = html;
},
function(err) {
alert("Error occurred " + err.message);
});
});
</script>
<title>Categories</title>
</head>
<body>
<div id="Categories"></div>
</body>
</html>
I did it like:
Used datajs-1.1.2.min.js instead of datajs-1.0.1.min.js.
Changed in the for loop:
$(document).ready(function () {
OData.defaultHttpClient.enableJsonpCallback = true;
OData.read("http://services.odata.org/Northwind/Northwind.svc/Categories", function (data, request) {
var html = "";
for (var i = 0; i < data.results.length; i++) {
html += "<div>" + data.results[i].CategoryName + "</div>";
}
document.getElementById("Categories").innerHTML = html;
}, function (err) {
alert("Error occurred " + err.message);
});
});
May be below like will help you.
http://datajs.codeplex.com/workitem/392
https://datajs.codeplex.com/discussions/344801
If your service uses OData version 4 then DataJs will call the error handler because it doesn't know how to parse the response. If you look into datajs.js file you will see the "3.0" hard-coded in there, meaning this is the version for which was designed.
Here is a status report as of May 2014 that confirms the above: http://www.odata.org/blog/status-updates-of-odata-libraries-that-support-odata-version-4-0/. It seems there wasn't any update on datajs to handle OData v4.
For OData version 4 you can use another javascript library called Olingo as described here: http://olingo.apache.org/doc/javascript/index.html
Another library you can use is BreezeJs that has an adapter for version 4. See this other question: Breeze | datajs - no handler for data

Categories

Resources