Last active
December 2, 2015 06:53
-
-
Save permatis/1e88d364861725d54cd6 to your computer and use it in GitHub Desktop.
Mengirim data dengan method (post/get) dengan Laravel 5 dan Ajax menggunakan csrf.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Mengirim data method get | |
* / | |
// index.html | |
<!-- Header --> | |
<meta name="_token" content="{!! csrf_token() !!}"/> | |
<!-- Footer --> | |
$.ajaxSetup({ | |
headers: { 'X-CSRF-Token' : $('meta[name="_token"]').attr('content') } | |
}); | |
var CSRF_TOKEN = $('meta[name="_token"]').attr('content'); | |
jQuery.ajax({ | |
type: 'get', | |
url: '/ajax/', | |
data: {'_token' : CSRF_TOKEN}, | |
dataType: 'json', | |
success: function(data) { | |
$('#select').empty(); | |
$.each(data, function(i, val) { | |
$('#select') | |
.append($('<option>').text(val).attr('value', i)); | |
}); | |
} | |
}); | |
//route | |
get('ajax', function() { | |
return response()->json(\Request::all()); | |
}); | |
/** | |
* Mengirim data dengan method post | |
*/ | |
//index.html | |
<form method="POST" action="http://localhost.dev/ajax" accept-charset="UTF-8"> | |
<input name="_token" type="hidden" value="{!! csrf_token() !!}"> | |
<input type="submit" value="simpan"> | |
</form> | |
<!-- Footer --> | |
$.ajaxSetup({ | |
headers: { 'X-CSRF-Token' : $('input[name="_token"]').attr('value') } | |
}); | |
$('form').submit(function(e) { | |
var CSRF_TOKEN = $('input[name="_token"]').attr('value'); | |
jQuery.ajax({ | |
type: 'post', | |
url: '/ajax/', | |
data: {'_token' : CSRF_TOKEN}, | |
dataType: 'json', | |
success: function(data) { | |
//pesan sukses atau lainnya | |
console.log(data); | |
} | |
}); | |
e.preventDefault(); | |
}); | |
// route | |
post('ajax', function() { | |
//simpan ke database | |
return response()->json(['pesan', 'Sukses tersimpan.']); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment