Murlidhar Fichadia
Murlidhar Fichadia

Reputation: 2609

Select onChange Ajax get list of data from mysql database Laravel 5.4

I have 2 select input fields.

first select input field contains static data.

second select input field needs to be populated depending on first input field selected value.

Below is my code

<select id="filter_type" name="filter_type" class="selectpicker form-control" style="width:30%;">
           <option value>Select Filter Type..</option>
           <option value="abc">Abc</option>
           <option value="def">Def</option>
           <option value="ghi">Ghi</option>
           <option value="jkl">Jkl</option>
</select>

<select id="search" name="search" class="selectpicker form-control" style="width:70%;" disabled="disabled">
       <option value>Select Filter type first..</option>
</select>

Javascript

<script type="text/javascript">
$(document).ready(function()
{
$("#filter_type").change(function()
{
var id=$(this).val();
console.log(id);
var dataString = 'id='+ id;
console.log(dataString);
$.ajax
({
type: "GET",
url: "{{url('/users/abc')}}",
data: dataString,
cache: false,
success: function(data)
{
  console.log(data); // I get error and success function does not execute
} 
});

});

});
</script>

Controller

public function get_onchange_data(Request $request)
{
        if($id == 'abc')
        {
            $searches = Abc::select('field_name')->get();
            return response(view('/users/Def', compact('searches'))->render());
        }
}

I am unable to get returned ajax data.

I get this error:

GET http://localhost:8000/users/abc?id=year&_=1496176229318 500 (Internal Server Error)

I think my check in if condition is wrong. I am considering $id as the value passed from dataString.

I don't know how to do this. Get the data, compare it with if condition and finally return array result of the data.

Edited code

$("#filter_type").change(function()
{
var id=$(this).val();
console.log("1:"+id);
var dataString = '{id:'+ id+'}';
console.log("2:"+dataString);
$.ajax
({
type: "GET",
url: "{{url('/users/abc')}}",
data: dataString,
cache: false,
success: function(data)
{
  console.log("3:"+data);
} 
});

});

public function get_search_data(Request $request)
{
    return response($request->input('id'));
    }

Upvotes: 0

Views: 10661

Answers (1)

Bernd Strehl
Bernd Strehl

Reputation: 2920

Two/Three issues here:

  1. You haven't defined $id in the context of your method. Access it via your request object $request->input('id');
  2. Don't send your data as a string, send it as an object data: {id: id}
  3. Always return a response. If the statement evaluates to false, the request will not be answered.

Upvotes: 1

Related Questions