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

时间:2015-02-26 06:41:09

标签: php ajax laravel

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>

所以我的问题是我在xampp服务器上安装了laravel。所以我想使用post发送ajax请求,但每当我发送请求时,它都会显示 500内部服务器错误 TokenMismatchException 。我已经在谷歌上搜索了所有内容并尝试了每一个但仍然得到相同的错误。我无法理解问题出在哪里,所以如果有人可以帮助我,

2 个答案:

答案 0 :(得分:0)

您忘了将url操作添加到Form :: open

更改此行

{!!Form::open(array('id'=>'regForm','method'=>'get'))!!} 

 {!!Form::open(array('id'=>'regForm','action' => 'register','method'=>'get'))!!} 

答案 1 :(得分:0)

Hmmmm,

你问题实际上是因为CSRF和我测试你的代码并且我在VerifyCsrfToken.php第45行出现了TokenMismatchException错误所以为了解决这个问题你需要传递带有ajax请求的CSRF _token来解决这个问题你需要添加< / p>

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

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

你最后的javascript代码应该是这样吗?

<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>

<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>