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'));
Related
i am using ajax to store the info but when i store or not store it returns a json page and i don't want it to return a json i want to add the item without relead the page and using calidation also
please help
here is my code
my route
Route::resource('products',App\Http\Controllers\ProductController::class);
my form
<form method="POST" id="productform">
#csrf
#method('POST')
<ul id="showerrors">
</ul>
<div class="form-group">
<label for="">name</label>
<input type="text" name="name" class="form-control">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
and my ajax code
<script>
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var data = {
'name' : $("input[name='name']").val(),
'_token' : $("input[name='token']").val(),
}
// console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:data,
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
Try this solution
add id to input field
<input type="text" name="name" class="form-control" id="name">
changes in script
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:{
name: name
},
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
in your controller store function
suppose your model name is Product
public function store(Request $request)
{
...
$product = Product::create($request->only('name));
return response()->json([
'status' => 200,
'message' => 'Product created successfully.'
]);
}
I have a trouble when to upload img using ajax in laravel. I have an error in getClientOriginalExtension() I think that trouble in enctype in ajax because the controller can not read the upload file.
this is my view :
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('body').on('click', '#saveBtn', function(){
var url;
var registerForm = $("#data-form");
var formData = registerForm.serialize();
$(this).html('saving...');
$('#saveBtn').attr('disabled',true);
$.ajax({
enctype: 'multipart/form-data',
url: '{{ route('blog.store') }}',
type:'POST',
data:formData,
success:function(data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Data');
}
});
});
});
</script>
and this is my controller
$name_file = time().'.'.$request->img_thumbnail->getClientOriginalExtension();
$request->img_thumbnail->move(public_path('images'), $nama_file);
create.blade.php
#section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>
<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>
</form>
#endsection
#push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
#endpush
upload.js
$(function () {
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();
let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];
formData.append('photo', photo);
formData.append('name', name);
$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});
});
Controller
class MyController extends Controller
{
use StoreImageTrait;
public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}
StoreImageTrait
<?php
namespace App\Traits;
use Illuminate\Http\Request;
trait StoreImageTrait
{
public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready( function () {
$("form#data-form").on("submit",function (e) {
e.preventDefault();
var formData = new FormData(this);
//Ajax functionality here
$.ajax({
url : '{{route('blog.store')}}',
type : "post",
data : formData,
dataType : 'json',
success:function (data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
}, // success end
contentType: false,
processData: false
}); // ajax end
}); // form submit end
}); //document end
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 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