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

如何在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条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动