mardi 30 mai 2017

How to return views upon Ajax requests in Laravel

Let me start off by saying I am a moderate at Laravel/JQuery so please bear with my question.

I would like to return a view when the user clicks a button, using ajax. Whenever I click the button, I receive no error but also do not get any html. Any help is appreciated.

I defined my routes web.php as:

Route::get('ajax', function() {
    return view('test');
});

Route::post('/getmsg', function() {
     $msg = "<strong>This is a simple message.</strong>";
     $returnHTML=view('form1_sections/section2_form')->render();
     return response()->json(array('html'=>$returnHTML, 'msg'=>$msg));
});

My test.blade.php looks like:

<html>
<head>
    <meta name="csrf-token" content="">
    <title>Ajax Example</title>

    <script src = "http://ift.tt/1yCEpkO">
    </script>

    <script>
        function getMessage() {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $.ajax({
                type: 'POST',
                url: '/getmsg',
                data: '_token = <?php echo csrf_token() ?>',
                success: function (data) {

                    $("#msg").html(data);
                }
            });
        }
    </script>
</head>

<body>
    <div id = 'msg'>This message will be replaced using Ajax. 
        Click the button to replace the message.</div>
    <form>
        <button onclick="getMessage()">Replace Message</button>
    </form>
</body>

My section2_form view looks like:

<div class="well">
<div class="row">
    <div class="col-xs-12">

        <h4>Date of Previous Research Leave</h4>
        <br>
        <label>Start Date:</label>
        <label>
            <input class="form-control" name="startDate" id="startDate" placeholder="Start Date" type="date">
        </label>
        <br><br>
        <label>End Date:</label>
        <label>
            <input class="form-control" name="endDate" id="endDate" placeholder="End Date" type="date">
        </label>
    </div>
</div>



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire