How to transfer javascript data between websites? - php

i simply want to transfer a javascript array from one page to another javascript array on another page within the same domain. Php's get does not work because the user should not see the data and i don't know whether/how this could be done with post.
How would you solve this?
Thanks.

Yes, this is trivially easy to do. The best way is to use localStorage, which is essentially cookies for the 21st century.
So on the first page:
localStorage.setItem('data', JSON.stringify(yourdata));
And on the second page:
var yourdata = JSON.parse(localStorage.getItem('data'));
You could use sessionStorage if you only need the data to work for the current browser session.
If you need to support older browsers, there are various shims that will add in the functionality. This one looks quite good to me.

You can try to store this array in cookie using js. After receiving this array from cookie you can delete it.

if you are using jquery you can do something like this
$.post("test.php", { name: "John", time: "2pm" } );

This would be cross-site scripting (XSS), which cannot be done reliably with JS.
If the pages are on the same domain, you can use PHP $_SESSION to keep data related to the user.

If pages of same domain:
You need to post data to the other page using a form / AJAX.
If Not , With JS you cannot
You need a server side code/process to handle data like that.

Related

The best way to change the text on a webpage without refreshing

I'm trying to emulate the upvote/downvote system used on the SE sites. Each of my pages have a score which users can upvote or downvote.
The arrows are images with onclick links to javascript functions. I need to find a way to dynamically change the score without refreshing the page and then run a script (probably PHP) to increment the score in the server's data files.
Is javascript the best way to do this? I'm not that big of a fan of letting users see the source for my functions.
This is only possible using Javascript.
Don't worry about users seeing the source; as long as the server is secure and well-designed, it won't do any harm.
You should only implement display and validation logic in Javascript; everything must be validated again on the server.
Welcome to AJAX.
The easiest way to do that is to use jQuery and its $.ajax method.
See http://api.jquery.com/jQuery.ajax/
It's as simple as
$('a.upvote-button').click(function() {
$.ajax('/posts/123/upvote', {type: 'post'});
return false;
});
Yes, you need javascript (or something considerably less sane) to do this. Namely, you need an AJAX callback.
I'm not that big of a fan of letting users see the source for my functions.
The client-side source of your "function" would be ridiculously simple. It could be as simple as:
$.post('/1234567/vote/up')
You may use a direct link to a php script (and form post values) instead, and without a javascript library it would be a few more lines, but you shouldn't need to expose anything of value in your javascript.
Use javascript. JQuery is an excellent choice for manipulating on screen content and interacting with a server via asynchronous calls.

Create a php/mysql form to be embedded on many different websites

I am not sure where to start, and would appreciate it if someone could point me in the right direction. I would like to create a simple form 'widget' for embedding on different websites.
The idea is that the form reside on my server, and the form information will be submitted to the database on my server, but will be embedded on other sites.
** The form has dynamic drop down menus that populate based on $_GET variables. For example, if I were using an iframe it would look like this...
<iframe src="http://www.example.com/form.php?id=555"></iframe>
Should I use an iframe or would javascript be better for this, is there a better way? What are the security concerns that I need to look out for?
Your best solution for this would to use an iframe.
The reason you cannot do this with javascript is because of most browsers security policy regarding cross site scripting.
With an iframe, you will be able to provide the end user a URL and then they would be able to position the frame anywhere they'd like. I imagine you would provide a URL with a specific path for each user, or a variable to define the user.
Something like:
<iframe src="http://yourdomain.com/form/?clientid=12345&style=woodgrain"></iframe>
One of the problems with the browser origin policy is that the website owner will not be able to style your forms themselves, nor will they be able to manipulate the DOM within that iframe in any way. This might actually be a blessing or a curse for you, depends on the circumstance.
If you need action after the form is submitted, you can always have the site use a script with a function that does nothing during the first iteration, but on the second iteration changes the iframe source, or even removed it from the DOM of the parent site. This would be done via an onLoad="" action in the iframe tag.
As mentioned above Cross Browser security restrictions limit your alternatives
There are 4 alternatives I know to get around this. JsonP is probably the most flexible, but I've included them all here for completness.
1) iframe is the easiest, but your widget will have limited access to the website that contains it and vis versa
2) Jsonp = most flexible - this works by using the tag. Your serverside code takes a callback parameter and tags it on front of any json it passes back.
Example in php
<?php
header("content-type: application/json");
$json = array('example'=>'results');
// Wrap and write a JSON-formatted object with a function call, using the supplied value of parm 'callback' in the URL:
echo $_GET['callback']. '('. json_encode($json) . ')';
?>
And the JQuery code would look like this
$.ajax({ url:'http://yourserver.com/ajax.php',
dataType:'jsonp',
success: function(data)
{ alert(data); }
});
Your widget consumers can either copy paste, the javascript they need or better yet load it directly off of your web server with a script src call.
3) DNS alias - Require all users of your widget to make an entry in their dns to your server so its in the same top level domain. IE point - widgetprovider.consumersdomain.com to your server. (You'll need a fixed ip as setting up virtual host for all the domains woulc be troublesome) You can then load the javascript with a script tag as in above, but you don't have to worry about jsonp and can use standard ajax calls to interact with the site.
4) Flash, Silverlight - Can get around cross domain policy by including an xml file on your server.
Bonus - I think you'll be able to do this with WebSockets once that roles out for real.
I've never done anything like that before. But you could use jQuery to load your form from an external link.
$("#feeds").load("feeds.html");
You could use some PHP to.
include 'your external path';
Then your form could look like the following:
<form action="yourExternalActionLink" method="post or get">
some tags...
</form>
I don't think you have any other option other than going with an iFrame.
Most of the modern browsers don't even allow accessing websites other than your own domain using ajax/Javascript.
you have to go with iframe, as long as you want the stuff to reside on your own server for easy updates
I haven't actually tried it but there are a lot of techniques to do cross-domain ajax requests. Here's one: http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/ . The javascript solution to this would be something like this:
$.ajax({
url: 'yoursite.com/forms/272.json?param1=23&param3=df',
type: 'get',
success: function (response) {
//populate a form with response data.
}
});
So you cook up an API on your server that throws back JSON about what the form should look like, pass it whatever params you need. You get JSON back and can build the form however you like. That would be the javascript solution anyway.
But as others have mentioned cross-domain ajax isn't something you're supposed to be able to do, or so I'd thought. So if you were interested in trying this way I'd look into YQL (what the mod uses to do this) a bit more: http://developer.yahoo.com/yql/
if you want to do something out of the box... why dont you try Zoho creator forms?!
its easy and handy to use.
http://creator.zoho.com

