I currently have this code and I want to know how to store it, and then use it, in a database:
var stores = {
"McDonalds" : .90,
"Target" : .92,
"iTunes" : .95,
"Starbucks" : .87,
"Best Buy" : .93,
}
This list will be different and much bigger, but thats an example. It is currently put into action using:
<script src="location"></script>
I want to hide it in a database so that it isn't accessible to customers or competitors. How can I do that? And, when doing so, how would I then have my page access it instead of using script src?
You can't hide this from your customers, and still have your customers use that data in their browser. That isn't how the Internet works. If the browser needs to read that data, the user can also read that data.
If you can move whatever calculation you're doing server-side, that might be an option, but these are pretty simple values, and I'm guessing that people will have little difficulty guessing them simply by examining the inputs and outputs of your algorithm.
Related
This post is more a question than an actual issue with code.
So for a long time when I had to display for example a list of items from database, I used to display the Id (primary key in the table) directly in the HTML like this for example :
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
So like this when I wanted to do an Ajax request of the current clicked item, it was easy because I just had to retrieve the attribute from the html like this :
$.ajax({
url: '/api/Item/'+$(this).attr('id'),
type: 'GET',
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
That's only after browsing a lot of websites that I noticed that nobody display the primary key (Id) directly in the HTML. But somehow they could still do ajax request to the API using the Id of the clicked item. So my question is : How can I get the current clicked Id to do my ajax request without displaying anywhere. I mean how does these websites manage to do that ? Maybe they get list from server that they use in the client then ? But it still does not explain how they manage to get the current clicked Id.
Appreciate your thoughts and suggestions on this.
Example of website : https://www.toneden.io/
The chat at the bottom right when connected see network and web browser console.
To get response from the server, you have to request something. In this case, you are saying i don't want to display primary key anyware in html side and get result from server. my suggestion on this, In php > you can use binary number instead of primary key and convert back to number and use acc. to requirements. Example :- decbin() and bindec()
There's nothing wrong with displaying an id. I've appended the database id such as id="game_1281" in cases where I only want to refer to the DOM in response to a server push update. Another option is to use a data attribute like so: data-id="1281". This allows you to get the value without any messy parsing before sending it to the server.
Referencing a unique id is not a security issue. Just make sure you are doing the appropriate server-side checks to ensure that the action taken is possible for that user based on various constraints and privileges.
What i need to accomplish in the end is
A. send a url to the form on this page: youtube-mp3.org
B. get the scr attribute of a link on the resulting page.
I'm using Ruby on Rails and tried this method to send the request and get the body of the resulting page:
require 'uri'
yt_uri = URI('http://www.youtube-mp3.org')
params = { :id => "youtube-url" , :value => "http://www.youtube.com/watch?v=KMU0tzLwhbE" }
yt_uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(yt_uri)
res.body
and it works fine but the problem is that the website uses javascript to render the link so it is not showing up in the source. Instead I get
<noscript>
<div class="warning">You have to enable JavaScript to use this Service!</div>
</noscript>
is there a way around this. Im open to any suggestions
There are two routes:
Actually execute the Javascript, and then do the scraping. This is heavyweight, both in terms of resources, in terms of work required
Figure out what the Javascript in question is actually doing
In this case, it's pretty easy. Go to http://www.youtube-mp3.org, open up your browser's trusty network debugger, and use the web form. Now, go back and inspect the requests and responses.
In my case, there appear to be four calls to external elements:
/a/pushitem
rectangle.htm
skyscraper.htm
/a/iteminfo
i.ytimg.com/vi/KMU0tzLwhbE
There's nothing interesting in the first three requests, but the fourth has some interesting looking JSON, and the last is a thumbnail image for the video.
The text from /a/iteminfo:
info = { "title" : "Developers", "image" : "http://i.ytimg.com/vi/KMU0tzLwhbE/default.jpg", "length" : "3", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "a0bb1715519025e36487b173b231295c" };
And, for those following along at home, the link src jsamm is trying to ferret out:
http://www.youtube-mp3.org/get?video_id=KMU0tzLwhbE&h=a0bb1715519025e36487b173b231295c&r=1380935176286
video_id is pretty easy to figure out- and we already have it. The h value came back in that JSON blob. r is a little more mysterious- but it looks remarkably like the current unix epoch + 3 extra digits. Oh wait- that's what Javascript's Date.getTime() gives you!
Anyway, don't do this. Not only are you being a jerk to whoever runs youtube-mp3.org, you're almost certainly violating the YouTube terms of service, and you're swimming in ugly copyright waters.
i'm quite new to javascript/jQuery/Json. i'm building myself a local app ( no client side for now). right now i have a simple form (inputs and submit) and would like to get the inputs from the user with javascrip/JQuery and then build a JSON object and store it on a file. i managed to get the inputs using jQuery ,and using JSON.strigify() i have a JSON object. only thing is that i dont know how to write to a file with JS. i searched for a solution and understand that i might need to use PHP for that as JS is not meant for changing files.
here is my code:
HTML form:
<form name="portfolio" id="portfolio" method="post" onsubmit="getform()">
<p>General</p>
Portfolio Name: <input type="text" id="portfolioName" name="portfolioName"><br>
Owner First Name: <input type="text" id="ownerFName" name="ownerFName"><br>
Owner Last Name: <input type="text" id="ownerLName" name="ownerLName"><br>
<p>Risk Management</p>
%stocks : <input type="text" id="stocksPerc" name="stocksPerc"><br>
<input type="submit" value="submit">
</form>
JS code
function getform() {
var portfolioName = document.portfolio.portfolioName.value;
var ownerFname = document.portfolio.ownerFName.value;
var ownerLname = document.portfolio.ownerLName.value;
var stocksPerc = document.portfolio.stocksPerc.value;
var myJsonObject =JSON.stringify({
"general": {
"portfolioName": portfolioName,
"ownerFname": ownerFname,
"ownerLname": ownerLname
},
"riskManagement": {
"stocksPerc": stocksPerc
}
});
alert(myJsonObject);
event.preventDefault();
};
now in "myJsonObject" i have the JSON object which i would like to write to a local file.
later on i would like to read this file ,and maybe update some of the values there.
can someone please help me understand how do i write it to a file ?
you can try and load this page which runs my code. hope it works for you.
note: programming is my area of interest but i didnt study it ,i'm learning all by myself so i'm sorry if i askqdo things that make you blind for a moment :). also this is the first question i post here ,feel free to say if i need to improve.
Thanks
Sivan
update + clarification : Thanks for the answers guys ,localStorage is something i didnt know about. from what i understand about localStorage its only good for working in a single domain/location. (i encountered this question on site). what if i want the option of running the app from different locations - lets say there will be only one person updating the JSON data, no need for sync/lock and stuff like that. right now my files (JS,JSON..) are saved in dropbox ,this is how i can use the app from different locations today , i dont have any other server.
2'nd update : i tried the localStorage solution i've been offered and even though its a great capability ,its not exactly what i'm looking for since i need the JSON data available in more then one location (i'll be using my desktop and my laptop for instance).
i'd be glad if you have other suggestions.
Thanks Again.
Check out the HTML5 localStorage API. You will be able to store your JSON objects there and retrieve them. They will be stored as key-value pairs. You can't write to a file using JS AFAIK.
Don't use a file as storage, use localStorage: http://diveintohtml5.info/storage.html. If you need to save information on a session scope, you should use sessionStorage, mind though that the latter is not persistant.
An example of how you would use it:
var item = {
"general": {
"portfolioName": portfolioName,
"ownerFname": ownerFname,
"ownerLname": ownerLname
},
"riskManagement": {
"stocksPerc": stocksPerc
}
}
// set item, you should think up of a unique key for each item
localStorage.setItem('your-key', item);
// remove it if no longer needed, you don't have a lot of space
localStorage.removeItem('your-key');
Saving files is possible in some browsers but this will probably be removed in the future - so I wouldn't use it unless you must.
This article shows how to -
http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
You can post the json to a server and use the server to generate a download file (ask a new question if thats what you seek)
and finally - are you sure you want to save to file? if all you want is to save and restore data then there are better alternatives (such as localStorage, cookies, indexDb)
I am writing a gadget for Jira with some configuration options. One of these configuration options is a "project or filter picker".
My problem lies in the part, when I want to reconfigure the gadget's preferences. I have read the code of the timesince-gadget as an example and I think the relevant part is the following:
if (/^jql-/.test(gadget.getPref("projectOrFilterId"))){
projectAndFilterPicker =
{
userpref: "projectOrFilterId",
type: "hidden",
value: gadgets.util.unescapeString(this.getPref("projectOrFilterId"))
};
} else {
projectAndFilterPicker = AJS.gadget.fields.projectOrFilterPicker(gadget, "projectOrFilterId", args.options);
}
Basicly I've copied the code from the timesince-gadget. Unfortunately even if already configured, the javascript always enters the else part.
A problem is, that I ve no experience with jql and don't totally understand the if clause.
But usually (e.g. when calling the rest api and processing the config infos)
gadget.getPref("projectOrFilterId")
returns a string containing the id of the picked project or filter.
Question is now: How can I make my gadget remember the last configuration like it's done with some many other Jira gadgets?
I really hope anyone can help me with that.
It turnes out, the answer is even simplier then I thought.
First: In the descriptor you can totally forget the if part from above. Just
var projectAndFilterPicker = AJS.gadget.fields.projectOrFilterPicker(gadget, "projectOrFilterId", args.options);
is needed.
Second: Retrieve the project's or filter's name in your rest resource, which shouldn't be a problem, since you already want to use the processed id. Then return this name back to the view part of your javascript and type in something like
this.projectOrFilterName = args.myrestclasskey.projectOrFilterName;
And tada: reconfiguration will display the old configured name!
I had this problem once when I forgot to specify the option in the Gadget XML file. I solved it by adding this to the XML:
<UserPref name="projectOrFilterId" datatype="hidden"/>
I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)