dimanche 8 janvier 2017

Using Cookies to transfer JSON data between 2 web pages

So I've been trying to do this for more than a day now. I'm getting a few user inputs through a form (ex - a name of a car), then I search through a JSON file to see whether its available. After this I'm trying to send the results of the search to a results page. I've been trying to use a cookie for this process. However there is a problem that I can't figure out. Following is my code,

This is getting input and searching:

function search() {
var name = $("input[name=carName]").val();

var cars = new Array();

$.getJSON("properties.json", function (data) {
    $(data.cars).each(function (index, value) {
        if (value.name == name) {
            cars.push(value);
        }
    });

    if (cars.length > 0) {
        send(cars);
    } else {
        // do some handling
    }
});

function send(cars) {
var str = JSON.stringify(cars);
Cookies.set("carResults", str);
window.location.replace("result.html");
}

This is the script from result.html

<script>
    $(document).ready(function () {
        var temp = Cookies.get("searchResults");
        var cars = JSON.parse(str);

        if(results!=null) {
            for (var i = 0; i < results.length; i++) {
                var temp1 = "Found a " + cars[i].name;
                $("#resultArea").append(temp1);
            }
        } else {
            $("#resultArea").append("Nothing to show");
        }
    });
</script>

PS. I'm using a javascript library called cookie.js for creating cookies




Aucun commentaire:

Enregistrer un commentaire