Send variable to external PHP file from JavaScript - javascript

I have the following code to include in one domain (http://www.example1.com)
<script
type="text/javascript"
src="http://www.example2.com/API/incoming.php?id=560">
</script>
All this does is invoke the page incoming.php in my second domain (http://www.example2.com), and send it the value "560".
My questions are:
Is it possible to send runtime variables to the page? (Eg : I am hard coding `560`, is there any way to get it dynamically if it is part of the URL?
Would it be possible to send the page URL where this script was loaded? This is what I tried so far, but I am not able to access the variable URL.
<script type="text/javascript" src="http://www.example2.com/API/incoming.php?id=560">
var Url = "";
if (typeof this.href != "undefined") {
Url = this.href.toString().toLowerCase();
}else{
Url = document.location.toString().toLowerCase();
}
</script>

you can create the script tag dynamically and pass all the variables you like via GET.
<script>
(function() {
var id = 560;
var url = document.location.toString().toLowerCase(); // use other means if necessary
var scriptElement = document.createElement('script');
scriptElement.src = 'your.php?id=' + encodeURI(id) + '&url=' + encodeURI(url);
document.body.appendChild(scriptElement);
}());
</script>
the scriptElement will begin to load after it is inserted in the document.
this is how google analytics and others did or do it.

Related

how to Restrict access to some urls of wordpress website from single referrer domain

hello my question is what is the best approach to Restrict access to some urls of wordpress website to single referrer domain.
as far as I am familar with javascript I found a way for that. but I think javascript code is not good, because the source code of the page does not change.
I wrote this code:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
document.body.style.display="none";
var url = document.referrer;
var domainname;
var referal_code = getCookie("protect_faq_pages");
console.log(url);
if(url){
var anchor = document.createElement("a");
anchor.href = url;
domainname = anchor.host;
console.log(domainname);
if(domainname == "softwareservicetech.com"){
var cookieString = "protect_faq_pages=cWs#fgf$a1fD#FsC-)";
document.cookie = cookieString;
}
}else if(!(referal_code == "cWs#fgf$a1fD#FsC-)")){
document.getElementById("page").innerHTML="<p>Sorry you do not have permission to view the content</p>"
}
console.log(referal_code);
document.body.style.display="block";
this site can be accessed itself:
https://health-unity.com/
you can find out the page below is restriced on the view :
https://health-unity.com/help-centre/videos/
and also these pages too:
https://health-unity.com/help-centre/videos/video-number-2/
https://health-unity.com/help-centre/videos/video-number-1/
but when click on the link on below site (link to health-unity-videos):
https://softwareservicetech.com/testpage/
the archive page will be accessible after that. user can go to the pages below directly:
https://health-unity.com/help-centre/videos/video-number-2/
https://health-unity.com/help-centre/videos/video-number-1/
these were restricted before and now can be accessed by a cookie that is set.
but the problem is that page source still exist and did not changed by javascript code and user can view the page source. also I want that the cookie value should be hidden. because of these two problem I think javascript is not a good idea.
please share with me if there is way with javascript, php, or editing functions.php or .htaccess file to achieve this.
thank you for your response in advance
You can use $_SERVER['HTTP_REFERER'] in functions.php
For example:
<?php
add_action('init','check_referrer');
function check_referrer(){
if( str_contain($_SERVER['HTTP_REFERER'], 'https://example-domain.com/'){
// do somthing
}else{
// do somthing else
}
}
?>

how replace the id in src script with var in file config

<html>
<head>
<script async src="https://www.googletagmanager.com/gtag/js?id=xxxxx">
</script>
<html>
replace value xxx by var get from config
<script async src="https://www.googletagmanager.com/gtag/js?id=Var">
I want to replace the value of the id in src of script with a variable that I get from conf file
any help?
As HTML is "read" by the web browser, you won't be able to simply add a variable to a <script> tag. You can accomplish this through pure Javascript by loading in the file dynamically as stated here: Dynamically load JS inside JS
Where id_number is the number you are attempting to add:
var url_string = 'https://www.googletagmanager.com/gtag/js?id=' + id_number
var script = document.createElement('script');
script.onload = function () {
//do stuff with the script
};
script.src = url_string;
document.head.appendChild(script);

Dynamically include javascript code from within javascript file

I'm inserting the following script, which is on my own server, into an external page of a 3rd party: www.test.com/test.html:
<script type="text/javascript">
(function() {
var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
var ttScript = document.createElement('script');ttScript.async = true;
ttScript.src = '//www.example.com/script/mycode.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>
This is the other script I want to dynamically inject, please note that it can't just be added to the above script! I want this script to be dynamically available.
This complete code, will later be stored within object message.jsScript
<script type="text/javascript">
var tt_totalordervalue;
function tt_getordervalue(){
tt_totalordervalue=$('#subtotal');
console.log(tt_totalordervalue);
}
</script>
In file mycode.js:
I want to dynamically add the above script and call the function tt_getordervalue defined in there, I'm now trying to do this as below. Notice that I also want to assign the value of variable tt_totalordervalue which is defined in the dynamic script, to a variable in my mycode.js:
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(message.jsScript);
console.log('script added');
tt_getordervalue();
console.log('function called');
var val = tt_totalordervalue;
I however then get the error Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
Why?
Following works on chrome on a Mac (sorry, was too lazy to cross test):
var script = document.createElement('script');
script.innerHTML = 'window.doStuff = function(){alert("do")}';
document.getElementsByTagName('body')[0].appendChild(script);
doStuff();

Google Translate / Basic Javascript issue

Given the following
<textarea style="width: 150px; height: 150px" id="sourceText">Hello Justin how are you today?</textarea>
<textarea style="width: 150px; height: 150px" id="translation"></textarea>
<button id="translateMe" value="Translate!" onclick="translateThis();"></button>
<script>
function translateText(response) {document.getElementById("translation").innerHTML += response.data.translations[0].translatedText;}
function translateThis(){
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2?key=MY_KEY_HERE&source=en&target=es&callback=translateText&q=' + sourceText;
return source;
}
</script>
How can I hook up this button to process the function to put the translated text in to the translation text area?
You've left out a step. The "source" variable needs to become the src attribute of an HTML script element.
Take a closer look at their "getting started" doc.
By the way, other folks are pointing you towards AJAX, but that won't actually work. Because the Google URL is not hosted on your site, you will be prevented from using AJAX by the "same origin" policy. The Google approach is meant to either use an API call from server-side code (e.g. Java, ASP.NET, Ruby) or be used directly in javascript using a technique called "JSONP" which involves creating a "script" element on-the-fly.
(You should also be aware that, when you use this latter approach, you are exposing your Google Translate API key within the page source, so users can potentially steal it.)
Edited to add: here's the example code from Google's API docs:
<div id="sourceText">Hello world</div>
<div id="translation"></div>
<script>
function translateText(response) {
document.getElementById("translation").innerHTML += "<br>" + response.data.translations[0].translatedText;
}
</script>
<script>
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
// WARNING: be aware that YOUR-API-KEY inside html is viewable by all your users.
// Restrict your key to designated domains or use a proxy to hide your key
// to avoid misuage by other party.
var source = 'https://www.googleapis.com/language/translate/v2?key=YOUR-API-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
</script>
You will want to use your favorite AJAX method (Mine being $.ajax in JQuery) to post to that url and then put the response into your text field.
http://api.jquery.com/jQuery.ajax/
Currently you're building a URL that, if visited, will have the answer you want - an AJAX request will programmatically visit that URL and get data back from it.
I solved my question this way.
<script>
function callbackDescription(response) {
document.getElementById("siteDesc" + langCode).innerHTML = response.data.translations[0].translatedText;
}
var langCode;
function translateToLangCode(lang) {
langCode = lang;
translateDescription();
}
function translateDescription() {
var faciDescScript = document.createElement('script');
faciDescScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("siteDescEN").innerHTML);
var faciDesc = 'https://www.googleapis.com/language/translate/v2?key=API_KEY_HEREsource=en&target=' + langCode.toLowerCase() + '&callback=callbackDescription&q=' + sourceText;
faciDescScript.src = faciDesc;
document.getElementsByTagName('head')[0].appendChild(faciDescScript);
}
</script>

Handle Malformed Remote JSONP Response

this is a continuation of my original question here link
You can see through my rather lengthy conversion with aaronfrost that we determined the jquery was loading in the .php (as seen on the network tab in CHROME) however it's trying to be ran as a script immediately. My question is where or not it's possible to load that in as plain text and simply then do a js parse out the needed data. Doesn't have to be jQuery this was just the route we were going in this example. I've also tried with the following code and recieve the exact same "Unexpected token" error. I think if there were a way to just some how handle the malformed JSON client side we would be able to make this work, in a ugly sort of way.
If javascript doesn't work do you think going the route of a java applet (preserve client cookies, non-server side) would achieve the desired end result i'm looking for?
<script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="application/javascript">
var url = 'http://www.makecashnow.mobi/jsonp_test.php';
//<!-[CDATA[
function JSONscriptRequest(fullUrl) {
// REST request path
this.fullUrl = fullUrl;
// Keep IE from caching requests
//this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
// Get the DOM location to put the script tag
this.headLoc = document.getElementsByTagName("head").item(0);
// Generate a unique script tag id
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}
// Static script ID counter
JSONscriptRequest.scriptCounter = 1;
// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {
// Create the script tag
this.scriptObj = document.createElement("script");
// Add script object attributes
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("charset", "utf-8");
//this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("src", this.fullUrl);
this.scriptObj.setAttribute("id", this.scriptId);
}
// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
// Destroy the script tag
this.headLoc.removeChild(this.scriptObj);
}
// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
// Create the script tag
this.headLoc.appendChild(this.scriptObj);
}
var obj = new JSONscriptRequest(url);
obj.buildScriptTag();
obj.addScriptTag();
//]]>
</script>

Categories