2016-01-19 1 views
0

Эта проблема отлично работает при вызове ajax из PHP, но я не могу заставить ее работать с Laravel 5.2. Все, что я пытаюсь сделать, это отправить электронное письмо с помощью AJAX при отправке формы.Ajax вызов возвращает CSRF-токен при успешном завершении и не возвращает сообщения

Это мой routes.php запись для отправки электронной почты:

Route::post('/send', '[email protected]'); 

И это мой layout.blade.php файл:

<head> 
    <meta name="csrf-token" content="{{ csrf_token() }}" /> 
</head> 

$(document).ready(function() { 
    $.ajaxSetup({ 
     headers: { 
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
     } 
    }); 

    ... 

    $("#send").button().click(function(event) { 
     var form  = $("#contact-form"), 
      postAction = form.attr('action'), 
      isValid = form.valid(), 
      valSum  = $(".validation-summary"); 

     if (isValid) { 
      var postData = { 
       message_type: "contact" 
       ,first_name: first_name.val() 
       ,last_name: last_name.val() 
       ,email: email.val() 
       ,message: message.val() 
      }; 

      // process the form 
      $.ajax({ 
       type: "POST", 
       // our data object 
       url: postAction,  // the url where we want to POST 
       data: postData 
      }) 
      // using the done promise callback 
      .done(function(data) { 
       // log data to the console so we can see 
       console.log(data); 
       // here we will handle errors and validation messages 
       if (! data.success) { 
        valSum.removeClass("success"); 
        valSum.addClass("validation-summary error"); 
        valSum.html(data); 
       } else { 
        // $(".validation-summary").html("Message sent."); 
        valSum.html(data.message); 
       } 
      }) 
      // using the fail promise callback 
      .fail(function(data) { 
       // show any errors 
       // best to remove for production 
       console.log(data); 

       valSum.removeClass("success"); 
       valSum.addClass("validation-summary error"); 
       valSum.html("Server Error: " + data.statusText + " processing your request, please contact Dorothea or report a bug."); 
      }); 
      // stop the form from submitting the normal way and refreshing the page 
      event.preventDefault(); 
     } else { 
      return false; 
     } 
    }); 

И, наконец, вот мой CommsControllersend() функция:

public function send(Request $request) { 
    //check if its our form 
    if (Session::token() !== Request::get('csrf-token')) { 
     return Response::json(array(
      'message' => 'Unauthorized attempt to create setting' 
     )); 
    } 

    $message_type = strval(Request::input('message_type')); 
    $first_name = strval(Request::input('first_name')); 
    $last_name = strval(Request::input('last_name')); 
    $email = strval(Request::input('email')); 
    $message = strval(Request::input('message')); 

    $to = "[email protected]"; 

    // subject 
    $subject = "Dorothea - Contact Us"; 

    Mail::send('email.contact', ['request' => Request::all()], function ($message) use ($request) { 
     $message->from($this->email, $this->email); 
     $message->to($user->email, $user->email)->subject($subject); 
    }); 

    $response = array(
     'status' => 'success', 
     'message' => 'Message sent.', 
    ); 

    return Response::json($response); 
} 

Это вопрос связан с тем, который я опубликовал here, но вместо получения MethodNotAllowedHttpException все, что было возвращено сейчас из вызова AJAX, это значение CSRF-токена.

ответ

0

Заменить .done callback с .success, чтобы получить данные о возврате.

.success(function(data) { 
    if (data.status != 'success') { 
     valSum.removeClass("success"); 
     valSum.addClass("validation-summary error"); 
    } 

    // eventually, print out the return message 
    valSum.html(data.message); 
}) 
+0

@ In9187 обратитесь пожалуйста [здесь] (http://stackoverflow.com/questions/10931836/should-i-use-done-and-fail-for-new-jquery-ajax-code-instead-of-success -and), почему я использую '.done' вместо' .success'. –

0

Просто хотел, чтобы все, что пытался помочь мне знать, что отправка писем отлично работает в Laravel, если я поменяю запрос пост на запрос GET.

Не слишком уверен, почему это так, поэтому, если кто-то может пролить свет на то, почему это было бы так, что было бы здорово.

Смежные вопросы