POST to relax api using jQuery

I am writing a function to send data from a form to a rest api. This is what I have, but it does not work, and I cannot understand why.

<script>
    console.log(document);
    var form = document.getElementById("myform");

    form.onsubmit = function (e) {
      // stop the regular form submission
      e.preventDefault();

      // collect the form data while iterating over the inputs
      var data = {};
      for (var i = 0, ii = form.length; i < ii; ++i) {
        var input = form[i];
        if (input.name) {
          data[input.name] = input.value;
        }
      }

    function addData(){
     $.ajax({
             type: "POST",
             url: "http://example.com",
             data: JSON.stringify(data),
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 alert(success);
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }
</script>

Can someone point me in the right direction?

+4
source share
2 answers

You are not calling addData()into the form.onsubmitevent.

form.onsubmit = function (e) {
  // stop the regular form submission
  e.preventDefault();

  // collect the form data while iterating over the inputs
  var data = {};
  for (var i = 0, ii = form.length; i < ii; ++i) {
    var input = form[i];
    if (input.name) {
      data[input.name] = input.value;
    }
  }
  addData();
}
+1
source

call below

addData(data);

function addData(data){// pass your data in method
     $.ajax({
             type: "POST",
             url: "http://example.com",
             data: JSON.stringify(data),// now data come in this function
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 alert("success");// write success in " "
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }
+5
source

All Articles