0

I'm facing the following problem and I wonder if I could get some help, (please do not bully me ;)), I have the following structure, basically is validating a form with POST method using json, I have a php controller which receive a $data array with user and password and return a json encond with the corresponding answer, this is what I have:

Login Form

  <form class="login-form" method="post" name="loginform"> 
   <fieldset>
      <legend>Login</legend>
      <label>
        <input id="user" type="text" placeholder="User" />
      </label>
      <label>
        <input id="pass" type="password" placeholder="Password" />
      </label>
      <input type="submit" placeholder="Submit" />
   </fieldset>
  </form>

And my Javascript looks like this:

 function login() {
  var arr = //missing ;
   $.ajax({
      url: 'myController.php',
      type: 'POST',
      data: JSON.stringify(arr),
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      async: false,
      success: function(msg) {
           console.log(msg);
      },
      timeout: 5000,
      error: function(jqXHR, textStatus, errorThrown) {
           alert("Error al cargar ");
      }
   });  
 }

 $('.login-form').on('submit', function () {
    login();
    return false;
 });

So far I think this should work, however, I cannot find how to send the parameters to looks like this:

  {
    username: userinput,
    password: passwordinput
  }

And asign that json to arr

Any advise on this?

Thanks in advanced!

andresmijares
  • 3,658
  • 4
  • 34
  • 40
  • 1
    You need to serialize the form-data to get the parameters to look like the ones you want, check this SO http://stackoverflow.com/questions/1184624/convert-form-data-to-js-object-with-jquery – andy May 14 '14 at 20:56

1 Answers1

0

You just need to get the form data. Since you're already using jQuery:

var arr = { "username":$("#user").val(), "password":$("#pass").val() }
Brian Anderson
  • 621
  • 7
  • 22