Question

I want to pass the object to the new page by using only client side script(javascript), and I want to read the data back when the new page is loads, but I could not find any tutorial or method to get it.

function postToURL(path, parameters) {
    var form = $('<form></form>');

    form.attr("method", "post");
    form.attr("action", path);

    $.each(parameters, function(key, value) {
        var field = $('<input></input>');

        field.attr("type", "hidden");
        field.attr("name", key);
        field.attr("value", value);

        form.append(field);
    });

    // The form needs to be a part of the document in
    // order for us to be able to submit it.
    $(document.body).append(form);
    form.submit();
}
Was it helpful?

Solution

The POST message sent to the server to retrieve the current page is not exposed, by the browser, to JavaScript in that page, so you cannot.

Pass the data via some other technique (such as through the URL, or localstorage).

OTHER TIPS

Yeah, POST data is only handled and seen by the server side (ex. PHP). Javascript is on the client side so it will never be able to see that data unless the POST data first gets passed to server side and that server side in turn hands it off to the client side (ex. Javascript).

Consider using GET as your method in your code above so that you can pass the parameters inside the actual URL to make it accessible to the browser / client / Javascript.

parameters can be parsed from a JSON-encoded string. If you build your parameters programmically (in the previous step) like:

parameters = {};
parameters['USA'] = 'Washington DC';
parameters['UK'] = 'London';

You can create a flat JSON String representing your structured data by:

parametersString = JSON.stringify(parameters);

and end up with something like this:

"{'USA': 'Washington DC', 'UK': 'London'}"

You can store this string in a cookie, or in a query string or fragment part of the URL.

Your next page can read back this value on the following page, and re-create the structured parameters by decoding the JSON string like:

parameters = JSON.parse(parametersString);

and you're getting the original data back, on which you can run JQuery's each.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top