-2

I have a <form>. I want to strip that form (or other HTML) of particular data elements, form them into JSON, and then send that JSON as a request to the domain server, where the server will consume it.

What does the JavaScript look like to do the job described above?

Note: I do not need CORS (e.g. no cross-site, it's all same-server)

Termininja
  • 6,620
  • 12
  • 48
  • 49
Larry
  • 23
  • 5

1 Answers1

0

Get data in Forms

You could use the serializeArray for the forms. You just need to parse it in the correct way. An example method is provided below

$.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;
};

Example in action: http://jsfiddle.net/sxGtM/3/

Get content in HTML elements

You can get the content of an div or something else by using the document.getElementById method and then the innerHTML property

var MyDiv1 = document.getElementById('DIV1');
var content = MyDiv1.innerHTML;

Post object to server using jQuery

function sendData() {
$.ajax({
    url: '/example',
    type: 'POST',
    contentType: 'application/json',
    data: <Your JSON Object>,
    dataType: 'json'
});
}
Tom Droste
  • 1,324
  • 10
  • 14
  • Thank you for a great answer and quickly! Here is what I have so far: `code` $(function() { $('form').submit(function() { $SendData(JSON.stringify($('form').serializeObject())); return false; }); }); $(function sendData(form_data) { $.ajax({ url: '/my_data', type: 'POST', contentType: 'application/json', data: form_data, dataType: 'json' }); }); I am a total neophyte at JavaScript, so forgive this if it is wildly wrong. :-) – Larry May 18 '16 at 13:13
  • Sorry--I am not getting yet how to format code in responses – Larry May 18 '16 at 13:20
  • Please modify your first post with the updates. From there I can specify my answer better. – Tom Droste May 18 '16 at 14:20
  • Hi Tom! Yes--that post up there is really ugly! I apologize. I don't yet know how to format these bits to properly display. However! I was able to get it all working and in fine fashion. Your answer, plus a little more research resolved into working code! Thanks again! – Larry May 18 '16 at 17:10