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.