2

I'm working on a simple blog-application with Symfony2.
I'd like to check login-data via ajax:

  • if the data is correct -> forward to another page
  • if not -> respond with a 400 status and animate the form

My problem is that the Request, JQuery sends, seems not to be XHR.

Html:

<form id="logfo" action="{{path('Login_Ajax')}}" method="POST">
    <p> Name </p>
    <input type="text" id="logname"> </br>
    <p> Password </p>
    <input type="text" id="logpass"> </br>
    <input type="submit" value="Log In">
</form>

Javascript:

$(document).ready(function() {
    //listen for the form beeing submitted
    $("#logfo").submit(function(){
        var url = $("#logfo").attr("action");
        //start the post
        $.post(url,{Name:$("#logname").val(),
            Password:$("#logpass").val()}, 
            function(data){
                if(data.responseCode==400) {
                    //animate the Form
                    var fo=$("#logfo");
                    fo.animate({left:'+=25px'}, "fast");
                    fo.animate({left:'-=50px'}, "fast");
                    fo.animate({left:'+=50px'}, "fast");
                    fo.animate({left:'-=25px'}, "fast");
                }
        });
    }); 
});

routing.yml:

Login_Ajax:
pattern: /thefitthing/logjax
defaults: {_controller: FitcompTheFitThingBlogBundle:Ajax:login }
requirements:
    _method:  POST

For testing reasons, I replaced code for comparing the request with data
from the database with simple if-terms.
controller:

class AjaxController extends Controller {

    public function logInAction()
    {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) { 
            $name=$request->request->get('Name');
            if($name == "page") return new Response("",400);
            if($name == "plant") return $this->redirect($this->generateUrl('Thanks_Page'));
        }
        else return $this->render('FitcompTheFitThingBlogBundle:Blog:test.html.twig', array('hint' => "noXHR"));
    }
}
4

1 回答 1

4

您的submit处理程序不会阻止浏览器提交表单,因此您的 XHR 请求永远没有机会完成(浏览器只是先执行常规 POST)。您可以通过简单地删除您的呼叫来确认这一点$.post——行为完全没有区别。

通过阻止默认操作来解决此问题:

$("#logfo").submit(function(event) {
    event.preventDefault();
    $.post(...);
});
于 2013-02-28T21:45:21.877 回答