I am new to jQuery, AJAX, and javascript in general, and I am trying to do some front end validation for a rails form that uses an ajax call to have the server run a query. It seems to work well, if I am in the debugger (since the AJAX call has enough time to return and stop the submission of the form), but it wont work all of the time when I am just testing it without the debugger. I believe this happens because after the ajax call, the javascript validation method exits, and the form submits. Here is my javascript method
$('#runner-job-submit').click(function(e) {
runnerJobValidation(e);
});
function runnerJobValidation(e) {
var user_login = $('#user_login').val();
var name = $('#name').val();
var location = $('#location').val();
var description = $('#description').val();
var user_exists;
//AJAX call to check if user exists in the database
$.post("/jobs/user_exists", {user_login: user_login}, function (response) {
if(response == "false") {
$('#runner-new-job-errors').html('');
e.preventDefault();
$('#runner-new-job-errors').append('<small style="color:red"> User doesnt exist </small>');
}
});
if(user_login == "" || name == "" || location == "" || description == "") {
$('#runner-new-job-errors').html('');
e.preventDefault();
$('#runner-new-job-errors').append('<small style="color:red"> Please fill out all fields </small>');
}
}
And here is my controller action url it is hitting
def user_exists?
user_login = params[:user_login]
user = User.where("login = ?", user_login).first
user_exists = user.present?
respond_to do |format|
format.js { render :json => user_exists.to_json}
format.html { redirect_to jobs_path }
end
end
Can someone please tell me the correct way to do this. I feel the solution is to somehow prevent runnerJobValidation()
from exiting before response
is received from the server, but I just dont know how to do this.