This is stupid but for future reference. I did put all my code in:
$(document).ready(function () {
//your jQuery function
});
But still it wasn't working and it was returning undefined
value.
I check my HTML DOM
<input id="username" placeholder="Username"></input>
and I realised that I was referencing it wrong in jQuery:
var user_name = $('#user_name').val();
Making it:
var user_name = $('#username').val();
solved my problem.
So it's always better to check your previous code.