How to pass JS variable to php?

I have a javascript functions which returns a hash. I need to pass this hash to php to do stuff with it. Whats the best way to do that?
Assuming you mean JavaScript function returns a hash and sends it to PHP - then AJAX
You should give more info about what exactly you are trying to do. Like this all we can do is guess and you'll get no good answers. But the usual suspects in this case are:
AJAX (or JSON)
Cookies
Hidden form fields, where you set the value via JS
Give more info and we can be more specific.
You could use a cookie. How the exchange takes place (AJAX, page reload, whatever) is up to you.
in PHP: see setcookie()
in JS: see document.cookie - or perhaps a JS library such as Dojo / jQuery.
Use AJAX. But remember, never trust data coming in from GET or POST and always run the data through a security check before using or storing it.
look into jquery, this will make your this easier!
$.get('myphp.php?senddata='+javascriptdata,function(receivedata){
alert('this is what was received' + receivedata);
});
or you could set a hidden input's value in a form and submit.

Fetching content from Website on another Server

What i basically want to do is to get content from a website and load it into a div of another website. This should be no problem so far.
The problem is, that the content that should be fetched is located on a different server and i have no source access to it.
I'd prefer a solution using JavaScript of jQuery.
Can i use a .htacces redirect to fetch the content from a remote server with client-side (js) techniques?
I will also go with other solutions though.
Thanks a lot in advance!
You can't execute an AJAX call against a different domain, due to the same-origin policy. You can add a <script> tag to the DOM which points at a Javascript file on another domain. If this JS file contains some JSON data that you can use, you're all set.
The only problem is you need to get at the JSON data somehow, which is where JSON-P callbacks come into the picture. If the foreign resource supports JSON-P, it will give you something that looks like
your_callback( { // JSON data } );
You then specify your code in the callback.
See JSONP for more.
If JSONP isn't an option, then the best bet is to probably fetch the data server-side, say with a cron job every few minutes, and store it locally on your own site.
You can use a server-side XMLHTTP request to grab your content from the other server. You can then parse it on you server (A.K.A screen-scraping) and serve-up the portion you want along with your web page.
If the content from the other website is just an HTML doc that you want to display on your site, you could also use an iframe to pull it in. You won't have access to any of its content because of browser security rules.
You will likely have to "scrape" the data you need and store it on your server.
This is a great tutorial on how to cache data from an external site. It is actually written to fetch and store XML, so it'll need some modification. Also, if your site doesn't allow file_get_contents then you may have to modify it to use cUrl.

javascript php array

i have a js array like this:
var myArray = [];
myArray[1] = 'test';
myArray[2] = 'test';
-i want to hide it from users to see it. how can i store just the array in a php script and call it?
right now i have the .js separate from my form. and i just call it. but anyone can easily view source and visit the url using the .js name
-another question i have is to hide a url values from the user. i have something like this:
www.test.ca/people.php?id=12
i want to hide the values. thanks
For the JS code, if the browser has to execute it, then the user can see it. Not much you can do.
If you want to carry values between pages and you don't want them to be seen, don't use a query string -- use PHP sessions instead.
All Javascript code is viewable from the client. There really is no way around this.
Even an AJAX call can be viewed via a good browser plugin.
Javascript is a client-side executed script, so you won't ever be able to hide it.
You can encrypt it, you can make it difficult to view it, but that's pretty useless.
Just put it in your sources, or if you want to hide it a little further, get the array with an AJAX call, and make the call show nothing when it's not called with AJAX (the array can still be revealed with developper browser plugins, or with being hacked adding extra headers.
Here's the PHP condition code : if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
Don't try to make it harder then that, it will be a waste of time.
Think that the browser is a transparent box. Everything you want to hide, needs to sit on the server.
If you want to send data across multiple pages, you have two options -
Use PHP Sessions
Use hidden fields
I would recommend the second option, because PHP sessions have the same problem as using a global variable, i.e., you can't use the same key in the whole applications, it is harder to maintain a session etc.
You can't hide a JS code from the user, because the browser will certainly execute it.

Categories