jlrdw's avatar
Level 75

Jquery get response

Some folks when first learning ajax has questions on getting an ajax response. This example uses jquery. Adapt if using a newer version.

This is just a quick simplified example.

Normally you would have a layout file (template), but for the example I just used a single page.

So this

<script type="text/javascript" src="<?php echo asset('assets/js/jquery.js'); ?>"></script>

Would be in the layout file or where ever you load your jquery. But just for a demo, I only have a single file, but it works the same.

Here is a file called testjq.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>test</title>
        <link href="<?php echo asset('assets/css/dog/style.css'); ?>" rel="stylesheet">
        <script type="text/javascript" src="<?php echo asset('assets/js/jquery.js'); ?>"></script>

    </head>
    <body>
        <a href="" Id="testme">testme</a>
        <br>
        <br>
        <br>
        <input type="text" name="dogname" id="dogname" size="100">
        <input type="text" name="comment" id="comment" size="100">
    </body>
</html>
<script>

    $(function () {
        $("#testme").click(function (event)
        {
            event.preventDefault();

            var somevar = '1';
            $.ajax({
                url: 'testc',
                type: 'GET',
                data: 'somevar=' + somevar,
                dataType: 'json',
                success: function (data) {
                    if (data.error) {
                        //handle the error here
                    } else {
                        alert(data.dogname);
                        $('#dogname').val(data.dogname);
                        $('#comment').val(data.comments);
                    }
                }
            });

        });


    });



</script>


See this image https://imgur.com/4Gq7lJd

The objective is after clicking testme a dog with a dogid of 1 (one) will be retrieved from the database and the dog's name and comments about that dog will be placed in the text boxes.

This is achieved with these two lines from the jquery script:

    $('#dogname').val(data.dogname);
    $('#comment').val(data.comments);

I like using the facade shortcuts, so at the top of controller I have:

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
// other use statements as requird

And the controller method

    public function testc() {
        $dogid = Request::input('somevar');
        $dog = DB::table('dc_dogs')
                ->where('dogid', '=', $dogid)
                ->first();
        $data = [
            'dogname' => $dog->dogname,
            'comments' => $dog->comments
        ];
        return Response::json($data);
    }

And a very short video showing it in action:

https://drive.google.com/file/d/1Vgcz2QubqZPu73WR975iJ27uyzwR8vjR/view?usp=sharing

Regular laptop or desktop with full screen shows better.

I don't use blade myself, so just change as needed to blade.

See reply one for more examples

and an eloquent simple example

0 likes
2 replies
jlrdw's avatar
Level 75

Oh I just used very simple routes for the example:

Route::get('testjq', 'DogController@testjq');
Route::get('testc', 'DogController@testc');

Also to convert an object to array for the response, this works:

    public function testc() {
        $dogid = Request::input('somevar');
        $dog = DB::table('dc_dogs')
                ->where('dogid', '=', $dogid)
                ->first();
        
        $dogarray = (array)$dog;
       return Response::json($dogarray);
    }

I found this tip in a stackoverflow post about 8th answer down: https://stackoverflow.com/questions/19495068/convert-stdclass-object-to-array-in-php

An alternative solution:

For a simple ajax response, you can just get an array by setting:

$sth->fetch(\PDO::FETCH_ASSOC);

So here is how that looks:

    public function testc() {
        $dogid = Request::input('somevar');
        $sql = "SELECT * FROM dc_dogs WHERE dogid = :dogid";
        $params = ['dogid' => $dogid];
        $sth = DB::getPdo()->prepare($sql);
        $sth->execute($params);
        $dog = $sth->fetch(\PDO::FETCH_ASSOC);
        return Response::json($dog);
    }

For some simple responses this solution works great.

A quick eloquent solution

Here returning more than one row, but just quick example:

Controller:

    public function testg() {
        $dogid = Request::input('somevar');
        $dog = Dog::select('dogname', 'comments')
                ->where('dogid', '<', $dogid)
                ->get()
                ->toArray();
        return Response::json($dog);
    }

Jquery script

<script>

    $(function () {

        $("#testme").click(function (event)
        {
            event.preventDefault();
            var somevar = '3'; // Usually a variable generated by you
                                  // for demo hard coded
            $.ajax({
                url: 'testg',
                type: 'GET',
                data: 'somevar=' + somevar,
                dataType: 'json',
                success: function (data) {
                    $.each(data, function (index, item) {
                        alert(item.dogname);
                         // loop and do whatever with data
                    });
                },
                error: function (err) {
                    alert(err);
                }
            });

        });


    });

</script>

Notice the

->toArray();

That is needed for a json response.

Later I will post an Ajax post request example.

3 likes
bernardkortor's avatar

thank you for your effort, sir. the event I'm using select not click event don't know whether this one correct $("#hospitalno").change(function (event) I want to select from the dropdown and auto-fill two text fields eg first_name, last_name

Please or to participate in this conversation.