Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### To call ajax in laravel, you have to send csrf token as input. There are two ways to send csrf token into input....
- (Jquery ajax full documentation link https://api.jquery.com/jQuery.ajax/)
- way-1. First one is to send csrf using meta tage in header area, then call it into jquery. The example is given below.
- --keep this meta in header area
- <meta name="csrf-token" content="{{ csrf_token() }}" />
- --write this code in jquery code area. then you don't need to do anything more.
- $.ajaxSetup({
- headers: {
- 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
- }
- });
- $.ajax({
- url: '{{route("ajax_groups")}}',
- dataType: 'json',
- type: 'post',
- data: {category_id: cat_id},
- success:function(response){
- console.log(response);
- }
- });
- way-2. Send csrf token with the data. The example is given below...
- var csrf_token= {{ csrf_token()}}
- $.ajax({
- url: '{{route("ajax_groups")}}',
- dataType: 'json',
- type: 'post',
- data: {category_id: cat_id, _token: csrf_token },
- success:function(response){
- console.log(response);
- }
- });
- ### What is content-type and datatype in an AJAX request?
- contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
- dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.
- If you're posting something like:
- {"name":"John Doe"}
- and expecting back:
- {"success":true}
- Then you should have:
- var data = {"name":"John Doe"}
- $.ajax({
- dataType : "json",
- contentType: "application/json; charset=utf-8",
- data : JSON.stringify(data),
- success : function(result) {
- alert(result.success); // result is an object which is created from the returned JSON
- },
- });
- If you're expecting the following:
- <div>SUCCESS!!!</div>
- Then you should do:
- var data = {"name":"John Doe"}
- $.ajax({
- dataType : "html",
- contentType: "application/json; charset=utf-8",
- data : JSON.stringify(data),
- success : function(result) {
- jQuery("#someContainer").html(result); // result is the HTML text
- },
- });
- One more - if you want to post:
- name=John&age=34
- Then don't stringify the data, and do:
- var data = {"name":"John", "age": 34}
- $.ajax({
- dataType : "html",
- contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
- data : data,
- success : function(result) {
- jQuery("#someContainer").html(result); // result is the HTML text
- },
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement