How to use JS to retreive API data - javascript

I have written a basic API in PHP on my site (domain1.com). I need to load a simple form on another site (domain2.com) by placing a simple JS file on the other site. JS needs to access my API and format the form based on returned data.
Question: should I keep my JS file on initial site, with all the JS code in it and just let the other site include it like this
<script src="https://domain1.com/api.js?form=domain2"></script>
or shall I let the other site place a JS code, something like this:
<script>
var form = ... // send request to https://domain1.com/api/form
</script>
I'm sure it's a common knowledge, but I really never had to deal with this sort of issues, so, if you don't wish to answer, please don't mark for "close".

Related

How do I create environment variables to protect my Google Maps API Key(or any other secret value) for my website?

I am learning to code my own website using Bootstrap and have easily placed a map on my page using a Google map API-key and script from Google Developers:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Ideally I would have something like:(i.e. I have tried this):
Html: <script src="map-value-pair.php"></script></script><script async defer src="$MapURL"></script>
PHP: <?php $MapURL="maps.googleapis.com/..." ?>
So obviously this doesn't hide the URL it prints to the html.
I am not convinced anyone actually tries to hide this key for a basic purpose like mine because the http referrer restriction on Google Developers is sufficient. But, after trying many different approaches to obfuscate the key I have decided I would like to learn to create environment variable to hide values. I think it could be useful and I would like to extend my server-side knowledge. Google best practices also suggests to "store them in environment variables or in files outside of your application's source tree".
I have found a related stack: What steps should I take to protect my Google Maps API Key?
In that stack a related link was given to hackernoon.com (limited links in first post) My hosting service uses cPanel and provides this apache environment variables tutorial: documentation.cpanel.net...
I am having problems finding material to start myself off. Right now I have two potential action plans:
enable ssh on cpanel>follow cPanel tutorial noted above>figure out how to access variable in html
or
enable ssh on cpanel>install node.js somehow>follow something like this on twilio>figure out how to access variable in html
Any help or suggestions appreciated. Best case scenario some edits to my action plan with a couple links to check out. I just need some sort of confidence to move forward with one of these plans.
P.S. Woo first post!
EDIT: Minor cleanup of question. Added ideally script.
Anything you output as HTML can be scraped by anyone visiting your website. You can't access variables etc in HTML as it is the final output, generated server side once it has processed all your variables.
As you are using the Javascript library then there is no way to hide your key. Javascript is executed on the client's browser, so you have to pass them your API key for it to work.
If all you need are static maps then you can generate them server side and return them in your HTML without ever revealing your key to the end user.
Heres a PHP example:
$mapimg = "https://maps.googleapis.com/maps/api/staticmap?center=<$USER-LOCATION>&size=640x320&key=<$YOUR-KEY>"; // Include the user location in your request URL
$imagedata = file_get_contents($mapimg); // Retrieve the image server side
$src = base64_encode($imagedata); // Encode the image server side
$imagemap = '<img src="data:image/jpg;base64,'.$src.'">'; // Create a variable to insert the image into your page
Then within your PHP script to output the HTML you just include $imagemap wherever you want the map to appear.
This stack has a similar question, see geocodezip's answer: How do I securely use Google API Keys
(I looked but could not find this answer before posting the original question).
Basically what I gather is you must have the API_Key showing for Googles javascript to work, despite Googles somewhat contradictory advice here: https://support.google.com/googleapi/answer/6310037
If you know of some reading material for me or others about creating environment variables or their usefulness please do so, I am still interested in that!

Write a line to javascript file

