JSON - CORS confusion - json

I am having a problem with retrieving JSON feeds to use in a widget.
I have googled the hell out of it and just seem to be confusing myself more.
I have this code
function insertReply(content) {
document.getElementById('holder').innerHTML = content.result;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
from this post - Get JSON data from external URL and display it in a div as plain text
Which works great. However if I change the URL i get no response and no errors in the console.
new URL: http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG
Why does one work and not the other?
EDIT #Amit
Amit Sorry for being retarded but I am really new to JQuery and javascript. Where do you put these? I have
<!DOCTYPE html>
<html>
<head>
<title>Widget Holder</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</style>
</head>
<body>
<form runat="server">
<div id="holder"></div>
</form>
<script type="text/javascript">
$().ready(function () {
$.get("http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG", function (data) {
debugger;
$("#holder").html(data);
});
});
</script>
</body>
</html>
But still get this error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I managed to fix the issue using a PHP proxy to fetch the data. The proxy I have used can be found here http://benalman.com/code/projects/php-simple-proxy/examples/simple/
Thank you for all your help on this subject.

The script:
$().ready(function () {
$.get("http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG", function (data) {
debugger;
$("#holder").html(data);
});
});
The html:
<form runat="server">
<div id="holder"></div>
</form>
is working for me.

Related

There was an error during the transport or processing of this request. Error code = 10, Path = /wardeninit

I'm trying to pass an object (contents of a sheet row) to an apps script template. You can see the row in the screenshot.
my function in apps script contains:
var sendableRows = rows.filter(function (row) { //ONLY CHECKED ROWS.
return row['Index'] == true;
});
var sendableRow = sendableRows[0];
Logger.log('sendableRow '+ JSON.stringify( sendableRow));
var html = HtmlService.createTemplateFromFile('RowPopup');
html.row = JSON.stringify(sendableRow);
var h =html.evaluate();
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(h, 'Create Documents');
The logger statement produces:
sendableRow {"Index":true,"Timestamp":"2019-02-12T21:09:14.000Z","FROM":222222,"CONVERSATION":"THIS IS A TEST","ME":"","relativeRow":14,"absoluteRow":15}
My Rowpopup.html is :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('forms');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
// the output from form goes to processDocBuildHtml
google.script.run
.withSuccessHandler(updateUrl)
.processRowPopupHTML(formObject);
}
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Sent!';
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<div>
<label for="optionList">Click me</label>
<select id="optionList" name="email">
<option>Loading...</option>
</select>
</div>
<br>
<div>
</div>
<br>
<div>
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
</div>
<div id="textboxes"></div>
<div id="insert"></div>
<input type="submit" value="Submit" />
</form>
<div id="output">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
<script>
function getConversations() {
var jsonRow = <?= row ?>; //PASSED IN JSON
console.log('row');
var myObj = JSON.parse(jsonRow);
console.log(myObj['CONVERSATION']);
return myObj['CONVERSATION'];
}
</script>
</body>
When I run this I see:
Which shows some issue with "warden".
Also, I don't see the expected data outputted to console in:
console.log('row');
var myObj = JSON.parse(jsonRow);
console.log(myObj['CONVERSATION']);
What am I doing wrong?
Your client side code never calls getConversations, that is why you don't see it on the console. Among many ways to do this, you could add an IIFE to call that function by adding the following on between <script> tags
(function (){getConversations()}());
By the other hand, the referred error message on the Chrome Developers Tools Console occurs even with the simplest code like the following
function myFunction(){
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Test')
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Hello world!
</body>
</html>
So it's not you, it's Google
I know this answer is not related to this OP and the place I should post is not appropriate, but for the other people who reach this page in future, I leave an answer here because I struggled to solve similar problems.
I think this error means we cannot connect from an HTML file to the scripts written in Script Editor.
So basically you can ignore this error message(maybe. If not, tell me the correct feature.)
To me, the error has occurred when executing google.script.run.myFunction(). So, at the first, I thought the error prevents this execution. However, the error was completely unrelated to this execution. It was another problem and I detected why my issue had happened by using withFailureHandler(onFailure). It emits an error message. (See more information at https://stackoverflow.com/a/33008218/3077059)
As Mr. Rubén says "So it's not you, it's Google", this error can be replayed, easily. Please don't be puzzled by this message. The error message("There was an error during the transport or processing of this request. Error code = 10, Path = /wardeninit") is useless, I think.
Ruben's great post is this -> https://stackoverflow.com/a/54756933/3077059
You have only declared the function getConversations. It's not executed until call it ().
To execute directly on loading, try
(function getConversations(){})()
I had a similar problem. But in my case, most of my users didn't have the issue. Just some users in some PCs. Then I found out that, in these cases (about 10%), if they installed Firefox and ran the app, everything worked just fine. So that was my solution: suggest Firefox when this behavior occurred.
My solution: use versioned deployments of library scripts.
I had a similar issue where I was unable to run my own functions from the sidebar in Google Sheets. The issue seemed to be connected with using a library, even though the scripts that I was attempting to execute were not dependent on the library.
When the library was connected to the container script i couldn't get functions in the sidebar to execute. When I removed the library it all worked fine. I was using the head version of the library, meaning the most current development. I decided to try managing deployments and creating versions of the project. I added a Library deployment and version, then updated my library reference, and everything works again.
References:
Why does my apps script deployed as API executable return Permission Denied?
https://developers.google.com/apps-script/concepts/deployments
A descriptive alert from Google would be helpful.
To anyone getting this error. Try to run the code in another browser, Safari, or in guest mode.
In my case, it was probably some extension, I'm still not sure but I have already spent hours on this so I won't further investigate.

Angularjs <script> received via json place in HTML code

I have seen quite a few similar questions but they all seem to be related to <p> tags and are not working for scripts.
The below snippet is a e-signable pdf - it is not rendering in here for some reason but if placed in a .html it would just be a basic pdf with 2 signable fields.
<script type='text/javascript' language='JavaScript' src='https://secure.eu1.echosign.com/public/embeddedWidget?wid=CBFCIBAA3AAABLblqZhBErQXBc488fW6dc9TExmomSqMLibzpk1duAQnawv3c1xGBoAjI-zvPUGWe1goCLs0*'></script>
I receive the script via json and I am trying to embed it onto a html page on when it is returned. I am using ngSanitize This is what I have tried so far...
Angular:
vm.someFunction = function () {
$http({
url: 'https://api.eu1.echosign.com/api/rest/v5/widgets',
method: "POST",
data:
{
// ... json data
}
}).then(function (response) {
$scope.data = response.data;
$scope.script = {content : response.data.javascript };
}
)};
});
HTML:
<div ng-app="MyApp" ng-controller="MyCntrl as vm">
<p ng-bind-html="script.content"></p>
</div>
I have seen that link it is returning a javascript function as a string.
document.write('<iframe src="https://secure.eu1.echosign.com/public/esignWidget?wid=CBFCIBAA3AAABLblqZhBErQXBc488fW6dc9TExmomSqMLibzpk1duAQnawv3c1xGBoAjI-zvPUGWe1goCLs0*&hosted=false&token=&firstName=&lastName=&nameEditable=true" width="100%" height="100%" frameborder="0" style="border: 0; overflow: hidden; min-height: 500px; min-width: 600px;"></iframe>');
you can do is eval:
eval($scope.script.content)
but there is a problem your webpage get overridden by the eval code.
the best way is to open a new tab, get the reference of opener property.
var newWindow = window.open();
newWindow.opener.window.eval($scope.script.content);
Solved using:
var myWindow = window.open("http://pdf.test/input.html");
myWindow.document.write($scope.script);

