简体   繁体   中英

Display Json in search field in laravel or Php

I need to display searched value on search bar.

My controller code :

$q = Input::get('q');
  $query = Jobs::select('job_title')->Where('job_title', 'LIKE', '%'.$q.'%')->get();
  return response()->json($query);

My jquery axios code :

 $(document).ready(function(){
  $("#jobsearch").keyup(function(){
     url = "{{route('searchexistingjob')}}";
     var word = $("#jobsearch").val();
     const data = {
       'q' : word
     }
     axios.post(url,data).then(response =>{
        for(i=0; i<response.data.length; i++){
            // $('#jobsearch').val(response.data[i].value);           
     });
  });
});

HTML code

<input type="text" id="txtjobsearch" name="txtjobsearch" class="form-control" placeholder="Job title, designation, description..." autocomplete="off" data-id="1">

all the thing are correct only but i need how to display that value in search box any ideas?

If can you can change the response format

$q = Input::get('q');
$query = Jobs::select('job_title')->Where('job_title', 'LIKE', '%'.$q.'%')->get();
return response()->json([
    search_terms => $q,
    results => $query,
]);

Or as you are using ajax, you already have the search term:

So instead of:

$('#jobsearch').val(response.data[i].value);  

You will use:

$('#jobsearch').val(word);  

Or just remove the line and leave what is already typed.

You can do it in a few easy steps.

Make a route, with same link, controller and function, just use POST method. Wrap input field in the form, and when its submitted, let it go to the same page. Create the variable in that controller@function, let's say:

$result = "";

And pass that variable to the view. And in the view, set the value of that input to the $result;

If its not queried yet, that input will be clear($result = '';), otherwise, it will display result of that query.

// routes/web.php 
Route::get('/home', 'SearchBarController@index');
Route::post('/home', 'SearchBarController@index');

// app/Http/Controllers/SearchBarController.php
public function index()
{
    $result = '';
    if(request()->isMethod('post'))
    {
        $q = Input::get('textjobsearch');
        $query = Jobs::select('job_title')->where('job_title', 'LIKE', '%'.$q.'%')->get();
        $result = json_encode($query);
    }

    return view('searchbar.index', compact('result'));
}

// resources/views/searchbar/index.blade.php

<form method='post'>
    <input type="text" id="txtjobsearch" name="txtjobsearch" value="{{ $result }}" class="form-control" placeholder="Job title, designation, description..." autocomplete="off" data-id="1">
<input type='submit' />
</form>

That's it.

That simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM