Alex B
Alex B

Reputation: 1575

Send JSON from HTML form with NODEJS backend

I haven't done front end HTML since I was 10 and that was drag and drop frontpage stuff. with static pages. As a result I'm really rusty.

What I need to do is put together a web client for a rest API that I wrote in NodeJS. My question is how, do you send a request from a form (say a log in form) to the server where the body of the POST request is a JSON of the email/password?

HTML form:

<form id="loginForm" action="" method="" class="form-horizontal">
  <fieldset>
        <legend>Log in</legend>
        <div class="control-group">
        <label class="control-label" for="email">Email</label>
        <div class="controls">
                <input type="text" class="input-xlarge" id="email">
        </div>
      </div>
        <div class="control-group">
            <label class="control-label" for="password">Password</label>
        <div class="controls">
                <input type="password" class="input-xlarge" id="password">
        </div>      
      </div>
      <div class="form-actions">
            <button type="submit" class="btn btn-primary">Save changes</button>
            <button class="btn">Cancel</button>
            </div>
  </fieldset>
</form>

Upvotes: 2

Views: 10922

Answers (3)

thomas
thomas

Reputation: 1

This might help you. Here is the form below: If you notice there is action and method if you don't know what these are, just go on and search for it. Action is the target server file that handles the information you send and method is get which is retrieving not updating.

Existing Users


Username:

Password:

Keep Me Logged In

Here is the jquery part to handle the ajax call:

 $.ajax({
           type: "GET",
            url: action,
            data: form_data,
           success: function(response)
            {
               if($.trim(response) == 'success')
                    window.location.replace("profile.php");        
               else
                   $("#result").html(response);
          }
        });

       return false;    });

});

Upvotes: 0

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7896

I suggest a lot of reading. To get you started with a very basic example, though, you will find a page with a sample form below that does what you need. You just need to replace the string your URL here with the actual URL you expect will be doing the handling.

The serializeObject() function was taken from here: Convert form data to JavaScript object with jQuery

<html>
    <body>
        <form id="loginForm" action="" method="">
            Username: <input type="text" name="username" id="username" /> <br />
            Password: <input type="password" name="password" id="password" /> <br />
            <input type="submit" />
        </form>

        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $.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;
                };          


                $("#loginForm").bind("submit", function(evt) {
                    console.log(JSON.stringify($("#loginForm").serializeObject()));

                    $.ajax({
                        url: "your URL here",
                        type: "POST",
                        contentType: "application/json",
                        data: JSON.stringify($("#loginForm").serializeObject()),
                        success: function (data, textStatus, jqXHR) {
                            // do something with your data here.
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            // likewise do something with your error here.
                        }
                    });

                    return false;
                });

            });
        </script>
    </body>
</html>

The problem with your form is that input elements don't have name attributes. The name attribute is essential in many ways, so I would fix your html by setting each element's name attribute to the same value as its id attribute. The serializeObject function relies on form elements having names.

Upvotes: 3

maerics
maerics

Reputation: 156444

Here's an example using jQuery:

<form name="myform" action="#" method="POST">
  Username: <input type="text" id="user" name="username"/><br/>
  Password: <input type="password" id="pass" name="password"/>
  <input type="submit" id="login" value="Login"/>
</form>

<script type="text/javascript">
  var user=$('#user').val(), pass=$('#pass').val();
  $('login').bind('click', function() {
    $.ajax('/my/url', {
      type: 'POST',
      contentType: 'text/json',
      data: JSON.stringify({username:user, password:pass}),
      complete: function() { /* Do something with the response. */ }
    });
    return false; // Prevent form submit.
  });
</script>

Upvotes: 2

Related Questions