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>
Related
I need to have the functionality in the server side in order to hide the implementetion to the final user.
I didn't find a topic with this kind of solution.
I have a .js file with functions I use within the html5 file.
The js files are "called" in the html by using the script tag, but through the url the user can track them and see the .js file content. I don't want this to happen.
$getScript() does the job, but again the url can be cathched, thus the file content too. Much the same with $ajax function.
Everything work ok, but I want to hide the js content.
The .js file is something like this:
var x, x,....
function A(){...}
function B(){...}
and so on, I use A(), B() functions in the html.
Which is the best approach to get the content file from the server without doing the url visible?
Server: nodejs. (I send some json files through socket.io correctly, but I don't know how to achieve this other issue.
Thanks in advance, best!
If you are sending sensitive information to the client then you are doing it wrong. No matter if the client has the URL to the script, they will still be able to find it if they are determined as long as it is sent to their computer.
Find a different way to accomplish what you are trying to do without sending sensitive information to the client. It is not safe.
I have a javascript file that other people use on their site. It creates a button and loads a css file that is hosted on our server:
style.setAttribute('href', 'http://mysite.com/assets/some.css');
The user can call it in their site like so:
<script type="text/javascript" src="http://mysite.com/global.js"></script>
I want to give the user the ability to upload their own CSS file on my web app that will replace the one that I am setting in global.js.
Currently, I added a custom_css:binary column in the Users table that will hold the CSS file, but this requires the user to stay signed in on the site. I'm not sure if this is the right way to approach this or if there is a better way to do it. Also, what are some security risks to this approach?
I'm using RoR for the backend.
Any help would be great!
UPDATE 1
I'm able to store the uploaded JS file and load the custom CSS, but it's currently checking the current_user - this means the stylesheet will not be rendered for the users. How can I work around this?
I was able to find the solution myself.
There are several ways to approach this:
Add a query string to the JS src
Scrape the page for a certain element that gets generated by your script
I opted for option 1. When I detect a dynamically generated query string, I send that over to the controller in the params hash and load the css file accordingly.
I hope the following isn't too tricky.
I have a simple html button. Now I want to open a filechooser as soon as a user clicks on this button.
I do this like the following:
$('.button').click(function()
{
$('<input type="file"/>').attr('value');
});
This opens a filechooser, but I want this file-chooser to only show files on the server, not on the client. I've searched the net but couldn't find an adequate solution so far.
Any proposals are welcome :)
Impossible, sorry. You'd need to use server side code to make a tool that allows the end user to browse the server's files.
The file input is used for the end user to choose file(s) on their machine. It has no knowledge of the server's files.
It's not tricky, but you can't use Input tag for it. The steps are:
Create a module to traverse the directory on your server and output is a JSON format in whatever server implementation that you choose
Create a REST endpoint to give the browser the JSON output from step #1
Use AJAX to call this REST webservice and get the directory listings
Use Tree Widget to basically build the file structure based on JSON (I am sure if you look, one is probably there already for you to use)
There's no simple way to do it. If you use jQuery UI you can use a plugin like this:
http://gusc.lv/jquery/gcmedia.html
With a server-side scripts that outputs a list of the files you want to make browseable.
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>
I have the following problem which I'm trying to solve with javascript. I have a div with a background image specified in a css file, and I want my javascript to change that image periodically (let`s say every 5 secs).
I know how to do that, the problem is that I have a folder of images to choose from for the back image. I need to be able to read the filenames (from the image folder) into an array, change the background image of the div, delay for 5 seconds and change again.
in your javascript, use an array like
var images = [ "image1.jpg", "image2.jpg", "image3.jpg" ];
function changeImage() {
var image = document.getElementById("yourimage");
image.src=$images[changeImage.imageNumber];
changeImage.imageNumber = ++changeImage.imageNumber % images.length;
}
changeImage.imageNumber=0;
setInterval(changeImage,5000);
The values in the array should be generated by your php
You're still going to need php or asp to query the folder for files. Javascript will not be able to "remotely" inspect the file system.
You can do something like the following in jQuery:
$.ajax({
url: 'getFolderAsArrayOfNames.php',
dataType: 'json',
success: function(data) {
for(var i=0;i<data.length;i++) {
// do what you need to do
}
});
});
And in your getFolderAsArrayOfNames.php, something like this:
echo "function "
.$_GET['callback']
."() {return "
.json_encode(scandir('somepath/*.jpg'))
."}";
If you are using Apache as your
web server, and
if you can configure
it to provide a default directory
listing for your images folder (use
the appropriate options in
httpd.conf and/or .htaccess), and
if you don't care that the list of
images is available to everyone who
visits your web site,
then you don't need PHP or any other server-side processing.
You can use XMLHttpRequest (or the jQuery ajax function, which is a nice wrapper) to get the listing for the folder. The response will be HTML and it will look something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /demo1/images</title>
</head>
<body>
<h1>Index of /demo1/images</h1>
<pre><img src="/icons/blank.gif" alt="Icon "> Name Last modified Size Description<hr><img src="/icons/back.gif" alt="[DIR]"> Parent Directory -
<img src="/icons/image2.gif" alt="[IMG]"> tree.gif 17-Mar-2009 12:58 6.2K
<img src="/icons/image2.gif" alt="[IMG]"> house.gif 17-Mar-2009 12:58 6.5K
<img src="/icons/image2.gif" alt="[IMG]"> car.gif 02-Mar-2009 15:37 8.4K
<img src="/icons/image2.gif" alt="[IMG]"> elephant.jpg 02-Mar-2009 15:37 3.4K
<hr></pre>
<address>Apache/2.0.63 (Unix) Server at zeppo Port 80</address>
</body></html>
Since this output is pretty predictable, you might try parsing out the filenames using a JavaScript regular expression, but it's probably just as easy and more robust to create a hidden DIV on your page, put the HTML response into that DIV, and then use DOM methods to find <a href>s that are after <img> tags with an alt="[IMG]" attribute. Once again, using jQuery Selectors or similar helper methods available in other toolkits will make this DOM parsing pretty easy.
Once you have the URL of the new image (parsed from the href), you can set the new CSS background for your div with the .style.backgroundImage property.
You cannot do any file IO using JavaScript mainly because of security reason, so anyway you have to create some back end service which will update you with an list of available files in your folder. You don't have to do it in a hard way, you can use AJAX to it smoothly and nicely
You can't read a folder's contents, neither on the server nor on the clientside.
What you can do is to read the folder's contents with the help of a serverside script, and load it to a JavaScript array while processing the page.
This would not be ideal but in the absence of server-side processing (which you really should be doing--either PHP or Rails or Perl or whatever your host supports), you could allow directory listing on your images folder. This has security implications.
Then loading e.g., http://mysite.com/rotatingImages should respond with a list of files. You could do this with AJAX, parse out the relevant hrefs, push them onto an array and render your rotating images in JS.
You must send the list of names along with the JavaScript and then iterate through it.
A noted above, you can not access server's system from a client's browser (which is where JavaScript runs).
You have 3 possible solutions:
Create the JavaScript file via some dynamic back-end (php or perl scripts are best for that).
The main JavaScript function could still be static but the initialization of the array used by it (either as a snippet on the main HTML page or a separate .js imported file) would be a php/perl generated URL.
A recent StackOverflow discussion of the topic is at link text
Make an XMLHttpRequest (AJAX) call from your JavaScript to a separate service (basically a URL backed by - again - php/perl backend script) returning XML/JSON/your_data_format_of_choice list of files.
This is probably a better solution if you expect/want/need to refresh a frequently-changing list of images, whereas a pre-built list of files in solution #1 is better suited when you don't care about list of files changing while the web page is loaded into the browser.
An un-orthodox solution - if browsers you care about support animated background images (gif/png), just compile your set of images, especially if they are small sized, into an animated gif/png and use that as background.