0

I am working on Dynamic WebProject using JAVA/REST as my backend. I need to pick up data from html form and send it as a JSON object with AJAX to my server. How can I do that?

This is my html form:

<form role="form" id="registrac" method = "post" class = "ajaxForm">

      <input type="text" id="userName" class="form-control" placeholder="Korisnicko Ime"><br>
      <input type="password" id="password" class="form-control" placeholder="Lozinka"><br>
      <input type="text" id="firstName" class="form-control" placeholder="Ime"><br>
      <input type="text" id="LastName" class="form-control" placeholder="Prezime"><br>
      <input type="text" id="role" class="form-control" placeholder="Uloga"><br>
      <input type="text" id="phone" class="form-control" placeholder="Telefon"><br>
      <input type="text" id="email" class="form-control" placeholder="Email"><br>
      <input type="text" id="address" class="form-control" placeholder="Adresa"><br>
      <input type="text" id="image" class="form-control" placeholder="Slika"><br>   
      <input type="submit" id="regist" class="btn btn-lg btn-primary btn-block" value="Potvrdi">

</form>

And this is my ajax function:

$.ajax({
            headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
            },
            url: '../SnippetApp/rest/users/registerUser',
            type : 'POST',
            data : data,
            success: function(response){

            }


        });

I don't know how to collect data and make it JSON object.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
avaXmovieS
  • 11
  • 3
  • Have a look here https://stackoverflow.com/a/11338832/578855 – muasif80 Sep 04 '17 at 22:49
  • Possible duplicate of [Convert form data to JavaScript object with jQuery](https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery) – tima Sep 04 '17 at 22:51

2 Answers2

0

You can get form data as below. Below is an example.

Use $('form').serializeArray(), which returns an array:

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

Other option is $('form').serialize(), which returns a string:

"foo=1&bar=xxx&this=hi"
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
amit wadhwani
  • 1,140
  • 1
  • 7
  • 12
0
var formData = JSON.stringify($("#myForm").serializeArray());

and set

data : formData
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197