Skip to content
Advertisement

Get Id From AJAX Response And Use The Id For Select2

I write HTML code in controller

public function edit($id)
{
    $user = User::find($id);
    $rolesForEdit = Role::pluck('name', 'name')->all();
    $userRole = $user->roles->pluck('name', 'name')->all();

    $html = '<div class="row">
     <div class="col-md-6">
        <label for="name">Name</label>
        <input value="' . $user->name . '" class="form-control"
            placeholder="Full Name" type="text" name="name" id="name" />
        <br>
        <label for="phone">Phone Number</label>
        <input value="' . $user->phone . '" class="form-control"
            placeholder="Phone Number" type="text" name="phone" id="phone" />
        <br>
    </div>
    <div class="col-md-6">
        <label for="roles">Role</label><br>
        <select style="width:220px;" name="rolesForEdit[]" multiple id="rolesForEdit"
            class="rolesForEdit form-control"></select>
        <br>
    </div> <!-- kanan -->
</div> <!-- row-->';

    return response()->json(['html' => $html]);
}

And then in view, I am trying to get rolesForEdit id and use it for select2. It doesn’t work with this way. Any solution?

$.ajax({
            url: "user/" + id + "/edit",
            method: 'GET',
            success: function(data) {
                //var roles = $($.parseHTML(data)).find("#rolesForEdit").html();
                //var roles = $(data).find('#rolesForEdit').text();
                //var roles = $(this).attr('rolesForEdit');
                //var roles = $($.parseHTML(data)).filter("#rolesForEdit");

                alert(roles);

                $(roles).select2({
                    ajax: {
                        url: '{{ url('searchrole') }}',
                        processResults: function(data) {
                            return {
                                results: data.map(function(item) {
                                    return {
                                        id: item.id,
                                        text: item.name
                                    }
                                })
                            }
                        }
                    }
                });
                $('#dataUserElement').html(data.html);
                $('#saveBtn').val("create-product");
                $('#user_id').val('');
                $('#productForm').trigger("reset");
                $('#modelHeading').html("Update User");
                $('#ajaxModel').modal('show');
            }
        });
    });

Advertisement

Answer

Your server return json as response so add dataType: 'json' to your ajax call. Then , append data return to your dataUserElement i.e : data.html and finally intialize your select2 .

Demo Code :

//suppose data is this :)
var data = {
  'html': '<div class="row"><div class="col-md-6"> <label for="name">Name</label><input value="abc" class="form-control" placeholder="Full Name" type="text" name="name" id="name" /><br><label for="phone">Phone Number</label><input value="12346" class="form-control" placeholder="Phone Number" type="text" name="phone" id="phone" /><br></div><div class="col-md-6"><label for="roles">Role</label><br><select style="width:220px;" name="rolesForEdit[]" multiple id="rolesForEdit" class="rolesForEdit form-control"></select><br></div></div>'
}

/*$.ajax({
url: "user/" + id + "/edit",
method: 'GET',
dataType:'json',//add this 
success: function(data) {*/
$('#dataUserElement').html(data.html); //then append this 
var roles = $('#dataUserElement').find(".rolesForEdit") //get select refernce
$(roles).select2({
  ajax: {
    url: "https://api.github.com/orgs/select2/repos", //this is for demo change it to your real url
    processResults: function(data) {
      return {
        results: data.map(function(item) {
          return {
            id: item.id,
            text: item.name
          }
        })
      }
    }
  }
});
//all other codes modal ..etc etc
/*}
});*/
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>

<div id="dataUserElement">
</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement