Using AJAX in Laravel to interact with the database

I am studying the Laravel PHP structure based on the Model, View, Controller paradigm. I'm stuck trying to incorporate AJAX into my simple starter app ... phonecall registrar. Here I usually give up. But I refuse!

So I have a Phonecall model:

class Phonecall extends Eloquent { // Creates an instance of the database object } 

Here is my phonecalls table:

 mysql> desc phonecalls; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | who | varchar(200) | NO | | NULL | | | what | varchar(200) | NO | | NULL | | | created_at | datetime | NO | | NULL | | | updated_at | datetime | NO | | NULL | | | initiator | varchar(200) | NO | | NULL | | | info | text | NO | | NULL | | +------------+------------------+------+-----+---------+----------------+ 7 rows in set (0.00 sec) 

My view lists all the calls (by whom and by whom) currently in the database:

 <!doctype html> <html> <head> <title>Title</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"> </script> </head> <body> <h1>Welcome</h1> <p>Here a list of recent phonecalls</p> <ul class="call-list"> @foreach($phonecalls as $call) <li>{{ $call->who }} - {{ $call->what }} - <a href="phonecalls/show/{{ $call->id }}">Show</a> | {{ HTML::link('phonecalls/delete/'.$call->id, 'Delete') }} | {{ HTML::link('phonecalls/update/'.$call->id, 'Update') }} </li> </ul> {{-- Placeholder for AJAX content --}} <div id="call-info"> </div> </body> </html> 

Here is my simple controller:

  class Phonecalls_Controller extends Base_Controller { // Use $this within a method the same way you // would use the object name outside of the class public function get_index() { $phonecalls = Phonecall::all(); return View::make('phonecalls.index')->with('phonecalls', $phonecalls); } // ************************************ // DISPLAY CALL INFO public function get_show($call_id) { $call = Phonecall::find($call_id); // WHAT GOES HERE? } 

I want the user to be able to click "Show" in the view and have the call information display within ...

 <div id="call-info"> </div> 

in view.


UPDATE:

Here is what he did ...

My get_show () method

 // ************************************ // SHOW CALL INFO public function get_show($call_id) { $call = Phonecall::find($call_id); return $call->info; } 

My javascript

 //************************************ // Phonecall AJAX Example //************************************ $(document).ready(function() { $('.call-list > li > a').click(function(e) { // e=event e.preventDefault(); var id = $(this).attr('id'); $.get(BASE+'/phonecalls/show/'+id, function(data) { $("#call-info").html(data); }) }); 
+6
source share
3 answers

This can be done in many ways.

You can do this first:

 public function get_show($call_id) { $call = Phonecall::find($call_id); return View::make('phonecalls.single')->with('phonecal', $call); } 

In this case, you need to create a template for one phonecall and place it in the folder with your music libraries.

Another option is to return a JSON response from the Laravel application:

 public function get_show($call_id) { $call = Phonecall::find($call_id)->first(); return Response::eloquent($call); } 

Another option is to use the javascript MVC framework to make things like fetching / updating AJAX data very simple, like Backbone JS or Angular JS can do this.

In any case, if you want to make AJAX data, you need to create an API to separate between the regular site and the AJAX data backend.

Here is my blog post with details on how to do this: http://maxoffsky.com/code-blog/building-restful-api-in-laravel-start-here/

Also, a great introduction to AJAX in Laravel is Code Happy by Dayle Rees, AJAX chapter: codehappy.daylerees.com/ajax-content

Let me know if you have more questions and approve this comment if you feel you have helped. Thanks!

UPDATE:

To actually download files from the controller (or the Laravel route), you need to use jQuery ajax, GET (to load data) or POST (to send form results) Here is an example:

  $('#get-info').click(function(e) { // e=event e.preventDefault(); var BASE = "<?php echo URL::base(); ?>"; // attempt to GET the new content $.get(BASE+'phonecalls/show/2', function(data) { $('#content').html(data); }); 
+4
source

it took me a while to understand how the examples in webz are confusing, referring to the change in headers to account for the csrf token, etc. Here is an example, and I hope this helps someone else.

First: the form that appears in your view:

 {{ Form::open(['id' => 'testForm']) }} <p>{{ Form::label('title', 'Title') }} {{ Form::text('title') }}</p> <p>{{ Form::label('description', 'Description') }} {{ Form::text('description') }}</p> <p>{{ Form::submit('Submit') }}</p> {{ Form::close() }} 

Secondly: write your route in route.php :

 Route::post('ad', ' AdController@store '); 

Third: controller:

 public function store() { if(Request::ajax()){ $ad = new ad; $ad -> title = Input::get('title'); $ad -> description = Input::get('description'); $ad -> save(); $response = array( 'status' => 'success', 'msg' => 'Option created successfully', ); return Response::json( $response ); } } 

Fourth: jQuery ajax request:

 $('form#testForm').submit(function(e){ e. preventDefault(); var str1 = $('input[name="title"]').val(); var str2 = $('input[name="description"]').val(); var str3 = $('input[name="_token"]').val(); var data = {title:str1,description:str2, token:str3}; //console.log(data); var request = $.ajax({ url: "ad", type: "POST", data: data , dataType: "html" }); request.done(function( msg ) { var response = JSON.parse(msg); console.log(response.msg); }); request.fail(function( jqXHR, textStatus ) { console.log( "Request failed: " + textStatus ); }); }); 

This. For protection, you can set Session::token() == Input::get('_token') in the controller as an if check. This is just an example that works great for you to get started. The use of an absolute URL may be required (in this case, use http://www.pretty.url/ad ) were www.pretty.url - your localhost or local private development URL.

+5
source

You can intercept clicks on the Show link. If you create your restful controller, it will be easy for you to make an ajax request to your controller.

You must send an ajax request when the user clicks in the Show link.

I suggest you output the results as JSON, so it’s pretty easy to use js to output your results.

0
source

All Articles