user1493448 user1493448 - 1 month ago 6
Ajax Question

Laravel 5 AJAX post don't work

I am new in Laravel. I try to create a ajax post function on my project. But my following code don't work. When I click the button it does not response anything but I create the function as mention on the tutorial site. I search on google but don't get any suggestion or appropriate answer. Please, anyone help me solve this problem. Any suggestion will be appreciated. My English is not good. So please, don't mind. Thank you. ohh I forget to mention that I used Laravel 5.

View file: message.php



<html>
<head>
<title>Ajax Example</title>

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>

<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>

<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>

</html>

/* route file: */

Route::get('ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController@index');

/* controller file: AjaxController.php */

class AjaxController extends Controller {
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
}

Answer

Follow this Steps:

route.php

 Route::post('/getmsg','AjaxController@index');

AjaxController.php

class AjaxController extends Controller {
   public function index(){
      $msg = "This is a simple message.";
      return response()->json([
            'msg'=> $msg
          ], 200);
   }
}

Inside View

<html>
   <head>
      <title>Ajax Example</title>
      <meta name="_token" content="{{ csrf_token() }}" />  

      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
   </head>

   <body>
      <div id = 'msg'>This message will be replaced using Ajax. 
         Click the button to replace the message.</div>

      {{ Form::button('Replace Message',['onClick'=>'getMessage()']) }}

      <script>
         function getMessage(){
            var _token = $('meta[name="_token"]').attr('content');

            $.ajax({
               type:'POST',
               url:'/getmsg',
               data: {_token: _token},
               success:function(data){
                  $("#msg").html(data.msg);
               },
               error: function(data){
                    console.log(data);
               }
            });
         }
      </script>

   </body>

</html>

Hope this help's you