dreamy1992 2015-02-26 06:41
浏览 30
已采纳

如何在xampp上使用laravel5发送ajax请求

routes.php

Route::get('/register',function(){
    $data = 'Register';
    return View::make('user.register');
});

Route::post('/register',function(){
    $inputData = Input::get('formData');
    parse_str($inputData, $formFields);  
    $userData = array(
      'name'      => $formFields['name'],
      'email'     =>  $formFields['email'],
      'password'  =>  $formFields['password'],
      'password_confirmation' =>  $formFields[ 'password_confirmation'],
    );
    $rules = array(
        'name'      =>  'required',
        'email'     =>  'required|email|unique:users',
        'password'  =>  'required|min:6|confirmed',
    );
    $validator = Validator::make($userData,$rules);
    if($validator->fails())
        return Response::json(array(
            'fail' => true,
            'errors' => $validator->getMessageBag()->toArray()
        ));
    else {
    //save password to show to user after registration
        $password = $userData['password'];
    //hash it now
        $userData['password'] =    Hash::make($userData['password']);
        unset($userData['password_confirmation']);
    //save to DB user details
      if(User::create($userData)) {  
          //return success  message
        return Response::json(array(
          'success' => true,
          'email' => $userData['email'],
          'password'    =>  $password
        ));
      }
  }
});

Register.blade.php

<html>
    <head>
        <link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
<script src="./jquery.js"></script>


    </head>
    <body>
{!!Form::open(['url'=>'register'],array('id'=>'regForm'))!!}  
    {!! Form::label('name', 'Name', array('class'=>'control-label')) !!}
    {!! Form::text('name', null, array('class'=>'form-control','placeholder'=>'Enter Name')) !!}
    <div id ="name_error"></div>
    {!! Form::label('email', 'Email', array('class'=>'control-label')) !!}
    {!! Form::text('email', null, array('class'=>'form-control','placeholder'=>'Enter Email')) !!}
    <div id ="email_error"></div>
    {!! Form::label('password', 'Password', array('class'=>'control-label')) !!}
    {!! Form::password('password', array('class'=>'form-control', 'placeholder'=>'Password')) !!}   
    <div id ="password_error"></div>
    {!! Form::label('password_confirmation', 'Confirm Password',array('class'=>'control-label')) !!}
    {!! Form::password('password_confirmation', array('class'=>'form-control','placeholder'=>'Confirm Password')) !!}
    {!! Form::submit('Register', array('class'=>'btn btn-warning btn-lg')) !!}
{!! Form::close() !!}
<div id="successMessage"></div>
<script>
$( "#regForm" ).submit(function( event ) {    
  event.preventDefault();
  var $form = $( this ),
    data = $form.serialize(),
    url = $form.attr( "action" );
  var posting = $.post( url, { formData: data } );
  posting.done(function( data ) {
    if(data.fail) {
      $.each(data.errors, function( index, value ) {
        var errorDiv = '#'+index+'_error';
        $(errorDiv).addClass('required');
        $(errorDiv).empty().append(value);
      });
      $('#successMessage').empty();          
    } 
    if(data.success) {
        $('.register').fadeOut(); //hiding Reg form
        var successContent = '<div class="message"><h3>Registration Completed Successfully</h3><h4>Please Login With the Following Details</h4><div class="userDetails"><p><span>Email:</span>'+data.email+'</p><p><span>Password:********</span></p></div></div>';
      $('#successMessage').html(successContent);
    } //success
  }); //done
});
</script>
        </div>
    </body>
</html>

So my problem is this I have installed the laravel on my xampp server . So i want to send a ajax request using post but whenever i send the the request it shows me 500 Internal Server Error and TokenMismatchException . I Have search everything on google and tried every single but still getting the same error . I am not able to understand from where the problem is coming , so please if any one can help me

  • 写回答

2条回答 默认 最新

  • dongxinm279890 2015-02-26 08:25
    关注

    Hmmmm,

    You problem actually was because CSRF and i test your code and i get the TokenMismatchException in VerifyCsrfToken.php line 45 error so to solve this problem you need to pass the CSRF _token with ajax request to solve this problem you need to add

    $_token = "{{ csrf_token() }}";
    

    var posting = $.post( url, { formData: data, _token: $_token } );

    and should you final javascript code look like this

    <script>
    $( "#regForm" ).submit(function( event ) {    
      event.preventDefault();
      var $form = $( this ),
        data = $form.serialize(),
        url = $form.attr( "action" );
    
        $_token = "{{ csrf_token() }}";
    
      var posting = $.post( url, { formData: data, _token: $_token  } );
      posting.done(function( data ) {
        if(data.fail) {
          $.each(data.errors, function( index, value ) {
            var errorDiv = '#'+index+'_error';
            $(errorDiv).addClass('required');
            $(errorDiv).empty().append(value);
          });
          $('#successMessage').empty();          
        } 
        if(data.success) {
            $('.register').fadeOut(); //hiding Reg form
            var successContent = '<div class="message"><h3>Registration Completed Successfully</h3><h4>Please Login With the Following Details</h4><div class="userDetails"><p><span>Email:</span>'+data.email+'</p><p><span>Password:********</span></p></div></div>';
          $('#successMessage').html(successContent);
        } //success
      }); //done
    });
    </script>
    

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况