How can i get response coming from web server

i have a form, i am asking customer to enter few details,
<form id="redirectForm" accept-charset="UTF-8" method="post" action="https://test.test.com//api/v1/order/create" >
customerName: <input type="text" name="customerName" value=<%=customerName %> />
customerEmail: <input type="text" name="customerEmail" value=<%=customerEmail %> /><br><br>
customerPhone: <input type="text" name="customerPhone" value=<%=customerPhone %> /><br><br>
signature:<input type="text" name="signature" value=<%=signature %> />
On submit page redirect according to action of form and display a JSON type response(status + payment link).
response is like:
{"status":"OK","paymentLink":"https:\/\/test.test.com\/billpay\/order\/3ackwtoyn7oks4416fomn"}
Help me out with this
i am working in jsp.
thank you in advance.
Since this look like a simple Webservice answer (not a full HTML page), I would use Ajax to send the form and manage the response.
With JQuery, this is easy using $.ajax
$.ajax({
url: //the URL
data: //the form value
method: //GET/POST
success: function(response){
//decode the JSON response...
var url = $.parseJSON(response).paymentLink;
//then redirect / not sure since this could be cross-domain...
window.loacation = url;
},
error: function(error){
...
}
})
The only think is that the form should not be send with a submit input, you need to link a button to a function doing this Ajax call.
This can be done without JQuery but I can write this from memory ;)
If you can edit the JSP creating the response, you could generate an HTML to return the value directly.
<html>
<head>
<script>
window.location.href = '${paymentLink}';
</script>
</head>
<body>
Redirection ...
<br>If nothing happend, you can <a href='${paymentLink}'>click here</a> to be redirected.
</body>
</html>
Where ${paymentLink} is a EL that will print the value of this variable (well the name it has on the server) to complete the script with the URL.
Once it is received by the client, it will be executed.
Of course, this will not be cross-domain on every browser. If this is not, you will need to provide the link to the user with <a href='${paymentLink}'>Redirection</a> itsefl.
Try this...
while submitting the form write one JS function and get the URL value.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function check(){
//here you have to get value using element name or id (val1,val2,val3)
$.ajax({
type:'GET',
data: {customerName: val1, customerEmail: val2,customerPhone: val3},
url:'https://test.test.com/billpay/order/3ackwtoyn7oks4416fomn',// Replace with Your Exact URL
success: function(response){
alert(response);
var json = JSON.parse(response);
var values = json.values;
for(var i in values)
{
var New_redirect = values[i].address;
alert(values[i].address);
}
window.loacation=New_redirect;
}
});
})
}
</script>
</head>
i think you are looking for response message and redirecting to somewhere
if so you can use the following code
if(condition)
{
response.sendRedirect("urpage.jsp");
}
or
if(condition)
{
request.getRequestDispacher("page.jsp");//enter the name of page you want to redirect inside ""
}

