3

I have a form to submit data through a $.post() in jQuery. The PHP file returns a response in this format:

header('Content-type: javascript/json');
echo json_encode(['state' => true, 'message' => 'Some Message']);
exit;

Which looks like this when encoded and works fine:

{state: true, message: 'Some Message'}

However, I cannot send the form fields. I have tried using the find() function but it returns undefined in the console.

Here is my code:

$(document).ready(function() {

  var Member = {

    login_form: $('#login'),
    create_form: $('#register'),
    response: false,
    response_message: '',

    login: function() {
      var email = this.login_form.find('input[type=email]').val();
      var password = this.create_form.find('input[type=password]').val();
      this.request('/members/login', {
        email: email,
        password: password
      });
    },
    create: function() {
      var email = this.create_form.find('input[type=email]').val();
      var password = this.create_form.find('input[type=password]').val();
      this.request('/members/create', {
        email: email,
        password: password
      });
    },
    request: function(uri, params) {
      $.post(uri, params)
        .done(function(r) {
          Member.response = r.state;
          if (!r.state) {
            Member.response_message = r.message;
          }
        });
    },
    getEmail: function() {
     return this.create_form.find('input[type=email]').val();
    },
    getPassword: function() {
     return this.create_form.find('input[type=password]').val();
    }

  };
  
  $('#submit').click(function() {
   Member.login();
    console.log('[L_CTRL] Response : ' + Member.response_message);
    console.log('[L_CTRL] Email : ' + Member.getEmail());
    console.log('[L_CTRL] Password : ' + Member.getPassword());
  });

});
input {
  margin: 5px;
  background: none;
  padding: 5px;
  border: 1px solid #000;
  width: 80%;
}

button {
  padding: 5px;
  border: 1px solid #000;
  background: none;
  cursor: pointer;
}

button:hover {
  background: #000;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<h1>
Login
</h1>
<form id='login'>
<input type='email' placeholder='Enter your email address...'>
<input type='password' placeholder='Enter your unique password...'>
<button type='button' id='submit'>
Go
</button>
</form>

Could anyone point me in the right direction to accessing the val() of the input fields? Thank-you.

Update: I do not want to directly find it using its ID, ie:

$('#email').val();

Because the ID's can change from form to form.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • Your PHP output is a JSON object. not HTML. It is only able to get state and message values. – SaidbakR Dec 09 '16 at 11:22
  • I would suggest creating your form correctly with labels and input names and id's then you can just get the values with e.g. `$('#login-email').val()` otherwise you're creating a non semantic form which for the most part will be inaccessible to some users – Jez Emery Dec 09 '16 at 11:22
  • I can't because we have multiple login forms on one page, I know I could use classes but it would still have to use familiar methods like `nearest()` therefore, I found the `find()` easier since I only need to know which form they clicked which again, will become a class (`.login-form`) @JezEmery – Jaquarh Dec 09 '16 at 11:29

3 Answers3

3

Replace create_form with login_form, because you're now selecting the register form, not the login form:

getEmail: function() {
    return this.login_form.find('input[type=email]').val();
  },
  getPassword: function() {
    return this.login_form.find('input[type=password]').val();
  }

Full code:

  var Member = {

    login_form: $('#login'),
    create_form: $('#register'),
    response: false,
    response_message: '',

    login: function() {
      var email = this.login_form.find('input[type=email]').val();
      var password = this.create_form.find('input[type=password]').val();
      this.request('/members/login', {
        email: email,
        password: password
      });
    },
    create: function() {
      var email = this.create_form.find('input[type=email]').val();
      var password = this.create_form.find('input[type=password]').val();
      this.request('/members/create', {
        email: email,
        password: password
      });
    },
    request: function(uri, params) {
      $.post(uri, params)
        .done(function(r) {
          Member.response = r.state;
          if (!r.state) {
            Member.response_message = r.message;
          }
        });
    },
    getEmail: function() {
     return this.login_form.find('input[type=email]').val();
    },
    getPassword: function() {
     return this.login_form.find('input[type=password]').val();
    }

  };
  
  $('#submit').click(function() {
   Member.login();
    console.log('[L_CTRL] Response : ' + Member.response_message);
    console.log('[L_CTRL] Email : ' + Member.getEmail());
    console.log('[L_CTRL] Password : ' + Member.getPassword());
  });
input {
  margin: 5px;
  background: none;
  padding: 5px;
  border: 1px solid #000;
  width: 80%;
}

button {
  padding: 5px;
  border: 1px solid #000;
  background: none;
  cursor: pointer;
}

button:hover {
  background: #000;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Login
</h1>
<form id='login'>
<input type='email' placeholder='Enter your email address...'>
<input type='password' placeholder='Enter your unique password...'>
<button type='button' id='submit'>
Go
</button>
</form>
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
2

You're trying to access the response before receive it, you should get the values in the success callback, try :

.done(function(r) {
  Member.response = r.state;
  if (!r.state) {
    Member.response_message = $.parseJSON(r.message);

    console.log('[L_CTRL] Response : ' + Member.response_message);
    console.log('[L_CTRL] Email : ' + Member.getEmail());
    console.log('[L_CTRL] Password : ' + Member.getPassword());
  }
});

Take a look to How do I return the response from an asynchronous call?.

NOTE : you've to parse the response, using $.parseJSON() :

Member.response_message = $.parseJSON(r.message);

Hope this helps.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • I did not even come across that yet since I wasn't returning a message for the time being - you fixed a later issue, appreciated! – Jaquarh Dec 09 '16 at 11:25
2

change this two functions as follow :

    getEmail: function() {
        console.log();
        return this.login_form.find('input[type=email]').val();
    },
    getPassword: function() {
        return this.login_form.find('input[type=password]').val();
    }
rushil
  • 591
  • 7
  • 16