weixin_33724046 2013-06-10 02:55 采纳率: 0%
浏览 34

Rails,AJAX表单验证

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.

  • 写回答

2条回答 默认 最新

  • 妄徒之命 2013-06-10 03:34
    关注

    You are trying to make an synchronous ajax request. In short, you can do it by set async in ajax object to false.

    You can found your solution here : How to make JQuery-AJAX request synchronous.

    Hope this help.

    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作