Passing JSON Through URL - javascript

I have two html files, and the task for us is to pass data between the two. Then I came up with the idea of sending the data through the URL using the hash, and parsing this link something like JSON.parse(window.location.hash.slice(1)); and assigning it to a local variable. It seems to work for the couple try. But when I populated my JS files with codes error occurs. Can you tell what alternative can I do.? Here's the console errors. I'm using jquery by the way ..
The Console Error
Thank you!

JSON contains a number of characters that are not legal in urls.
A simple way around this could be to simply encode the JSON data using Base64.

You can use the latest way of accessing the data from one page to another:
//1st page
storage["key"]=data;
//2nd page
var value= storage["key"];

I think jQuery.param is what you need it converts a Json into a URL String
http://www.sourcecodemart.com/convert-json-object-to-url-query-string/

This won't work in the long run. urls are limited to about 2000 characters. What is the maximum length of a URL in different browsers?
You have to base64 encode the json to have it live in the URL. This eats up a lot of the available characters.
You don't get the same limitations when doing POST requests but a HTML page can't access post requests.
You might want to look at postMessage and embedding one page in the other in an iframe to do cross communication.
Also if the urls are on the same domain, just use local or session storage.

Related

Using DOMXpath to extract JSON data

I have used php simple html dom to no success on this issue.
Now I have gone to DOMDocument and DOMXpath and this does seem promising.
Here is my issue:
I am trying to scrape data from a page which is loaded via a web service request after the page initially shows. It is only milliseconds but because of this, normal scraping shows a template value as opposed to the actual data.
I have found the endpoint url using chrome developer network settings. So if I enter that url into the browser address bar the data displays nicely in JSON format. All Good.
My problem arises because any time the site is re-visited or the page refreshed, the suffix of the endpoint url is randomly-generated so I can't hard-code this url into my php file. For example the end of the url is "?=253648592" on first visit but on refresh it could be "?=375482910". The base of the url is static.
Without getting into headless browsers (I tried and MY head hurts!) is there a way to have Xpath find this random url when the page loads?
Sorry for being so long-winded but I wanted to explain as best I could.
It's probably much easier and faster to just use a regex if you only need one item/value from the HTML. I would like to give an example but therefor I would need a more extended snippet of how the HTML looks like that contains the endpoint that you want to fetch.
Is it possible to give a snippet of the HTML that contains the endpoint?

Passing large amounts of data from one page to another without POST?

I'm using a web server framework which works with only GET requests, at the moment I'm trying to pass a large amount of data, that is the text content in a textarea which comes from user input, into another page which echoes the user's input.
I've attempted Querystrings but I end up receiving the error "Requested URL too long".
Any suggestions as to what method I should use?
If you can only send data encoded in GET requests, then you will have to break up the request and send it in multiple parts.
You could either use Ajax or store the entire set of data in localStorage and fetch each chunk in turn as the page reloads.
One approach would be to make a request to an end point that allocates you a unique ID. Then send a series of requests in the form: ?id=XXX&page=1&data=... before closing it with ?id=XXX&total_pages=27 at which point you assemble the different pieces on the server.
This way lies madness. It would be much better to add POST support to your framework.
Try using Javascript Cookies.
you can store the textarea value there and then read it in another page (or wherever you want).
Here's a tutorial
http://www.w3schools.com/js/js_cookies.asp

Share data between HTML pages

I want to send some data from one HTML page to another. I am sending the data through the query parameters like http://localhost/project/index.html?status=exist. The problem with this method is that data remains in the URL. Is there any other method to send the data across HTML pages using JavaScript or jquery.
why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')
or more permanently:
localStorage.setItem('label', 'value')
localStorage.getItem('label')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I know this is an old post, but figured I'd share my two cents. #Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem and
sessionStorage.myValue = 'value'
in place of setItem.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
Link 1
And, of course, the CORS spec:
Link 2
~Cheers

.ajax load remote page content to javascript var

I want to get a short string hosted on a server where I do not have access to the data as XML, JSON, etc. I am trying to use either .load or .ajax to do this. I want to be able to parse the data into a javascipt array. The entire contents of the remote page is text and I am happy to take all of it and remove what I do not need via a small javascript. I have tried:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://url:8888/data", success:function(result){
$("div").html(result);
}});
});});
</script>
I have two questions.
1- why does this not work?
2- What would be the best way to store the string in a javascript var?
I am sure JQuery is working correctly.
The answer would be to long to post here (really). But look those up:
Same Origin Policy
Padded JSON
If you have no control over the remote site, you have lost - you will not get any data from it by Ajax (which is actually a feature, not a limitation of the technology). One way of circumventing the protection would be to build a proxy that just mirrors the remote service you need to reach and makes it available in the same domain that your main HTML came from.

Greasemonkey communication with server that requires windows-1250 encoding

I'm developing a greasemonkey plugin, which is supposed to send a form in background using POST (GM_xmlhttpRequest) on an application not under my control. That application is written in PHP and seems to expect all its input in windows-1250 encoding. What I need to do is to take all the form fields as they are, edit just one of them and resubmit. Some of the fields use accented characters and are limited in length.
Not a problem in theory - I iterate over all form fields, use the encodeURIComponent function on the values and concatenate everything to a post request body. HOWEVER. The encodeURIComponent function always encodes characters according to UTF-8, which leads to all sorts of problems. Because PHP doesn't seem to recode my request to windows-1250 properly, it misinterprets multibyte strings and comes to the conclusion that the resubmitted values are longer than the allowed 40 characters and dies on me. Or the script just dies silently without giving me any sort of useful feedback.
I have tested this by looking at the POST body firefox is sending when I submit the form in a browser window and then resending the same data to the server using xhr. Which worked. For example the string:
Zajišťujeme profesionální modelky
Looks as follows, when encoded by encodeURIComponent:
Zaji%C5%A1%C5%A5ujeme%20profesion%C3%A1ln%C3%AD%20modelky
Same thing using urlencode in PHP (source text in windows-1250) or Firefox:
Zaji%9A%9Dujeme+profesion%E1ln%ED+modelky
Apparently, I need to encode the post body as if it were in windows-1250 or somehow make the server accept utf-8 (which I doubt is possible). I tried all kinds of other function like escape or encodeURI, but the output is not much different - all seem to output in utf-8.
Is there any way out of this?
Another way to get Firefox to encode a URL is to set it as the href of a link. The property (NOT attribute) will always read back as an absolute link urlencoded in the page's encoding.
For a GET request you would simply set the href as http://server/cgi?var=value and read back the encoded form. For a POST request you would have to take the extra step to separate the data (you can't use ?var=value on its own because the link reads back as an absolute link).
Let the browser encode the form. Put it in a hidden iframe and call submit() on it.

Categories