How to retrieve data using ajax and without going to post page? Laravel 5

I’m new to using ajax. For example after field title is filled, I want to search in database for specific data and return more fields based on that input. So far I can only receive my title data in /ajax/post page by pressing get data/post data or submit button. How do I receive my title input and data from Route::post while/after filling title? If I remove Form::model and Form::close() I do get my dummy data from Route::post without page refresh by clicking Post data button, but without title value.

I’m aware that checking title field involves some jQuery/js, but I have no idea how to actually bring that title field into my route to do some database searching and return some data with it.

View:

            {!! Form::model($project = new AppProject, ['url' => 'ajax/post', 'method' => 'post']) !!}
            <!-- pass through the CSRF (cross-site request forgery) token -->
            <meta name="csrf-token" content="<?php echo csrf_token() ?>" />

            <!-- some test buttons -->
            <button id="get">Get data</button>
            <button id="post">Post data</button>

            <div class="form-group padding-top-10">
              {!! Form::label('title', 'Title') !!}
              {!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title']) !!}
            </div>
            {!! Form::submit('Submit Button', ['class' => 'btn btn-primary form-control']) !!}
            {!! Form::close() !!}

Ajax script:
<script>
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
    function onGetClick(event)
    {
        // we're not passing any data with the get route, though you can if you want
        $.get('/ajax/get', onSuccess);
    }
    function onPostClick(event)
    {
        // we're passing data with the post route, as this is more normal
        $.post('/ajax/post', {payload:'hello'}, onSuccess);
    }
    function onSuccess(data, status, xhr)
    {
        console.log(data, status, xhr);
        // JSON is deserialised into an object
        console.log(String(data.value).toUpperCase())
    }
    $('button#get').on('click', onGetClick);
    $('button#post').on('click', onPostClick);
</script>

And in route:
    Route::get('/ajax/view', ['as' => 'home', 'uses' => '<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6a78c879ea589889294898a8a8394a6908f8391">[email protected]</a>']);
    Route::get('/ajax/get', function () {
        $data   = array('value' => 'some get');
        return  Response::json($data);
    });
    Route::post('/ajax/post', function () {
        $data   = array('value' => 'some data', 'input' => Request::input());
        return  Response::json($data);
    });

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

What you need is to implement the jquery keypress function.

so here is you js:

$("input.title").keypress(function(){
    var title = $(this).val();

    // now do the ajax request and send in the title value
    $.get({
        url: 'url you want to send the request to',
        data: {"title": title}, 
        success: function(response){
           // here you can grab the response which would probably be 
           // the extra fields you want to generate and display it
        }
    });
});

as far as in Laravel you can pretty much treat it the same as a typical request except you will return json:
Route::get('/url-to-handle-request', function({
    // lets say what you need to populate is 
   //authors from the title and return them

   $title = Route::get('title'); // we are getting the value we passed in the ajax request

    $authors = Author::where('title' ,'=', $title)->get();

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

Now I would probably use a controller and not just do everything within the route but I think you’ll get the basic idea.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x