I am making a live search where user can search for business.
This would be done using ajax and display results however I get an error that there is an TokenMismatchException.
Here's my code:
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
method: 'POST',
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
}
}).done(function(response){
$('#results').html(response); // put the returning html in the 'results' div
});
}
Controller:
public function search($search) {
$search_text = $search;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
return view('results')->with('results',$data);
}
}
Route::
Route::get('/', function () {
return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
Route::get('tfgm', 'GuzzleController#tfgm')->name('tfgm');;
Route::get('odeon', 'GuzzleController#odeon')->name('odeon');;
Route::get('chronicle', 'GuzzleController#oldham_chronicle')->name('chronicle');;
Route::get('smokeyard', 'GuzzleController#smokeyard')->name('smokeyard');;
Route::get('profile/', 'ProfileController#checkid')->name('profile');;
Route::get('create/business', 'BusinessController#addBusiness')->name('createBusiness');
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');
Route::post('/searching/{search}', 'SearchController#search');
Route::post('update', 'ProfileController#updateProfile');
Route::post('create', 'BusinessController#createBusiness');
Route::post('image', 'ImageController#image');
Route::post('test2', 'ImageController#gallery');
Route::post('markers', 'BusinessController#saveMarkers');
Route::post('reviews', 'BusinessController#saveReviews');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/redirect/{provider}', 'SocialAuthController#redirect');
Route::get('/callback/{provider}', 'SocialAuthController#callback');
master.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
</div>
<div id="result">
#include('results')
</div>
</div>
</form>
Your line must be
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
In your ajax code you have written X-CSRFToken that is wrong. Correct is X-CSRF-TOKEN
Always use below code in you script file
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Change X-CSRFToken to X-CSRF-TOKEN
Related
i am trying to update data but i am getting error, failed loading post.
AJAX code:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("run");
// e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("updated");
},
});
});
});
view:
when i try all text field in div i get error failed loading post,
<div id="update-form">
//all text fields
<button type="button"name="id" value="{{#$teacher->id}}" id="update-data" >UPDATE</button>
</div>
but when i put everything in form my data is being updated correctly, but in this case ajax code is totally ignored and only last record is updating.
<form action="#if(isset($teacher)) {{route('teachers.update', $teacher->id)}} #else {{route('teachers.store')}}
#endif" method="post" id="update-form" autocomplete="off" enctype="multipart/form-data" >
<button type="submit" name="id" value="{{#$teacher->id}}" id="update-data" > UPDATE</button>
</form>
Console Error:
app.js:10216 POST http://todolist.local/teachers/729 405 (Method Not Allowed)
app.js:10216 XHR failed loading: POST "http://todolist.local/teachers/729".
javascript?v=1567677915:4 XHR finished loading: GET "http://todolist.local/_debugbar/open?op=get&id=X15228e3cd6c2213f70bded7c0a69583b".
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
web.php:
Route::get('/', 'TeachersController#index')->name('home');
Route::resource('teachers', 'TeachersController');
Update your ajax request as below:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "PUT",
/*Your logic*/
});
});
});
View
<form action="#if(isset($teacher)) {{route('teachers.update', $teacher->id)}} #else {{route('teachers.store')}} #endif" method="post" id="update-form" autocomplete="off" enctype="multipart/form-data" >
{{method_field('PUT')}}
{{ csrf_field() }}
<button type="submit" name="id" value="{{#$teacher->id}}" id="update-data" > UPDATE</button>
</form>
Try this..
ajax post caused the webpage to reload before I could get a result, therefore.
I'm trying to send data to back-end and i'm getting 404 error with this explanation in network tab:
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
Route
Route::middleware('verified')->group(function () {
Route::post('/snaptoken/{id}', 'Admin\PayController#token')->name('securepaymentnow');
});
Controller
public function token(Request $request, $id)
{
//Find project
$project = Project::findOrFail($id);
//rest of data
}
Blade
//form and button
<form id="payment-form" method="POST" action="{{route('securepaymentnow', $project->id)}}">
#csrf
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<button class="btn-sm bg-success pay-button" data-id="{{$project->id}}" type="submit"><i class="fas fa-fas fa-shield-alt"></i> Secure Payment</button>
//javascript
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/securepaymentnow")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
}
});
});
Any idea?
.........................................................................................................................
if you are using url() function, you should use the {{ url('/snaptoken') }}.
But if you want to use the "name" from the "securepaymentnow", use route() function with this example {{ route('securepaymentnow', $theId) }}.
Both should works.
Refer Laravel NamedRoute for details.
I can't figure out how to get this ajax request to post.
<button class="btn btn-sm btn-primary" id="ajaxSubmit">Submit</button>
<textarea rows="4" class="form-control resize_vertical" id="application_notes" name="application_notes" placeholder="Notes">{{$application->notes}}</textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var url = "/instructor-notes-save/{{$application->id}}"
$(document).ready(function(){
$('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: url,
method: 'post',
data: {
application_notes: jQuery('#application_notes').val(),
},
success: function(response){
console.log(response);
}});
});
});
</script>
My controller is this:
public function saveNotes(Request $request, $id)
{
$application = Application::findOrFail($id);
$application->notes = $request->application_notes;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}
And for what it's worth, here is my route:
Route::post('/instructor-notes-save/{id}', 'InstructorsController#saveNotes')->name('instructor.save.note');
What am i missing to get this ajax request to work? In my console log, i get a 419 unknown status error.
Kindly check that the meta tag _token is present in your layout file inside the <head> tag.
Also please make sure that the AJAX url is present in your routes file.
add the following tag in your html <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">
I have a Vue.js component...
<template>
<form method="POST" action="/login">
<button class="btn btn-primary center-block" #click="$emit('buttonClicked')">
Login
</button>
</form>
</template>
<script>
var axios = require('axios');
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
export default {
created: function () {
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
},
props: ['show'],
name: "login-component",
methods: {
close: function () {
this.$emit('close');
},
buttonClicked: function () {
axios.post('/login', {data: this.data})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.message);
});
}
}
}
</script>
My csrf exists in meta:
<meta id="token" name="csrf-token" content="{{ csrf_token() }}">
But it doesn't pass with the Ajax request instead I get...
419 unknown status and no _token in console->Form Data
What am I doing wrong?
I tried to use...
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
};
But it didn't help.
I solved by this way:
export default {
data() {
return {
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
},
...
And inside <form></form>:
<input type="hidden" name="_token" :value="csrf">
I am getting this error Method post does not exist., and I can't figure it out what is going on. My routes:
Route::group(['middleware' => ['auth']], function () {
Route::get('/', 'SiteController#index');
Route::get('/dashboard', 'DashboardController#index')->middleware('role');
Route::post('/search', 'UserController#search')->middleware('role');
});
HTML code:
<form class="navbar-form" role="search" id="employees-search">
<div class="input-group add-on col-md-6">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i> </button>
</div>
<input class="form-control" placeholder="Search" name="employee-name" id="employee-name" type="text">
</div>
</form>
JS code:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Search users
$('#employees-search').on('keyup', '#employee-name', function(){
let
$this = $(this),
name = $this.val();
if(name.length > 2){
$.ajax({
url: '/search',
type: 'POST',
data: $('#employees-search').serialize(),
contentType: 'application/json',
dataType: 'json',
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
})
UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function search(Request $request)
{
dd($request->post('employee-name'));
}
}
What am I doing wrong here?
The Illuminate\Http\Request class does not have a post() method. You're looking for input().
dd($request->input('employee-name'));