4

I've got some sample code for a form, and now i want to post that data to Restful API. I've checked lot but mostly found results based on TypeScript. I want to do that using only JavaScript. Is there any way to do that using JavaScript?

I want to call Post API on "onSubmit" event. Look at sample code.

(function(app) {
  app.FormComponent = ng.core
    .Component({
      selector: 'form',
      templateUrl: 'app/form.component.html'
    })
    .Class({
      constructor: function() {      
      },
      onSubmit: function() {
        console.log(this.model);
        this.submitted = true;
      },
    });
})(window.app || (window.app = {}));
Lynx 242
  • 7,658
  • 5
  • 22
  • 40
Nikunj Patel
  • 375
  • 1
  • 5
  • 19
  • You might need to revisit your approach. OnSubmit sends data in form-encoded format back to the server. So at least you need to return false to stop that from happening. Usually you would provide a submit function in a service. Don't call http in the UI – stwissel Dec 20 '15 at 03:22
  • Can you provide sample piece of code.? – Nikunj Patel Dec 21 '15 at 04:39

1 Answers1

0

You can use fetch to make your server call:

(function(app) {
app.FormComponent = ng.core
    .Component({
    selector: 'form',
    templateUrl: 'app/form.component.html'
    })
    .Class({
    constructor: function() {},
    onSubmit: function() {
        console.log(this.model);
        this.submitted = true;

        const url = 'http://example.com';
        fetch(url, {
            method: 'POST',
            body: this.model
            //new FormData(document.getElementById('inputform'))
            // -- or --
            // body : JSON.stringify({
            // user : document.getElementById('user').value,
            // ...
            // })
            })
        .then(
            response => response.text() // .json(), etc.
            // same as function(response) {return response.text();}
        )
        .then(html => console.log(html));
    }
    });
})(window.app || (window.app = {}));

As shown in https://stackoverflow.com/a/45529553/512089

Bas van Dijk
  • 7,931
  • 8
  • 51
  • 81