2

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>
Alex B
  • 1,575
  • 5
  • 16
  • 19

3 Answers3

3

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.

Community
  • 1
  • 1
Ioannis Karadimas
  • 7,746
  • 3
  • 35
  • 45
  • Awesome. Took my a while to get used with some of the JS stuff but i'm sort of ok for now. The thing that still bugs me is that I'm using Twitter Bootstrap for the UI feel and the script craps out at the $.each part. Can't really figure out how to fix it. I edited my question to add the form html. – Alex B Mar 20 '12 at 19:17
  • I 've edited my post to accomodate your additional questions. – Ioannis Karadimas Mar 26 '12 at 12:15
2

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>
maerics
  • 151,642
  • 46
  • 269
  • 291
0

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;    });

});
Alok
  • 2,629
  • 4
  • 28
  • 40
thomas
  • 1