Im using a array to display some images in a website:
var paintingImages;
paintingImages =
[
{
url: 'images/objects/ron.jpg',
alt: 'ron'
}
];
This js code is written in paintings.js and my main js code is written in the file main.js
I have made this website for a artist and I want to give him the opportunity to login and add pictures to his website. I'm not that good with php, but adding images to a ftp in a folder is no problem.
Because I'm using a array for retrieving the images, I need to be able to add items to the array.
This is the part where I'm stuck. I don't know how to edit a existing js file, so the next time I open the website, the items (images) will been shown.
Activexobject is not a option because it's only possible in IE.
In summary:
I need to add a item to a array
I need to save this into the file, so the next time the website opens, it will be shown
I'm not verry good with php, I prefer javascript
Can't use Activexobject because of the use of multiple browsers
You can not simply modify a javascript file sitting on the server from browser side javascript.
You need to implement some server side logic.
If you don't like PHP, but like JavaScript, check out NodeJS for example.
With Node you should be able to build some lightweight serverside logic to modify your json array file with additional images.
You would need to change your logic .. You need to send this data to server anyhow . and when you load your next time take it back from server and update your webpage accordingly. I would suggest use any javascript MVC framework like backbone, angular.js. it will help you.
Use a database.
Save it to a database server (You figure this out, could be via forms, xhr, websockets, etc.).
On page load, load the correct data for the current user.
Create the $userPaintings array (call it what you want) from the user data in PHP.
Then simply output a JS object in the page with PHP:
<script>
var paintingImages = <?php json_encode($userPaintings); ?>
</script>

How to add html content generated by json call to page generated html code?

I have a page. Which contain json method to load data. I call this method on page load. It works properly. The problem is when I view source of that page I don't see the generated code.
My concern is the search engine will never see the content even if end user see it.
Is there anyway to add it? If so how it can be done?
Here is the example of code I use
$(function(){
//Call to the server to get data.
var content = "Some data"; //from the json call
$("#content").html(content);
});
});
Most if not all search engines will not recognize content inserted into a page from Ajax/Javascript, this is why you need to load this content with in the page if you want the search engine to recognize it.
Your question seems to me a copy of what's asked over here and in Is there anyway of making json data readable by a Google spider?
So, Progressive enhancement and Unobtrusive JavaScript are the way out..
In addition to these, optionally, but importantly, test the crawlability of your app: see what the crawler sees with "Fetch as Googlebot".

Need to understand how tracking codes may be working in web content

I was recently approached by a web partner and they asked me to add their 'tracking code' to my site as shown below. The data and address would be different, but the structure is the same as below. Currently they load our site in an IFrame and what I can't understand is...
How could the script portion provide any value to them? Can a parent page read JavaScript state of something in a hosted IFrame? Google uses a similar pattern but they set the src which has Script that is executed when the page loads and could read the state.
Can anyone explain how this might be working or is this just useless page spam?
<img src="https://www.APartnerCompany.foo/thing.img?arg=value" />
<script type="text/javascript">
//<![CDATA[
var Foo = {};
Foo.Tracking = {};
Foo.Tracking.Sale = {};
Foo.Tracking.Sale.amount = '100.00';
//]]>
</script>
An inline script can also read values from the page it is contained in. To post them back to their own server, they seem to use the src attribute of that affiliate image. However, the pieces you provided are harmless (the code does nothing than constructing an object) and requests only a non-executable from https://www.APartnerCompany.foo/thing.img?arg=value (beeing logged at theirs).
When the request for that src is being sent the server is just logging the variables that are accompanied with it, the JS code is just updating the arguments with relevant data.
All it does is send information to a server through a GET request which it is logged. It can be as simple as reading the Apache logs for hits or it can be a cgi that processes the data. That is basically how all those ad/logging services work.

How to make a javascript like Disqus or IntenseDebate

