Gigacore
Gigacore

Reputation: 165

How to output JSON representation of form data in new file or window?

I have an HTML form and using Serialization jQuery snippet to convert form data to JSON representation as taught in this: Convert form data to JavaScript object with jQuery

I am only able to display the JSON output in an div tag. But I want to display the output in a new file or window upon form submit button click.

My jQuery Serialization snippet in header:

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject(), null, 4));
        return false;
    });
})

My HTML

<form id="student" method="post">
<label>Name: </label><input type="text" name="studentname" /><br />
<label>Age: </label><input type="text" name="age" /><br />
<label>City: </label><input type="text" name="city" />
<input type="submit" value="Submit" id="submitbutton" /><br />
</form>

<pre id="result"></pre>

Upvotes: 0

Views: 2000

Answers (1)

Dror
Dror

Reputation: 7303

Putting the result in a new window is easy - just change the submit section to somthing like this:

$(function() {
    $('form').submit(function() {
        var txt = JSON.stringify($('form').serializeObject());
        $('#result').text(txt, null, 4);
        var recipe =  window.open('','ResultWindow','width=600,height=600');
        var html = '<html><head><title>Result Window</title></head><body><div>' + txt + '</div></body></html>';
    recipe.document.open();
    recipe.document.write(html);
    recipe.document.close();
        return false;
    });
})

check out http://jsfiddle.net/u6z4X/

Upvotes: 1

Related Questions