I have a simple CGI script that would generate plain text content on demand. For example, http://1.2.3.4/hello.cgi?name=Joe would return Hello Joe!.
How can I read this into a string in Javascript?
name = "Joe";
url = "http://1.2.3.4/hello.cgi?name=" + name;
greeting = loadThis(url);
I'm new to Javascript, so even naive approach (i.e. no need to URL escape...) will be helpful for me :)
Based on this FAQ on JavaScriper.net, I have found solution that works for me. However, the called script must be on the same machine as the caller, otherwise I get security errors from browsers.
Apparently this is what #Makkes mentioned. However, I'm perfectly happy with having the hello.cgi on the same machine for now.
Here is the code:
function loadThis(localuri) {
var oRequest = new XMLHttpRequest();
var sURL = 'http://'
+ self.location.hostname
+ localuri;
oRequest.open('GET',sURL,false);
oRequest.setRequestHeader('User-Agent',navigator.userAgent);
oRequest.send(null);
if (oRequest.status==200) return(oRequest.responseText);
else alert('Error executing XMLHttpRequest call!');
}
name = "Joe";
localuri = "/hello.cgi?name=" + name;
greeting = loadThis(localuri);
(Of course, this would not handle names with spaces or special characters correctly, but that's another story.)
Related
I do not know how to code Java and am not an expert in GTM. However, the code I need is so simple, It worked on an online editor but I have been trying to get it to work on GTM and it does not validate the code.
I need to extract the email adresses from a long string (variable {{Click URL}} in GTM) that contains a complete "mailto:" url with many parameteres and only extract the short email from there (without the additional parameters after the ".com?")
Just an example of this kind of url:
'mailto:information#example.com?subject=Demande%20de%20renseign
ements&body=Votre%20nom:%20%0A%0ANom%20du%20produit:%20%0A%0AVotre%20tel
.%20si%20vous%20souhaitez%20recevoir%20un%20appel%20de%20notre%20part:%2
0%0A%0AVotre%20demande%20de%20renseignements:%20%0A'
Here is the code,
let shortmailto2 = {{Click URL}},
let fin = shortmailto2.indexOf('?'),
let debut = shortmailto2.indexOf(':'),
let shortmailto = shortmailto2.slice(debut+1,fin);
it pulls the right email address as I need when testing on an online editor but when I insert it into GTP (and use a pre-existinge variable, the "click url") I get an error (see monosnap link below for the screen shot): https://monosnap.com/file/eBFYfEwLv9LrPwGrGl6rzaHCbmoeYj
Thanks!
GTM Custom JavaScript Variables:
This field should be a JavaScript function that returns a value using the 'return' statement. If the function does not explicitly return a value, it will return undefined and your container may not behave as expected. Below is an example of this field:
function() {
var now = new Date();
return now.getTime();
}
The following worked for me when I tested it, returning just the email address.
function() {
var shortmailto2 = {{Click URL}};
var fin = shortmailto2.indexOf('?');
var debut = shortmailto2.indexOf(':');
return shortmailto2.slice(debut+1,fin);
}
I am trying to make a request to a backend API I created on Google App Engine. Right now it should be pretty simple, it sends the URL, and what should be returned is JSON that looks like this {"keys": [5676073085829120]}. I have tested the API by making CURL requests, and the the URL works, one thing that confuses me is that when I make a CURL request I have to specify "Accept: application/json", but I do not know how to add that to a getAsync request. Here is the code in question:
function verify(){
var uname = document.getElementById("username").value;
var pword = document.getElementById("password").value;
var c = new Windows.Web.Http.HttpClient();
var complete = "http://golden-bonsai-124817.appspot.com/users/" + uname + "/" + pword;
c.getAsync(new Windows.Foundation.Uri(complete)).done(function (result) {
var jsonResult = JSON.parse(result.content.toString());
var key = jsonResult.Results.series[0].data;
console.log("in here");
var authKey = new Array();
key.forEach(function (cur, i, arr) {
authKey.push(cur.keys);
});
};
I tried stepping through the code with the debugger in visual studio. It initializes the variables, and the value of my 'complete' variable is the correct URL that I have used for my cURL requests. I set a breakpoint inside of the function that is supposed to happen once the request completes, but the code never makes it inside of that function and eventually the windows phone emulator goes black and it seems like it just hangs, it doesn't exit but it gets to a point where I can no longer step through. I have been trying and trying but I just can't figure it out, and to make it worse the documentation for all of this stuff is garbage. Any help would be very greatly appreciated. Thanks in advance.
That need to be specified in the content of a request. To specify the content type of a request, you need to use HttpRequestMessage to create request and then specify the media type. You then need to use sendRequestAsync method of HttpClient to process your request. So your code will be something similar to the following.
var hc = new Windows.Web.Http.HttpClient();
var uri = new Windows.Foundation.Uri("http://golden-bonsai-124817.appspot.com/users/" + uname + "/" + pword);
var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.get, uri);
var content = "";
var encoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
var mediaType = "application/json";
request.content = new Windows.Web.Http.HttpStringContent(content, encoding, mediaType);
hc.sendRequestAsync(request).then(...);
It is possible this question might be a little vague for the liking of many people here, but my knowledge of the topic is vague also, and despite some searching I have not been able to find anywhere online with clear instructions on how to do this although (in my view) it should probably be one of the simpler cross-domain JSONP operations.
I will explain what I am trying to do. I am trying to retrieve the contents of a HTML file on an external server using both JSONP and a PHP script. I have access to the server - my PHP script is as follows:
<?php
$callback = '';
if (isset($_GET['callback']))
{
$callback = filter_var($_GET['callback'], FILTER_SANITIZE_STRING);
}
$html = include($callback);
echo $callback . '('.json_encode($html).');';
?>
Using this it seems that when I type www.myurl.com/myscript.php?callback=filename.html, the correct file is displayed (although, for some reason, the ?callback is duplicated in the address, and the filename is appended to the end of the output displayed...
I have tried a few different scripts for my HTML file but currently have the following...
function request_jsonp(){
var script = document.createElement('script');
var url = 'http://www.myurl.com/myscript.php?callback=filename.html';
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
Now obviously this doesn't work because the output of the PHP script isn't a working function of any sort, but I am not sure of the best way to go about making it one. I would like to somehow wrap the output in something like this:
function DisplayOutput() {
document.getElementById('output').innerHTML = ...external HTML goes here!... ;
}
...but currently I'm really not sure of the best way to do this.
Any help would be very much appreciated.
callback needs to be the name of the callback function. You should generate a unique one each time the function is called.
You should use a second, different query string variable to determine what URI to fetch.
var jsonp_counter = 0;
function request_jsonp(url, callback){
jsonp_counter++;
var callback_name = "jsonp_function_" + jsonp_counter;
window[callback_name] = callback;
var jsonp_url = 'http://www.myurl.com/myscript.php" +
"?callback=" + encodeURIComponent(callback_name) +
"&url=" + encodeURIComponent(url);
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
request_jsonp("filename.html", function (data) {
do_something_with(data);
});
<script src="myscript.js?someParameter=123"></script>
From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?
Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.
There are two ways to pass parameters to another JavaScript file:
As #Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.
Jquery Address does this, so i've been checking their code out and this is the improved solution I just created myself:
$.each($('script'), function(id, val){ //loop trough all script-elements
var tmp_src = String($(this).attr('src'));//store the src-attr
var qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index
//Check if the script is the script we are looking for and if it has QS-params
if(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
{
//this is myscript.js and has a querystring
//we want an array of param-pairs: var1 = value1, var2 = value2, ...
var params_raw = tmp_src.substr(qs_index + 1).split('&');
//create empty options array
var options = [];
//loop troug raw params
$.each(params_raw, function(id, param_pair){
//split names from values
var pp_raw = param_pair.split('=');
//store in options array
options[pp_raw[0]] = pp_raw[1];
});
//check the results out in the console!
console.log(options);
}
});
I hope this does what you need?
The answer is a definite "YES". I've been doing this on various projects for over a decade. The solution is actually easy, it's just non-intuitive (you have to generate an error). To be clear, the following code lets you do something like this:
<script src="https://example.com/script.js?id=1&bar=this works!" />
All you need to do is initiate a silent error, which takes less than 1/1000 of a second even on the worst outdated mobile browsers. You shouldn't do it a ton, but you only need to do it once. This error is processed, so it won't show up as an error in telemetry or 3rd party error trackers either.
// Generic function used to see if a param exists in a URL string.
// Provided here in case you don't know how to do it.
// This is not needed for the solution.
function getParameter (name, url) {
if (!url) url = scriptName()
name = name.replace(/[\[\]]/g, '\\$&')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
var results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
// Gets the name of this script (whatever this file runs in)
// You can use this name to get parameters just like you would for the window URL :)
function getScriptName () {
var error = new Error(),
source,
lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/),
currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/)
if ((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] !== '')
return source[1]
else if ((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1]
else if (error.fileName !== undefined)
return error.fileName
}
I am making a page that accepts post data from any number of pages that I cannot change, access, or in any way control.
I need, in one way or another, to get the timezone of the user. I know, ideally the posting page would do this, but I cannot access these pages.
I've read other answers on this site and come up with 2 almost, but not quite there solutions.
First, there is javascript. I can get the javascript function to return (or change a label to) the correct value, but the problem is I need this info before the postback. I've been trying to write the timezone name on another page and read that page, but I have no idea how to begin to do that? Any other workaround to use the javascript is welcome, or any way to force call this before Page_Load is called?
function getTimeZone()
{
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
var label = document.getElementById("<%=TZ.ClientID%>");
label.textContent = "GMT " + gmtHours;
}
The second solution is to read it from another page, and I am using this:
http://ipinfodb.com/ip_query.php?ip=192.36.167.120&timezone=true
(Completely random ip in there, btw)
So here is my function to get the info from that site:
public string GetTimezone(string ip)
{
string address = string.Format("http://ipinfodb.com/ip_query.php?ip={0}&timezone=true", ip);
string timezone = "";
try
{
XmlTextReader reader = new XmlTextReader(address);
HttpWebRequest wrq = (HttpWebRequest)WebRequest.Create(address);
wrq.Proxy.Credentials = CredentialCache.DefaultCredentials;
reader = new XmlTextReader(wrq.GetResponse().GetResponseStream());
string lastRead = "";
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
lastRead = reader.Name;
}
if (reader.NodeType == XmlNodeType.Text)
{
if (string.Compare(lastRead, "TimezoneName", true) == 0)
{
timezone = reader.Value;
break;
}
}
}
}
catch
{
timezone = "";
}
return timezone;
}
Basically, this works in debug mode, but when it's live only an empty string is returned. I am baffled? Is there any better way to read data from a page? I am using Request.ServerVariables["REMOTE_ADDR"] to get the ip, and that seems to be correct, since it inserts the correct ip into the database I'm using.
Here is the call:
GetTimezone(Request.ServerVariables["REMOTE_ADDR"]);
You're getting an exception, probably because of a trust issue / firewall on the production server.
Get rid of the evil catch block so you can find out what the exception is.