Laravel - Ajax and HTTP
This article will continue where we left off in Part 5 of the Laravel tutorial series. Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Laravel was created by Taylor Otwell.
In this article, we will have a look at how to send emails, handle Ajax and how to handle errors & events in the framework which is an important skill to gain in being a PHP developer. So, let’s dive straight into the code.
Sending Emails : SwiftMailer
Laravel is full of features library to send emails, SwiftMailer. Using this library, emails can be sent without using too much configuration and it guarantees reliability.
The best thing about this library is that we can use the same Blade syntax we use in designing our Laravel views. The following is some information about how to send an email:
void send(string|array $view, array $data, Closure|string $callback)
Let’s look at each parameter separately:
- $view(string|array) – name of the view that contains the email message
- $data(array) – array of data to pass to view
- $callback – a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message
In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below.
- $message->subject('Hello, from DiscoverSDK');
- $message->from('shubham@discoversdk.com', 'Mr.Shubham');
- $message->to('liran@discoversdk.com', 'Mr.Liran');
Some of the less common methods include −
- $message->sender('shubham@discoversdk.com', 'Mr.Shubham');
- $message->returnPath('liran@discoversdk.com', 'Mr.Liran');
- $message->cc('shubham@discoversdk.com', 'Mr.Shubham');
- $message->bcc('liran@discoversdk.com', 'Mr.Liran');
- $message->replyTo('shubham@discoversdk.com', 'Mr.Shubham');
- $message->priority(2);
To attach or embed files, you can use the following methods −
- $message->attach('path/to/attachment.txt');
- $message->embed('path/to/attachment.jpg');
Mail can be sent as HTML or text. We can indicate the type of mail that we want to send in the first argument by passing an array as shown below. The default type is HTML. If we want to send plain text mail then we will use the following syntax.
Mail::send(['text'=>'text.view'], $data, $callback);
In this syntax, the first argument takes an array. Use “text” as the key “name of the view” as value of the key.
Ajax Handling
Ajax (Asynchronous JavaScript and XML) is a set of web development mechanisms utilizing many web technologies used on the client-side to create asynchronous requests.
In Ajax, we send requests using Javascript and get a response on response() method. In that method, we can update HTML DOM elements in the response method. Let’s dive into the code to show an AJAX request:
<html>
<head>
<title>Ajax Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/discoverMe,
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
As told earlier, let’s create a Controller using the following artisan command:
php artisan make:controller MyAjaxController --plain
Put the below code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class MyAjaxController extends Controller {
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
}
Modify the routes.php file:
Route::get('ajax',function(){
return view('message');
});
Route::post('/getmsg','MyAjaxController@index');
Visit the following URL to test the Ajax functionality: http://localhost:8000/ajax
We will see an AJAX page.
Error Handling
In Laravel, errors are handled in app\Exceptions\Handler class, contains two methods : report and render.
report() method
The report() method can be used to report or log exception. It is also used to send log exceptions to external services like Sentry, Bugsnag etc.
render() method
The render() method is used to render an exception into an HTTP response which will be sent back to browser.
Beside these two methods, the app\Exceptions\Handler class contains an important property called $dontReport. This property takes an array of exception types that will not be logged.
HTTP Exceptions
Some exceptions describe HTTP error codes like 404, 500 etc. To generate such responses anywhere in an application, we can use the abort() method as follows.
abort(404)
Custom Error pages
Laravel makes it very simple to use the custom error pages for each separate error code. For example, if we want a custom page for error code 404, we can create a view at resources/views/errors/404.blade.php. Similarly, if we want to design an error page for error code 500, it should be stored at resources/views/errors/500.blade.php.
Example
Let’s add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('/error',function(){
abort(404);
});
Now, create a view file called resources/views/errors/404.blade.php and copy the following code in that file.
resources/views/errors/404.blade.php
<!DOCTYPE html>
<html>
<head>
<title>404</title>
<link href = "https://fonts.googleapis.com/css?family=Lato:100" rel = "stylesheet"
type = "text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div class = "container">
<div class = "content">
<div class = "title">404 Error</div>
</div>
</div>
</body>
</html>
Finally, let’s visit the following URL to test the event : http://localhost:8000/error
We will see a custom error page.
Event Handling
An event is an action or occurrence recognized by a program that may be handled by the program. Laravel events simply provide an observer pattern.
Let’s define simple steps through which we can handle our own custom events:
Create an Event class using the shown command:
php artisan make:event <event-class>
Create a handler class to handle the created event with command:
php artisan handler:event <handler-class> --event = <event-class>
Now, register the Event class and its handler in EventServiceProvider class.
We now need to register the event and its handler class in app\Providers\EventServiceProvier.php file. This file contains an array called $listen. In this array we need to add event class as key and event handler class as its value.
Finally, Fire the event using below command:
Event::fire(<Event Class Object>);
Conclusion
In this article, we studied how to send emails, handle Ajax and how to handle errors & events in Laravel.
In the final Part 7 of our Laravel tutorial series, we will cover Laravel Facades and Security in the framework. Stay tuned for a final one!
Recent Stories
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment