PlayHardGoPro
PlayHardGoPro

Reputation: 2933

Retrieve data from database using ajax with laravel

I'm able to select a value from database and throw it inside a <div>.
My problem is, I don't know how to do so and follow the MVC rules, as I'm using Laravel framework.

Here is what I've done so far:

Index.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="script.js"></script>
</head>
<body>
    <div id="wrapper">
        <input type="button" id="btn" value="Click Me :)"></input>
    </div>
</body>
</html>  

Ajax.php

<?php

include ('db.php');

$pdo = connect();

$dados = $pdo->prepare("SELECT field FROM table WHERE id = ?");
$dados->execute(array("2"));
$usr = $dados->fetch(PDO::FETCH_ASSOC);


echo "<p> Nome:" .$usr["nome"]. "</p>"; //Teste  

Script.js

$(document).ready(function(){
    $('#btn').click(function(){
        $.ajax({
        url: "ajax.php",
        type: "GET",
        dataType: "html", //expected return type        
        success: function(response){
            $('#calendario').fullCalendar(
            'renderEvent',
            {
                title: 'Novo evento',
                start: '2016-04-06T08:00:00', // I need to put the data here
                end:'2016-04-06T10:30:00'    // And here aswell
            }
        );
        }

    })

    });
});

I made this as a test, and it's working... How may I do the same using Laravel MVC ? Here I had to create a custom php file (ajax.php) only to make the select. Is there a way to do the same thing using my Controller /Model?

Upvotes: 1

Views: 5541

Answers (2)

Patrick Lewis
Patrick Lewis

Reputation: 83

Yes. What you would do is have the URL point to a route (URL) that you specify. You would specify the route in app/Http/routes.php like so:

    // Perform some action
    Route::get('/whatever/url/you/like', 'SomeController@someAction');

This will look for a "GET" method call, which means you can test it from the browser as well. The first parameter is the URL you want to use, while the second parameter is a Controller, the @ sign, then the public function you want called.

In the controller class you create, you would return an array with the data you want returned. Laravel automatically converts that array into JSON for your consumption by default.

If you're asking about how to go about separating the code (what should be in the controller and what should be in the model), then you can use the artisan command at the command line to have Laravel automatically create a blank controller class for you with public functions for common actions on an object:

php artisan make:controller PhotoController

More info can be found in Laravel's documentation. If you limit the code in the controller to actions done on an object created using the Model class, that will go a long way in getting you started. Hope this helps!

If entering the URL for the AJAX call in your browser returns some JSON, then you're on the right track. From the JavaScript making the call, the "response" variable should contain that data. If you need analyze it, use Chrome DevTools and add a checkpoint so that you can analyze exactly is returned in that variable. Another alternative is to use console.log to print that data to the browser's console.

Upvotes: 2

Achraf Khouadja
Achraf Khouadja

Reputation: 6279

Controller

public function testajax($id) {

$test = table::findorfail($id)->toarray();
return response()->json($test);
}

javascript

$(document).ready(function()
                      {
                       $(document).on('submit', '#reg-form', function()
                       {

                      var data = $(this).find("#post_id").val();
                        $.ajax({
                        type : 'GET',
                        url  : {{url("/ajax")}}',
                       data: data,
                       success: function(data) {
                          console.log(data);
                      },
                            error :  function(data)
                            {
                                alert("error");
                            }
                        });
                        return false;
                       });
                      });

routes file

Route::get('/ajax/{id}', 'Contoller@testajax');

this code dosent realy work but this is how its done

Upvotes: 1

Related Questions