ajax post with laravel 5.6 - ajax

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() }}">

Related

405 (Method Not Allowed) error on ajax in Laravel 8

I am trying to call an ajax function in my Laravel 8 Project. But on every call I am getting error POST http://127.0.0.1:8000/getReasonForVisit 405 (Method Not Allowed). I have tried many options like changing post method to get, change url etc. but no use. It would be helpful if someone can help me.
Here is my code.
JS File
function getReasonForVisit(catId) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
}
$('#treatment-category').on('change', function (){
var catId = $(this).val();
getReasonForVisit(catId);
});
View
<select class="form-control form-select" name="category" id="treatment-category">
<?php $categories = App::make("App\Http\Controllers\AppointmentsController")->getTreatmentCategories(); ?>
#foreach($categories as $cat)
<option value="{{ $cat->id }}">{{ $cat->category_name }}</option>
#endforeach
</select>
Route
Route::post('/getReasonForVisit', [App\Http\Controllers\AppointmentsController::class, 'getReasonForVisit'])->name('getReasonForVisit');
Controller
class AppointmentsController extends Controller
{
public function getTreatmentCategories() {
$categories = DB::table('treatment_category')->get();
return $categories;
}
public function getReasonForVisit() {
echo 111;
}
}
EDIT
I did cleared my route cache. now it's showing error CSRF token mismatch
Please change option type to method
$.ajax({
method: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
I resolved my issue. Actually I am missing csrf meta tag in my blade. So Now I added this code in view blade file in the <head> tag.
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

Request of Ajax with Laravel 5.4

I am trying to make an example of Ajax request with Laravel 5.4.
The test example is simple, just enter a numeric value in an input = text field in my View and leave the field to send to the Controller, then add + 10 to that value and then return that value to my View so that it can displayed on an alert.
HTML : viewteste.blade.php
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="">
Valor: <input type="text" id="valor" name="valor" />
</form>
</body>
</html>
JS: The js file is inside viewteste.blade.php, I just split it to make it easier to interpret.
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$("#valor").on('blur', function()
{
valor = $(this).val();
$.ajax({
type:'POST',
url:"{{ URL::to('/teste/valor') }}",
dataType: 'JSON',
data: {
"valor": valor
},
success:function(data){
alert('Success');
},
error:function(){
alert('Error');
},
});
});
});
</script>
Route
Route::get('/teste', 'TesteAjaxController#index');
Route::post('/teste/valor', 'TesteAjaxController#valor');
Controller
class TesteAjaxController extends Controller
{
public function index()
{
return view('painel.viewteste');
}
public function valor(Request $request)
{
$valor= $request->input('valor');
$valor += 10;
return $valor; // How do I return in json? in case of an error message?
}
}
Always when I try to send the request via ajax it goes to alert ('Error'). is it that I'm doing something wrong in sending the ajax or route?
to return a json response. you need to use.
response()->json([
'somemessage' => 'message',
'valor' => $valor
]);
UPDATE: you are getting an error alert because i think your route method doesnt match your controller methods.
Route::post('/teste/valor', 'TesteAjaxController#valor');
where in your controller you have
public function cep() ...

How to call ajax function on buttonclick in laravel?

View Code:
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Here ,When I click on the button it should be replaced by the other text. But nothings appears on clicking.
Controller code:
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
In pure js that code work fine
function getMessage(){
alert('Its working!');
}
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Looks OK.
Put a breakpoint in your success and see what data is.
Or do a console.log
Mick
in your ajax code you didn't define dataType, add dataType:"json", to retrive the json data, change your ajax code as
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
dataType:'json',
data:{
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
$("#msg").html(data.msg);
}
});
Update your code with below mentioned code, and let's try.. i will working for me..
<script type="text/javascript" charset="utf-8">
$(document).on('click', '#btnSelector', function(event) {
event.preventDefault();
/* Act on the event */
getMessage();
});
var getMessage = function(){
$.ajax({
type:'POST',
url:'/getmsg', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" id='btnSelector'>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" id="ajax_call" value="Replace Message">
</body>
<script>
$(function () {
$('#ajax_call').on('click', function () {
$.ajax({
type:'POST',
url:'<?php echo url("/getms"); ?>',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
},
complete: function(){
alert('complete');
},
error: function(result) {
alert('error');
}
});
});
});
</script>
Jquery onclick function: jquery onclick function not defined
Also check: Function not calling within an onclick event

Laravel live ajax search - token mismatch

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

Ajax laravel 5.2 doesn't work

I want to develop simple ajax with laravel5.2 with this code
This oneline_help.php view
<html>
<head>
<title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
This is the routes
Route::get('/ajax','front#support');
Route::post('/getmsg','Hello#index');
This is front #support
public function support()
{
return view('online_help', array('title' => 'Welcome', 'description' => '', 'page' => 'online_help','subscribe'=>"",'brands' => $this->brands));
}
This is Hallo #index controller
public function index(){
echo"i in in hello index";
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
The button appear But when click on it, The text doesn't change .
Please tell me why and how to resolve it.
Here is my working example of AJAX....
You don't need to add token in your ajax request, make it global so with every ajax request, your CSRF token will be added automatically.
In your HTML Head section add this meta tag
<meta name="csrf-token" content="<?php echo csrf_token() ?>">
Then add this code in your Javascript tags. this will add CSRF token in every ajax request.
Note this required jquery file should be included in your page. once include call this method below from the file.
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
I have modified your method....
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>', //remove this line
dataType:'json', // you skipped this line
beforeSend:function(){
alert('loading....'); //this will show loading alert
},
success:function(data){
$("#msg").html(data.msg);
},
error:function(){
alert('loading error...')
}
});
}
</script>

Resources