Laravel 5.4 TokenMismatchException Ajax call - ajax

I get a TokenMismatchException error only when I submit a form with an ajax call? If I don't use an Ajax call I don't get the error.
What is causing this?
Laravel 5.4
I have this in the head of my app.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
My ajax.js
$( document ).ready(function() {
// storing comments
$('#storeComment').on('submit', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
url: '/comments',
data: {},
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
});
I also use the bootstrap.js that automatically registers the value of the csrf-token meta tag with the Axios HTTP library. As explained in the Laravel documentation.
Controlle Method:
public function store(CommentRequest $request)
{
$comment = Auth::user()->comments()->save(new Comment($request->all()));
$response = array(
'status' => 'success',
'comment' => $comment
);
return response()->json($response);
}

Add the token to the ajax's data :
$.ajax({
type: 'POST',
......
data: {'_token': '{{ csrf_token() }}'},
........

Instead of calling jQuery you can call Axios directly and have this automatic csrf injection, with the following code:
var data = ['name' => 'Nikola', 'lastName' => 'Gavric'];
axios.post('/comments', data).then(function(response) {
console.log(response);
});
EDIT: Complete example for axios is
$('#storeComment').on('submit', function(e) {
e.preventDefault();
// Retrieve form data
var temp = [];
var data = $(this).serializeArray();
$.each(data, function(index, field) {
temp[field.name] = field.value;
});
// Post request with temp as data
axios.post('/comments', temp).then(function(data) {
console.log(data);
});
});
And this is the code for jQuery, use whichever approach you like better:
$.ajax({
method: 'POST',
url: '/comments',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
'name': 'Nikola',
'lastName': 'Gavric'
},
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});

$.ajax({
type: 'POST',
........
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
...........
});
try this...

Add csrf-token to head of your application :
<meta name="csrf-token" content="{{ csrf_token() }}">
then :
$.ajax({
url: '/some/url',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(res){
// Your result
console.log(res);
}
});

You can try to disable CSRF verification on specific route in App\Http\Middleware\VerifyCsrfToken.php
protected $except = ['/comments'];

Related

Laravel Explode Ajax Request Containing Name and Numbers

I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}

Notification Laravel

i want to make notification in laravel using ajax and get data from controller but i don't know why this always said 500 internal server error
this is my ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
// updating the view with notifications using ajax
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif",
method:"POST",
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', $("#token").attr('content'));},
data:{view:view},
dataType:"json",
success:function(data)
{
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
});
}
load_unseen_notification();
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
controller
public function index()
{
$pengumuman = Pengumuman::select("pengumuman.*")->count('pengumuman.id');
$data = array(
'unseen_notification' => $pengumuman
);
}
web.php
Route::Post('notif', 'NotifController#index')->name('notif');

How to get a value from ajax call in laravel

I want to get a value from the ajax call in controller function. How can i do it?
My code is here:
<i class="fa fa-pencil-square-o"></i>
My script:
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
My route:
Route::post('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
my controller function:
public function amount_to_pay($id)
{
echo $id;
}
easly return the value:
public function amount_to_pay($id)
{
return $id;
}
Use
var url = '{{ route('amount_popup', ['id' => #id]) }}';
url = url.replace('#id', id);
instead of
'amount_popup/'+ id
You are trying to get the value from a GET request, but you are sending the form as a POST request.
You should change your script code to:
<script>
function amount_pay(id)
{
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
THEN CHANGE YOUR ROUTE TO:
Route::get('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
OR IF YOU WANT TO USE POST... DO THIS...
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup',
data: "id=" + id + "&_token={{ csrf_token() }}", //laravel checks for the CSRF token in post requests
success: function (data) {
alert(1);
}
});
}
</script>
THEN YOUR ROUTE:
Route::post('/amount_popup', 'AdminController\AmountController#amount_to_pay');
THEN YOUR CONTROLLER:
public function amount_to_pay(Request $request)
{
return $request->input('id');
}
For more info:
Laravel 5 Routing

Error Code using $Ajax, phpjson and sqlsrv_fetch_array

I have code like this in dataset.php
$query = "SELECT A,B,C from Table ";
$stmt = sqlsrv_query($link2,$query);
$data = array();
while($row=sqlsrv_fetch_array($stmt))
{
$data['data'][]= array (
'kodeLang' => $row['A'],
'nama_lang' => $row['B'],
'address' => $row['C']
);
}
echo json_encode($data);
and , i want to load the dataset.php in index.php with code like this :
<script>
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'dataset.php', //Relative or absolute path to response.php file
data: '',
dataType: 'json',
contentType: "application/json",,
success: function(data){
alert(data);
$("#atotal td#aTotal").html(data[0]['kodeLang']);
},
error : function (jqXHR,textStatus, errorThrown){
$('#errorr').fadeIn(1000).show();
}
});
event.preventDefault();
});
</script>
But when i using alert(data) in index.php, there's no alert. Is there any missed with my code ?
Trims
I have answer by my self, the proble about the array. I modified the file in index.php
<script>
$(document).ready(function(){
$.ajax({
type: 'post',
dataType: 'json',
url: 'dataset.php',
data: '',
contentType: 'application/json',
success: function(response){
$("#atotal td#aTotal").html(response.data[0].A);
},
error : function (jqXHR,textStatus, errorThrown){
$('#errorr').fadeIn(1000).show();
}
});
event.preventDefault();
});
</script>

How to use ajax in Wordpress?

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me.
Here it is my wordpress action and hook.
function ajax_enqueuescripts() {
wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajax_enqueuescripts);
add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );
function my_action_callback(){
//echo "Df";print_r($_POST);die;
}
and here it is my js code
jQuery(document).ready(function(){
jQuery('#event-form').submit( function () {
var email = jQuery('#event_name').val();
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function() {
alert(email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
return false;
});
});
The value that you alert in your success ajax function must come from your php function so you would have something like this:
PHP
function my_action_callback(){
echo $_POST['email']; die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
in your case data in javascript will be equal to anything that you echo out in your php function.
You can send json objects to javascript by encoding arrays in which case you would have
PHP
function my_action_callback(){
echo json_encode('email' => $_POST['email']));
die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data.email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
I only gave you example of the places in your code that needed to be replaced, the rest seems alright.

Resources