I am calling a SOAP service in my Javascript code, and the response of this service is correct but strings returned does not show letters with accents. So, I have a problem with encoding charset and I am trying the following actions:
1) I ensure that the HTTP response returning string data has the correct charset defined. So, I have checked with https://validator.w3.org/i18n-checker/ that the encoding charset of the URI that I am calling is "utf-8".
2) I have defined charset in the head section of html:
<meta charset='utf-8' content-type="text/xml;charset=UTF-8"/>
3) Also, I call this service with a function in module.js, I have also defined
<script src="node_modules/my_module.js" charset="utf-8"></script>
All three with the same wrong result.
I added an image with the some examples:
image with result strings, where in green square have to say 'Sant Martí de Tous', in red 'Moianès', in blue 'Santa Bàrbara', 'Montsià', in orange 'Torroella de Montgrí', etc
This is a minimum sample code to call SOAP service with tinysoap library:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' content-type="text/xml; charset=utf-8"/>
<title>Test Charset Encoding</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="node_modules/tinysoap/tinysoap-browser-min.js"></script>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
var tinySoap=this.tinysoap;
require(["esri/Map"], function(Map) {
var inputCtrl = document.getElementById("inputString"); // gironès
var outputCtrl = document.getElementById("outputString");
inputCtrl.onchange = function() {
var userTxtValue = inputCtrl.value;
var args = {nom: userTxtValue};
//console.log("[INPUT] : ",args);
//outputCtrl.innerHTML = "<br><b>Input ... </b>" + userTxtValue +"<br>";
tinySoap.createClient(url, function(err, client){
client.localitzaToponim(args, function(err, result) {
var data = result['item'];
//console.log("[OUTPUT] : ",data);
//outputCtrl.innerHTML += "<b>Output ... </b>";
//data.forEach(element => {
// outputCtrl.innerHTML += "<br> "+ element.Nom;
//});
});
});
}
});
</script>
</head>
<body>
Look for place or address ...
<input id="inputString" size="50" value=""><br>
<span id="outputString"></span>
</body>
</html>
This is the result of this process for 'gironès' as input string
There is the error: "Refused to set unsafe header", but I can not see where to set header parameters to connection.
I am still working in that problem: I have checked that strings are encoded as UTF16 with this library: https://github.com/polygonplanet/encoding.js/
using Encoding.detect(string), but Encoding.convert(string,'utf8','utf16') does not work for me, neither Encoding.convert(string,'latin1','utf16'), etc
What is the right way to define the encoding charset? Thank you
Related
I have created a simple login page with hardcoded username and password, I was successful in calling the next page once the login credentials are passed but I am having a tough time passing the user name entered in page 1 to appear on page 2.
I tried to find a way to make user inputs as global variables in js file so I can use the same variables in the second page but I am unsuccessful.
greeter.html
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form);" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<p id = "passwarn"></p>
<script language="javascript" src="source.js">
</script>
</body>
source.js
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are
matching*/
let uid = form.userid.value;
let pswrd = form.pswrd.value;
if(uid == "shiva" && pswrd == "mypswrd") {
window.open('test.html')/*opens the target page while Id & password
matches*/
}
else {
document.getElementById("passwarn").innerHTML = "User name or
password is incorrect!"/*displays error message*/
}
}
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script language="javascript" src="source.js"></script>
<h1> Hello <span id = "UI"></span></h1>
</body>
</html>
I want Hello shiva printed on the test.html page, I do not want to use jquery while doing so, is there any way?
You can simply reference the value from the opening page in test.html.
To make things more straightforward, add an ID to the Username field :
Username <input type="text" name="userid" id="userid">
Then you can grab and display the value from the opened window like this :
<h1> Hello
<script>
document.write(window.opener.document.getElementById("userid").value)
</script>
</h1>
If you want to do things a little more elegantly, you could keep the scripting in your .js file and change the innerHTML of your "UI" span from there.
Bear in mind that cross-origin scripting rules mean that this will only work when served from the same domain.
Following on from the comments from your question two key points to identify
This is a very insecure way to do this
You may want to use cookies if the user if going to traverse many pages (not sponsoring, but I would recommend js-cookie, I have used it for a while and it's pretty robust)
In order to get what i believe you wanted to work i had to do a couple of this.
Put your JS on the page as for testing it quicker to have it all accessible on one page
I use function that is for parameter grabbing (yes this is completely insecure but would achieve what you want, a cookie would be more secure) you can find it here.
I renamed your inputs from names to ID's as they are more accessible in javascript this way.
This function when used with decode and encode URI components in javascript will help you pass the data from one page to another see code below
Greeter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Simple Login Page</h1></script>
<form name="login">
Username<input type="text" id="userid"/>
Password<input type="password" id="pswrd"/>
<input type="button" value="Login" id="LoginSubmit"/>
<input type="reset" value="Cancel"/>
</form>
<p id = "passwarn"></p>
<script type="text/javascript" src="./source.js"></script>
</body>
</html>
then your test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1> Hello <span id="UI"></span></h1>
<script type="text/javascript" src="./source.js"></script>
</body>
</html>
Finally your source.js
window.onload = checkpage(window.location.href);
function checkpage(url){
if(url.split('/').pop() == 'greeter.html'){
document.getElementById('LoginSubmit').addEventListener('click',function () {
var uid = document.getElementById('userid').value;
var pswrd = document.getElementById('pswrd').value;
console.log(uid, pswrd);
check(uid, pswrd);
});
}
else{
document.getElementById("UI").innerHTML = getAllUrlParams(decodeURIComponent(window.location.href)).uid;
}
}
function check(uid, pswrd) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are
matching*/
let redirect = "test.html"
let parameters = encodeURIComponent('uid='+uid);
if(uid == "shiva" && pswrd == "mypswrd") {
window.open(redirect+"?"+parameters)/*opens the target page while Id & password
matches*/
}
else {
document.getElementById("passwarn").innerHTML = "User name or password is incorrect!"/*displays error message*/
}
}
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// set parameter name and value (use 'true' if empty)
var paramName = a[0];
var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();
// if the paramName ends with square brackets, e.g. colors[] or colors[2]
if (paramName.match(/\[(\d+)?\]$/)) {
// create key if it doesn't exist
var key = paramName.replace(/\[(\d+)?\]/, '');
if (!obj[key]) obj[key] = [];
// if it's an indexed array e.g. colors[2]
if (paramName.match(/\[\d+\]$/)) {
// get the index value and add the entry at the appropriate position
var index = /\[(\d+)\]/.exec(paramName)[1];
obj[key][index] = paramValue;
} else {
// otherwise add the value to the end of the array
obj[key].push(paramValue);
}
} else {
// we're dealing with a string
if (!obj[paramName]) {
// if it doesn't exist, create property
obj[paramName] = paramValue;
} else if (obj[paramName] && typeof obj[paramName] === 'string'){
// if property does exist and it's a string, convert it to an array
obj[paramName] = [obj[paramName]];
obj[paramName].push(paramValue);
} else {
// otherwise add the property
obj[paramName].push(paramValue);
}
}
}
}
return obj;
}
So long as your HTML files are in the same folder you can run this. The main thing to notice is that you are binding the event listener to the element, getting the values input and then submitting them to the function.
I have added a function that retrieves the url of the page location and pops out the last bit of it and runs a check on it to ensure you are looking at the right place to run the correct code. as this runs on load then the subsequent functions run after. You can further refactor this to modularise it and ensure that it's cleaner to read if you wanted.
Splitting it out this way will make it easier when trying to implement a cookie as you can in the event listener (with a cookie created) can save those values to it on your greet page and then call them back after on your test page.
Hope that helps
I have written a code which extracts a specific table from a webpage. The website is dynamic and it updates the values in the table once every half an hour. My Javascript for parsing the website does reload the website once every 30 minutes. But the data extracted as JSON are only data of the particular time. But, I want to append or concatenate all the data every time the site reloads(i.e., i need the present list of data concatenated with previous list, as long as the program is running) How do i do that?.
The webpage is: https://www.emcsg.com/marketdata/priceinformation
The table required is: View 72 periods
My code is as follows:
<html>
<head>
<title>Pricing </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<meta http-equiv="refresh" content="1800" /><!--Reloads page every 30 minutes-->
<script>
function requestCrossDomain(site, callback) {
if (!site) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
window[callback](data);
} else throw new Error('Nothing returned from getJSON.');
}
}
var url = 'https://www.emcsg.com/marketdata/priceinformation';
requestCrossDomain(url, 'someFunction');
function someFunction(results){
var html = $(results);
var table = html.find(".view72PeriodsWrapper");
$('#loadedContent').css("display","").html(table);
}
</script>
</head>
<body>
<br><br>
<div id="result"></div>
<div id="loadedContent"></div>
</body>
</html>
i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
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
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('API_KEY');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q:'U2'
});
// 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);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks
Try this example here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Search API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// How to search through a YouTube channel aka http://www.youtube.com/members
google.load('search', '1');
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// So the results are expanded by default
options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
// Create a video searcher and add it to the control
searchControl.addSearcher(new google.search.VideoSearch(), options);
// Draw the control onto the page
searchControl.draw(document.getElementById("content"));
// Search
searchControl.execute("U2");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="content">Loading...</div>
</body>
</html>
When you use <script src="https://apis.google.com/js/client.js?onload=onClientLoad" ..></script>
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:
http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html
var maxRes = 50;
function searchQ(){
query = document.getElementById('queryText').value;
email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
'&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
'&callback=myPlan';
var oldsearchS = document.getElementById('searchS');
if(oldsearchS){
oldsearchS.parentNode.removeChild(oldsearchS);
}
var s = document.createElement('script');
s.setAttribute('src', email);
s.setAttribute('id','searchS');
s.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
function myPlan(response){
for (var i=0; i<maxRes;i++){
var videoID=response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var title=response.items[i].snippet.title;
var links = '<br><img src="http://img.youtube.com/vi/'+ videoID +
'/default.jpg" width="80" height="60">'+
'<br>'+(i+1)+ '. <a href="#" onclick="playVid(\''+ videoID +
'\');return false;">'+ title + '</a><br>';
document.getElementById('list1a').innerHTML += links ;
}
}
}
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<input type="text" value="abba" id="queryText" size="80">
<button type="button" onclick="searchQ()">Search 50 videos</button>
<br><br>
<div id='list1a' style="width:750px;height:300px;overflow:auto;
text-align:left;background-color:#eee;line-height:150%;padding:10px">
</div>
I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.
Simply i must make request from a web server.
Thanks all for your reply
Look at the below code, this JavaScript is used to take a string (in a language other than English) and convert it into English.
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var content = document.getElementById('translation');
// Setting the text in the div.
content.innerHTML = '<div id="text">HELLO WORLD<\/div>
<div id="translation"/>';
// Grabbing the text to translate
var text = document.getElementById("text").innerHTML;
// Translate from Spanish to English, and have the callback of
// the request put the resulting translation in the
// "translation" div. Note: by putting in an empty string for
// the source language ('es') then the translation will
// auto-detect the source language.
google.language.translate(text, '', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
</script>
I want that the string "HELLO WORLD" must be entered by user at run time in a text field and then that string is passed to the div id text. So is this possible?
Hope you are referring to the document below:
http://code.google.com/apis/language/translate/v1/getting_started.html
Please refer to the section "Getting Started" where it says about "Signing up for an API key". This needs to be done before you could implement the code in your page.
Once done, make the modification to the script file which you include in the html page with your key.
Here, replace your key with "MY_KEY_STRING" in the bottom code and get started.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Language API Sample</title>
<script src="https://www.google.com/jsapi?key=MY_KEY_STRING"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
//Show the translate button
document.getElementById("translateButton").style.display = "";
}
google.setOnLoadCallback(initialize);
function translate() {
var text = document.getElementById("fromText").value;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("toText");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
From:<input type="text" id="fromText"/>
To:<span id="toText"></span>
<input type="button" value="Translate" onclick="translate()" style="display: none;" id="translateButton">
</body>
</html>
HTML:
<form id="translate">
<textarea id="translate-me"></textarea>
<input type="submit" />
</form>
JavaScript:
var form = document.getElementById('translate')
var textarea = document.getElementById('translate-me')
form.onsubmit = function () {
google.language.translate(textarea.value, ...)
return false; // prevent default action (form submission)
}
Using jQuery or something similar would make this easier, of course.
Why doesn't JSON.parse behave as expected?
In this example, the alert doesn't fire:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing JSON.parse</title>
<script type="text/javascript" src="js/json2.js">
// json2.js can be found here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
</script>
<script type="text/javascript">
function testJSONParse()
{
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));
}
window.onload = testJSONParse;
</script>
</head>
<body>
</body>
</html>
In firefox, the Error Console says "JSON.parse". Not very descriptive..
This is a simplification of a problem I have which uses AJAX to fetch data from a database and acquires the result as a JSON string (a string representing a JSON object) of the same form as text in the example above.
Your JSON is not formatted correctly:
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
^-- This should be a ':'
It should be:
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
error in typing
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
//below is correct one
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));