转自:http://www.tuicool.com/articles/2u2mmmu

Post data using ajax in laravel 5 to controller

If you are going to work with ajax data post to controller or route in laravel 5. There are some need to get ajax call work correctly. Your requirement is csrf token. A default feature in Laravel is it’s automatic CSRF security. When you working with forms it’s automatically add a “_token” hidden field to your form. On each post request token will be matched for csrf protection. so it’s one more cool feature provided by laravel 5.

Why on ajax post 500 internal server error laravel :-

If you are using default way for ajax data post, you will get “500 internal server error” in laravel 5. cause you missing csrf token posting with ajax post data. and error reason is token not being matched on post request. so every time a form data is posting require csrf token match. else you will get “500 internal server error” in laravel.

In this article we will explore how to solve 500 internal server error in ajax post or call in laravel or how to Post data using ajax in laravel 5. there are many ways to do this but i am sharing two ways :-

1. Adding on each request

2. globally

How to Post data using ajax in laravel 5 :-

1. Adding on each request and post data to controller :-

In this way we need to add token on each ajax call with data which is posting

view:- add a “login.blade.php” under “resources/views/” and add below code to make a form


<div class="secure">Secure Login form</div>
{!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
<div class="control-group">
<div class="controls">
{!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
</div>
</div>
<div class="control-group">
<div class="controls">
{!! Form::password('password',array('class'=>'form-control span6', 'placeholder' => 'Please Enter your Password')) !!}
</div>
</div>
{!! Form::button('Login', array('class'=>'send-btn')) !!}
{!! Form::close() !!}

Now add your ajax call or post data script to your layout footer or in the same file.


<script type="text/javascript">
$(document).ready(function(){
$('.send-btn').click(function(){
$.ajax({
url: 'login',
type: "post",
data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val()},
success: function(data){
alert(data);
}
});
});
});
</script>

Routes:- Add your get and post route to “app/Http/routes.php”


Route::get('account/login', function() {
return View::make('login');
});
Route::post('account/login', 'AccountController@login');

Controller:- add a controller to “app/Http/Controllers” with named “AccountController.php” and add below code


<?php namespace App\Http\Controllers;
use Input;
use Request;
class AccountController extends Controller {
public function login() {
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}

After all make go to your page url and click on button and you get your data has been posted and you will get alert with success.

2. globally way :-

In this way we will add token for globally work with ajax call or post. so no need to send it with data post.

1. Add a meta tag to your layout header:- csrf_token() will be the same as "_token" CSRF token that Laravel automatically adds in the hidden input on every form.


<meta name="_token" content="{!! csrf_token() !!}"/>

2.Now add below code to footer of your layout, or where it will set for globally or whole site pages. this will pass token to each ajax request.


<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>

Now make an ajax post request an you are done your data will post successfully.

Post data using ajax in laravel 5的更多相关文章

  1. Fetching data with Ajax小例子

    ajax获取数据示例: 示例1 通过ajax获取txt文件里面的内容示例: <html> <head> <title>Ajax at work</title& ...

  2. html5 file upload and form data by ajax

    html5 file upload and form data by ajax 最近接了一个小活,在短时间内实现一个活动报名页面,其中遇到了文件上传. 我预期的效果是一次ajax post请求,然后在 ...

  3. jQuery 选择器 筛选器 样式操作 文本操作 属性操作 文档处理 事件 动画效果 插件 each、data、Ajax

    jQuery jQuery介绍 1.jQuery是一个轻量级的.兼容多浏览器的JavaScript库. 2.jQuery使用户能够更方便地处理HTML Document.Events.实现动画效果.方 ...

  4. 关于Jquery中ajax方法data参数用法的总结

    data 发送到服务器的数据.将自动转换为请求字符串格式.GET 请求中将附加在 URL 后.查看 processData 选项说明以禁止此自动转换.必须为 Key/Value 格式.如果为数组,jQ ...

  5. jquery ajax中data属性详解

    $.post.$.get是一些简单的方法,如果要处理复杂的逻辑,还是需要用到jQuery.ajax() 一.$.ajax的一般格式 $.ajax({ type: 'POST', url: url , ...

  6. 聊天室(下篇)GatewayWorker 与 Laravel 的整合

    思路 上一篇大概梳理了一下 GatewayWorker 的基础知识.这篇就来准备整合 GatewayWorker 到 Laravel. GatewayWorker 是基于 Socket 监听的服务器框 ...

  7. Laravel Vuejs 实战:开发知乎 (10)使用 Select2 优化话题选择

    1.添加选择Topic 使用Select2,如何安装Select2 ,具体使用实例 Select2 and Laravel: Ajax Autocomplete 及 Loading data remo ...

  8. Vue.js——基于$.ajax实现数据的跨域增删查改

    概述 之前我们学习了Vue.js的一些基础知识,以及如何开发一个组件,然而那些示例的数据都是local的.在实际的应用中,几乎90%的数据是来源于服务端的,前端和服务端之间的数据交互一般是通过ajax ...

  9. jquery ajax解析

    jQuery确实是一个挺好的轻量级的JS框架,能帮助我们快速的开发JS应用,并在一定程度上改变了我们写JavaScript代码的习惯. 废话少说,直接进入正题,我们先来看一些简单的方法,这些方法都是对 ...

随机推荐

  1. OpenGL———混合的基本知识

    混合是一种常用的技巧,通常可以用来实现半透明.但其实它也是十分灵活的,你可以通过不同的设置得到不同的混合结果,产生一些有趣或者奇怪的图象.混合是什么呢?混合就是把两种颜色混在一起.具体一点,就是把某一 ...

  2. HDU 5323 DFS

    DFS Time Limit : 5000/2000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Total Submissio ...

  3. FZU 1894 志愿者选拔(优化循环)

    我并没有多想,他们是用的数组模拟队列,然而我就是优化循环次数过得 #include<iostream> #include<cstdio> #include<cstring ...

  4. 开源企业管理软件 ONES

    ONES 不是 ONS,基于AngularJS + ThnkPHP开发的企业管理系统平台,名字可以理解为ONES is a Niubility ERP System 或者 ONES Notonly a ...

  5. EM阅读资料

    1,从最大似然到EM算法浅解 2,(EM算法)The EM Algorithm 3,数据挖掘十大算法----EM算法(最大期望算法) (番外)最大后验估计(MAP)

  6. STL笔记之【map之移除元素】

    //---------------------------------------------------------// 移除map中满足条件的元素//----------------------- ...

  7. SecureCRT 上传文件的两种方法 Zmodem、SFTP

    Zmodem: 无论有xshell还是secureCRT连接linux的时. 默认都用一个zmodem可以帮助window和linux之间传输文件 很方便和实用的工具. 不过默认是无法使用的 需要安装 ...

  8. 转 通过 spring 容器内建的 profile 功能实现开发环境、测试环境、生产环境配置自动切换

                                      软件开发的一般流程为工程师开发 -> 测试 -> 上线,因此就涉及到三个不同的环境,开发环境.测试环境以及生产环境,通常 ...

  9. view类的XML属性

    属性名称 对应方法 描述 android:background setBackgroundResource(int) 设置背景 android:clickable setClickable(boole ...

  10. CentOS6.5 安装ntopng-1.2.0

    0.准备工作 安装libpcap:最好源码安装. yum install -y libpcap* 安装redis yum install -y redis* 1.安装 tar -zxvf ntopng ...