DeiForm
DeiForm

Reputation: 664

Laravel select2 no results found

recently I run into problem with integration select2 with laravel.

I want to call ajax request to filter users but I get No results found.

I created test files in my localhost:

<html>
<head>
<script   src="https://code.jquery.com/jquery-3.3.1.min.js"   integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="   crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body>

<select class="js-data-example-ajax"></select>

<script>

$('.js-data-example-ajax').select2({
  ajax: {
    url: 'ajax.php',
    dataType: 'json'
    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
  }
});
</script>

Ajax.php

<?php echo "{
  \"results\": [
    {
      \"id\": 1,
      \"text\": \"Option 1\"
    },
    {
      \"id\": 2,
      \"text\": \"Option 2\"
    }
  ]
}";

This is running ok but when I use the same script in my laravel blade template I get Nore sult found:

index.blade.php (Note: I have jquery and select2 loaded in head section)

<select class="js-data-example-ajax"></select>

<script>

    $('.js-data-example-ajax').select2({
        ajax: {
            url: 'http://localhost/ajax.php',
            dataType: 'json'
            // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
        }
    });
</script>

Upvotes: 0

Views: 844

Answers (1)

aa-Ahmed-aa
aa-Ahmed-aa

Reputation: 382

if you want to just run your example in the laravel project you should move the Ajax.php file to your public folder. and if you want your list to be dynamic not just a static json content you should make a route for function that will generate the select2 elements

web.php

Route::get('select2list', 'TestController@select2list');

TestController.php

public function select2list()
{
    //generate your list in the way you want
    $temp = '{
      "results": [
           {
              "id": 1,
              "text": "Option 1"
           },
           {
              "id": 2,
              "text": "Option 2"
           }
         ]
        }';
    die(json_decode( $temp ));
}

and to load this list in your view you should make this ajax request like this

var mySelect2Elements;
$.ajax({
    url: "/select2list",
    dataType: 'json',
    type: "GET",
    success: function (data) {

         alert( data );
         mySelect2Elements = data;

    }
}).done(function() {
    $('.js-data-example-ajax').select2(
       { data: mySelect2Elements}
    );
});

Upvotes: 2

Related Questions