I want to make an app that can display on any webpage, just like how Disqus or IntenseDebate render on articles & web pages.
It will display a mini-ecommerce store front.
I'm not sure how to get started.
Is there any sample code, framework, or design pattern for these "widgets"?
For example, I'd like to display products.
Should I first create a webservice or RSS that lists all of them?
Or can one of these Ajax Scripts simply digest an XHTML webpage and display that?
thanks for any tips, I really appreciate it.
Basically you have two options - to use iframes to wrap your content or to use DOM injection style.
IFRAMES
Iframes are the easy ones - the host site includes an iframe where the url includes all the nessessary params.
<p>Check out this cool webstore:</p>
<iframe src="http://yourdomain.com/store?site_id=123"></iframe>
But this comes with a cost - there's no easy way to resize the iframe considering the content. You're pretty much fixed with initial dimensions. You can come up with some kind of cross frame script that measures the size of the iframe contents and forwards it to the host site that resizes the iframe based on the numbers from the script. But this is really hacky.
DOM injection
Second approach is to "inject" your own HTML directly to the host page. Host site loads a <script> tag from your server and the script includes all the information to add HTML to the page. There's two approaches - first one is to generate all the HTML in your server and use document.write to inject it.
<p>Check out this cool webstore:</p>
<script src="http://yourdomain.com/store?site_id=123"></script>
And the script source would be something like
document.write('<h1>Amazing products</h1>');
document.write('<ul>');
document.write('<li>green car</li>');
document.write('<li>blue van</li>');
document.write('</ul>');
This replaces the original <script> tag with the HTML inside document.write calls and the injected HTML comes part of the original page - so no resizing etc problems like with iframes.
<p>Check out this cool webstore:</p>
<h1>Amazing products</h1>
<ul>
<li>green car</li>
<li>blue van</li>
</ul>
Another approach for the same thing would be separating to data from the HTML. Included script would consist of two parts - the drawing logic and the data in serialized form (ie. JSON). This gives a lot of flexibility for the script compared to the kind of stiffy document.write approach. Instead of outpurring HTML directly to the page, you generate the needed DOM nodes on the fly and attach it to a specific element.
<p>Check out this cool webstore:</p>
<div id="store"></div>
<script src="http://yourdomain.com/store_data?site_id=123"></script>
<script src="http://yourdomain.com/generate_store"></script>
The first script consists of the data and the second one the drawing logic.
var store_data = [
{title: "green car", id:1},
{title: "blue van", id:2}
];
The script would be something like this
var store_elm = document.getElementById("store");
for(var i=0; i< store_data.length; i++){
var link = document.createElement("a");
link.href = "http://yourdomain.com/?id=" + store_elmi[i].id;
link.innerHTML = store_elmi[i].title;
store_elm.appendChild(link);
}
Though a bit more complicated than document.write, this approach is the most flexible of them all.
Sending data
If you want to send some kind of data back to your server then you can use script injection (you can't use AJAX since the same origin policy but there's no restrictions on script injection). This consists of putting all the data to the script url (remember, IE has the limit of 4kB for the URL length) and server responding with needed data.
var message = "message to the server";
var header = document.getElementsByTagName('head')[0];
var script_tag = document.createElement("script");
var url = "http://yourserver.com/msg";
script_tag.src = url+"?msg="+encodeURIComponent(message)+"&callback=alert";
header.appendChild(script_tag);
Now your server gets the request with GET params msg=message to the server and callback=alert does something with it, and responds with
<?
$l = strlen($_GET["msg"]);
echo $_GET["callback"].'("request was $l chars");';
?>
Which would make up
alert("request was 21 chars");
If you change the alert for some kind of your own function then you can pass messages around between the webpage and the server.
I haven't done much with either Disqus or IntenseDebate, but I do know how I would approach making such a widget. The actual displaying portion of the widget would be generated with JavaScript. So, say you had a div tag with an id of commerce_store. Your JavaScript code would search the document, when it is first loaded (or when an ajax request alters the page), and find if a commerce_store div exists. Upon finding such a container, it will auto-generate all the necessary HTML. If you don't already know how to do this, you can google 'dynamically adding elements in javascript'. I recommend making a custom JavaScript library for your widget. It doesn't need to be anything too crazy. Something like this:
window.onload = init(){
widget.load();
}
var widget = function(){
this.load = function(){
//search for the commerce_store div
//get some data from the sql database
var dat = ajax('actions/getData.php',{type:'get',params:{page:123}});
//display HTML for data
for (var i in dat){
this.addDatNode(dat[i]);
}
}
this.addDatNode = function(stuff){
//make a node
var n = document.createElement('div');
//style the node, and add content
n.innerHTML = stuff;
document.getElementById('commerce_store').appendNode(n);
}
}
Of course, you'll need to set up some type of AJAX framework to get database info and things. But that shouldn't be too hard.
For Disqus and IntenseDebate, I believe the comment forms and everything are all just HTML (generated through JavaScript). The actual 'plugin' portion of the script would be a background framework of either ASP, PHP, SQL, etc. The simplest way to do this, would probably just be some PHP and SQL code. The SQL would be used to store all the comments or sales info into a database, and the PHP would be used to manipulate the data. Something like this:
function addSale(){ //MySQL code here };
function deleteSale(){ //MySQL code here };
function editSale(){ //MySQL code here };
//...
And your big PHP file would have all of the actions your widget would ever need to do (in regards to altering the database. But, even with this big PHP file, you'll still need someway of calling individual functions with your ajax framework. Look back at the actions/getData.php request of the example JavaScript framework. Actions, refers to a folder with a bunch of PHP files, one for each method. For example, addSale.php:
include("../db_connect.php");
db_connect();
//make sure the user is logged in
include("../authenticate.php");
authenticate();
//Get any data that AJAX sent to us
var dat = $_GET['sale_num'];
//Run the method
include("../PHP_methods.php");
addSale(dat);
The reason you would want separate files for the PHP_methods and run files, is because you could potentially have more than one PHP_methods files. You could have three method API's, one for displaying content, one for requesting content, and one for altering content. Once you start reusing your methods more and more, its best to have them all in one place. Rewritten once, rewritten everywhere.
So, really, that's all you'd need for the widget. Of course, you would want to have a install script that sets up the commerce database and all. But the actual widget would just be a folder with the aforementioned script files:
install.php: gets the database set up
JavaScript library: to load the HTML content and forms and conduct ajax requests
CSS file: for styling the HTML content and forms
db_connect: a generic php script used connect to the database
authenticate: a php script to check if a user is logged in; this could vary, depending on whether you have your own user system, or are using gravitars/facebook/twitter/etc.
PHP_methods: a big php file with all the database manipulation methods you'd need
actions folder: a bunch of individual php files that call the necessary PHP methods; call each of these php files with AJAX
In theory, all you'd have to do would be copy that folder over to any website, and run the install.php to get it set up. Any page you want the widget to run on, you would simply include the .js file, and it will do all the work.
Of course, that's just how I would set it up. I assume that changes in programming languages, or setup specifics will vary. But, the basic idea holds similar for most website plugins.
Oh, and one more thing. If you were intending to sell the widget, it would be extremely difficult to try and secure all of those scripts from redistribution. Your best bet would be to have the PHP files on your own server. The client would need to have their own db_connect.php, that connects to their own database and all. But, the actual ajax requests would need to refer to the files on your remote server. The request would need to send the url of the valid db_connect, with some type of password or something. Actually, come to think of it, I don't think its possible to do remote server file sharing. You'd have to research it a bit more, 'cuz I certainly don't know how you'd do it.
I like the Azmisov's solution, but it has some disadvantages.
Sites might not want your code on their servers. It'd be much better if you would switch from AJAX to loading scripts (eg. jQuery's getJSON)
So I suggest:
Include jquery hosted on google and a short jquery code from your domain to the client sites. Nothing more.
Write the script with cross-domain calls to your server (through getJSON or getScript) so that everything is fetched directly and nothing has to be inctalled on the client's server. See here for examples, I wouldn't write anything better here. Adding content to the page is easy enough with jQuery to allow me not mentioning it here :) Just one command.
Distribute easily by providing two lines of <script src= ... ></script>

Categories

Resources