ajax doesn't show any response to a list of json objects, as rest api response

I use Spring for running my rest API service, i cant get the list of json object that my service send from a sample html file and plz tell me how can i access to the first object.
this is the sample output of my rest API service:
[{"src_ip":"1.1.1.1","src_id":"98","date":1470527874000},
{"src_ip":"1.1.2.1","src_id":"25","date":1470527934000},
{"src_ip":"1.1.2.1","src_id":"25","date":1470527934000}]
and this the code that i used in my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing Results</title>
<!--TODO badan version e CDN e jquery use shavad-->
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:8080/restapi2",
dataType: "jsonp"
}).then(function(data) {
$('.List').append(data);
$('.data').append(data[0]);
});
});
</script>
</head>
<body>
<div>
<br><br>
<p class="List"></p>
<br><br>
<p class="data"></p>
</div>
</body>
</html>
I should say that when i run the sample of this link on my html file, it worked Properly.
Updated part:
after fixing last error,still I didn't get any correct data to show in my browser, but this time, the console get something but i don't know how to use them. this is a snapshot of it and the left side show that two object were sent.
and this content of that object:
Based on the discussion on the comment the reason is you were trying to access the different domain than your page which is prohibited by browsers as a security precaution.
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/restapi2"
}).then(function(data) {
$('.List').append(data);
$('.data').append(data[0].);
});
});
"No 'Access-Control-Allow-Origin' header is present on the requested resource"

Converting from NATIVE to IFRAME sandbox

I have a large application that I want to convert from NATIVE to IFRAME sandbox now that NATIVE is deprecated. The general flow of the application is as follows: The user fills out a form on the beginning page and presses a Begin button. The beginning page is then hidden, and based upon values from the first page, the user is then shown a new page. My problem when using IFRAME is that the new page is never shown. It works as expected in NATIVE mode. I have created a simplified script that exhibits the problem. Please help me understand what I am forgetting or doing wrong.
Code.gs
function doGet() {
Logger.log('enter doget');
var html = HtmlService.createTemplateFromFile('BeginHeader').evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function include(filename) {
Logger.log('enter include');
Logger.log(filename);
var html = HtmlService.createHtmlOutputFromFile(filename).getContent();
Logger.log(html);
return html;
}
Javascript.html
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js">
</script>
<script
src="https://apis.google.com/js/api.js?onload=onApiLoad">
</script>
<script>
function showForm(hdr) {
console.log('enter showform');
console.log(hdr);
console.log('hiding first page');
document.getElementById('beginDiv').style.display = 'none';
var el = document.getElementById('recordDiv');
el.innerHTML = hdr;
console.log('showing new page');
el.style.display = 'block';
}
function oops(error) {
console.log('entered oops');
alert(error.message);
}
</script>
<script>
$(document).ready(function() {
console.log('begin ready');
$("#beginForm").submit(function() {
console.log('enter begin submit');
//console.log('hiding first page');
//document.getElementById('beginDiv').style.display = 'none';
console.log('including page 2');
google.script.run
.withSuccessHandler(showForm)
.withFailureHandler(oops)
.include('Page2');
});
});
</script>
BeginHeader.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="beginDiv" style="display:block">
<p>Click on Begin. </p>
<form id="beginForm">
<input type="submit" value="Begin">
</form>
</div>
<!-- results of content being filled in -->
<div id="recordDiv"></div>
<?!= include('Javascript'); ?>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<body>
<p> This is page 2. </p>
</body>
</html>
There is no point in ever using a button of the "submit" type, unless you want to force the form to make an HTTP Request, and reload the application. That's what a "submit" type button does. It causes the page to be reloaded. The "submit" type button is meant to work together with a form in a certain way. It causes a GET or POST request to happen. That's what the problem is. So, you'll need to reconfigure things a little bit.
Just use a plain button.
<input type="button" value="Begin" onmouseup="gotoPg2()">
I created a gotoPg2() function to test it:
<script>
window.gotoPg2 = function() {
console.log('enter begin submit');
//console.log('hiding first page');
//document.getElementById('beginDiv').style.display = 'none';
console.log('including page 2');
google.script.run
.withSuccessHandler(showForm)
.withFailureHandler(oops)
.include('Page2');
};
</script>
If you use that, they you don't need the $(document).ready(function() { etc. code anymore. And, if you don't need that code, then you don't need to load jQuery.
Unless you are using jQuery for other things, then you don't need:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js">
</script>
The NATIVE mode was probably blocking the intended usage of the "submit" request. That's why the code in NATIVE was working. IFRAME allows things to work as they are built and intended to work, which means that the page was probably trying to be reloaded, and an error was occurring. I was getting a 404 page error in the browser console.