Ramzan Mahmood
Ramzan Mahmood

Reputation: 1901

Get variable in jquery method and use it in view (laravel 5.3)

I am using jquery to get data from controller from controller i am returning a $user from controller method but don't know how to use it in view.

Here is my Code..

    <li>
<a href="#suppression" data-toggle="modal" onclick="getForm('{{ $data->id }}')"> Get Modal</a>
</li>

and my jquery method is

function getForm(id)
{
    $.ajax({
        url: '/student-forms/get-form/'+id,
        type: "GET",
    });
}

Controller method is

public function getForm($id)
{

    $user = DB::table('users')->select('name','type','options')->whereIn('id' , $id)->get();
    return $user;

}

I want to get above variable $user here in my model

<div id="suppression" class="modal" role="dialog" aria-hidden="true">
<div class="modal-dialog" style="width: 500px;">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        </div>
        <div class="modal-body">

        </div>
    </div>
</div>

Please help how can i achieve using above jquery method Thanks

Upvotes: 1

Views: 1244

Answers (3)

madalinivascu
madalinivascu

Reputation: 32354

Change your ajax to append the data to the page when the ajax is executed successfully

function getForm(id)
{
    $.ajax({
        url: '/student-forms/get-form/'+id,
        type: "GET",
        success:function(data) {
          $('modal-body').append(data.name);
        }
    });
}

Remove the onclick event , add a attribute to the link to store the id

<a href="#suppression" data-toggle="modal" data-id="{{ $data->id }}"> Get Modal</a>

trigger the ajax when the modal is shown

$('#suppression').on('show.bs.modal', function (e) {
  var id = $(e.relatedTarget).attr('data-id');
  getForm(id);
})

Controller should return json

public function getForm($id)
{

    $user = DB::table('users')->select('name','type','options')->whereIn('id' , $id)->get();
    return response()->json($user);

}

Upvotes: 1

Koray K&#252;pe
Koray K&#252;pe

Reputation: 736

If you use jQuery you can use this code:

function getForm(id)
{
    $.ajax({
        url: '/student-forms/get-form/'+id,
        type: "GET",
    }).done(function(msg) {
        $(".modal-body").val(msg);
    });
}

It will add returned value in your modal-body div. Since Laravel returns collection you will need format your user data.

e.g

.val('name:' + msg.name);

By the way don't forget to add crsf token field to your forms.

Upvotes: 0

Joe
Joe

Reputation: 4738

As you're using jQuery you'll need to also use it to edit the dom.

$.ajax({
    url: '/student-forms/get-form/'+id,
    type: "GET",
    success: function(response){
        $('#elementToChange').text(response.thingfromyourusermodel)
    }
});

Upvotes: 0

Related Questions