I'm working on a screen with the following url http://localhost/npr/public/admin/athletes/test/143
On this screen, I've implemented the following dynamic droplist Ajax call that's not found:
$(document).ready(function() {
$('select[name="section"]').on('change', function() {
var sectionID = $(this).val();
if(sectionID) {
$.ajax({
url: './getSportPositions'+sectionID,
method: 'get',
//data: {"_token": $('#token').val()},
dataType: "json",
success:function(data) {
$('select[name="position"]').empty();
$('select[name="position"]').append('<option value="">'+ '-- Please choose one --' +'</option>');
$.each(data, function(i, position) {
$('select[name="position"]').append('<option value="'+position.name+'">'+ position.name +'</option>');
});
}
});
}else{
$('select[name="position"]').empty();
}
});
});
Route:
Route::get('getSportPositions{id}','HomeController#getSportPositions');
I've also tried with:
Route::get('/admin/athletes/test/getSportPositions{id}','HomeController#getSportPositions');
Is it due to athlete ID 143 in the calling URL? How do I fix this call?
It seems from the error that it's trying to access this route:
Route::get('/admin/athletes/test/{athlete}/', [
'uses' => 'HomeController#testAnAthlete',
'as' => 'admin.test_athlete'
]);
HTML:
<div class="form-group {{ $errors->has('position') ? ' alert alert-danger' : '' }}">
<label for="position" class="col-md-3 control-label">Position in Team</label>
<div class="col-md-6">
<select class="form-control" name="position" id="position">
#if (!$errors->has('position'))
<option selected value> -- select a team first -- </option>
#endif
</select>
</div>
#if ($errors->has('position'))
<span class="help-block">
<strong>{{ $errors->first('position') }}</strong>
</span>
#endif
</div>
When you are using Ajax you have to get url like
var APP_URL = $('meta[name="_base_url"]').attr('content');
also add this
<meta name="_base_url" content="{{ url('/') }}">
to head tag
then after you can use APP_URL
var url = APP_URL+"/getSportPositions/"+sectionID;
Additional from me. in laravel view :
<meta name="_base_url" content="{{ url('/') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
in addition to #Nikhil Radadiya answer, because using jquery mean you wait for page ready, you can use javascript :
var APP_URL = document.getElementsByTagName('meta')._base_url.content;
var APP_CSRF = document.querySelector("meta[name='csrf-token']").content; // javascript cannot use dash, else you can use csrf_token at meta name
then you can use in your ajax like :
$.ajax({
headers: {
'X-CSRF-TOKEN': APP_CSRF
},
url: APP_URL + '/your_ajax_path',
...
...
});
and make sure the url is loaded in your web route.
You could name the route and use BLADE to set a Javascript variable to that route.
For example:
Route::get('/', 'MyAmazingController#function')->name('my.awesome.route');
Then in your Javascript you can do something like:
url: '{{ route('my.awesome.route') }}';
If you have the javascript in a seperate file, you could create a constant in your view with routes in it.
val ROUTES = {
AJAX: '{{ route('my.awesome.route') }}'
}
Related
How should I handle the csrf_field() function when doing this with AJAX?
here is a link to the project repo.
Here is a link to the article which helped me write the code.
I'm pretty sure I don't have to make too many changes to the code to handle the forms with AJAX instead of regular blade.php form submissions, but I'm unsure of the implementation
<form id="add_item" method="POST" action="/item">
<div class="form-group">
<textarea name="item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" >Add Item</button>
</div>
{{ csrf_field() }}
</form>
you can also put csrf-token in header file like this...
<meta name="csrf-token" content="{{ csrf_token() }}">
then give one unique id to submit button... then after in JavaScript detect that click event. then after call ajax on click event of submit button
$.ajax({
type: "POST",
// url: "{{ route('admin.users')}}" + id,
// url : '/admin/users/',
url: "{{url('admin/users/')}}", // you can pass url using url() OR as simple url OR Route name also
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //get the Csrf token from header
},
data: { id: id, }, //pass here all data which you want to pass to controller
success: function (data) {
console.log(data);
}
});
get the csrf value using
var token = $('input[name="csrfToken"]').attr('value');
and append it to the header
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
you can read more about it here https://stackoverflow.com/a/51964045/9890762
SOLVED.
I had to remove the 'type' attribute from the form as ajax is being used instead,
and ensure the ajax functions are at /public/js/file.js
Then, to make the changes available to the folder resources
npm run dev
<form id="add_item_form" action="/item">
<div class="form-group">
<textarea id="add_item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button id="ajaxSubmit_add">Add Item</button>
</div>
</form>
I am trying to get dependant select items using ajax call. After selecting 'class' it should show the related 'groups'. But, I am getting 500 internal server error on my console. Would someone help me please to get the expected result?
admission-form.blade.php -
<form action="{{ route('admin.students.admission') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-6">
<div class="form-group {{ $errors->has('first_admission_class') ? 'has-error' : '' }}">
<select class="form-control" name="first_admission_class" id="first_admission_class">
<option value="">Select Class</option>
#foreach($classes as $class)
<option value="{{ $class->id }}" {{ (old("first_admission_class") == $class->id ? "selected":"") }}>{{ $class->class_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group {{ $errors->has('first_admission_class_group') ? 'has-error' : '' }}">
<select class="form-control" name="first_admission_class_group">
</select>
</div>
</div>
</div>
</form>
Script for Ajax call:
<script>
$('#first_admission_class').on('change', function(e){
console.log(e);
var class_id = e.target.value;
$.get('http://localhost/school/public/admin/ajax-group/' + class_id, function(data){
console.log(data);
});
});
</script>
web.php -
Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => 'auth:admin'], function () {
Route::get('ajax-group/{id}', function(){
$class_id = Input::get('class_id');
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
});
your route is look like this, when we add param in route they accessible via function param. i hope it works for you.
Route::get('ajax-group/{id}', function($id){
$groups = AvailableclassGroup::where('availableclass_id', '=', $id)->get();
return Response::json($groups);
});
});
you can check laravel doc Laravel route doc
if still it didnot work then
add csrf token, like this in head of your html layout
<meta name="csrf-token" content="{{ csrf_token() }}">
and make your ajax call like this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
type: 'get',
url: '/ajax-group/'+ class_id,
dataType: 'json',
success: function (data) {
},
error: function (data) {
console.log('Error:', data);
}
});
Your wildcard its named id and you are getting as class_id so change :
And make sure your route its named as admin.students.admission
Route::get('ajax-group/{id}', function(){
$class_id = Input::get('id');
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
})->name('admin.students.admission');
And make sure you have imported the classes on route file.
as I saw, you're not sending data, so you can't say $class_id = Input::get('id');. You have id parameter in your url, just use it.
Route::get('ajax-group/{id}', function($class_id){
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
I'm trying to submit a form via ajax, but I'm always getting internal server error
Here is my form code
{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!}
<!-- Solo moderador -->
<div class="card-panel">
#if(Auth::user()->permision->request == 1)
<p class="center">Observaciones del moderador:</p>
<textarea type="textarea" class="materialize-textarea" name="observations" id="updateObservations"></textarea>
#else
<div class="center">
<input type="checkbox" id="userVerify" class="filled-in">
<label for="userVerify">Problema solucionado :)</label>
</div>
</div>
#endif
{!! Form::close() !!}
Here is my route
Route::post('request/update', 'RequestsController#postUpdateRequest')->name('request.update');
Here is my Ajax method
$.ajax({
type: "post",
dataType: "html",
url: 'request/update',
data: $("#form").serialize(),
success: function (response) {
// write here any code needed for handling success
console.log("se envio");
}
});
and here is my method in the controller
public function postUpdateRequest(Request $request)
{
if($request->ajax())
{
// Obteniendo registro de la petición
$petition = Petition::where('id', $request->id)->first();
// Guardando
$petition->fill($request->all());
$auditConfirm = $petition->isDirty();
$petition->save();
// Guardando registro de auditorÃa
if($auditConfirm){
AuditsController::postAudit($this->action_id_update);
}
}
}
EDIT: This is the console output
Include this in your form:
echo Form::token();
Basically Laravel expects a CSRF token, middleware makes sure that token sent from form matches the token created before it.
If you don't want to add that on forum, you can add that in AJAX setup:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
..and have this in the HTML page header:
<meta name="csrf-token" content="{{ csrf_token() }}">
You are missing the CSRF token, Laravel has a method of handling this vulnerability via middleware, you have 2 options:
Add csrf token in html form:
{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!}
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
Provide a global header when making a request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Read more
SOLVED:it seems that ive been missing the id value in the request all this time
I'm at lost on what is the way to do this. So basically i got a multiple comment form like this :
#foreach($lists as $list)
//some views
<form class="commentForm">
<input type="text" class="commentBox" name="comment" />
<input type="submit" class="submitBtn" value="Comment" />
</form>
#endforeach
And i want to implement AJAX so that every time user comment something, the page won't reload. My current route for submitting the comment is :
Route::post('list/{listID}/comment', 'ListController#comment');
And i don't know how to pass that ID from the view to AJAX and then back to controller. I tried to obvious one, use 'list/{{ $list->id }}/comment' in the AJAX url, that didn't work. Also tried some other things but basically all for naught.
Thank you in advance !
EDIT : My AJAX code :
$(document).ready(function(){
$(document).on("submit", '.commentForm', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
var data = $(this).serialize();
var me= this;
$.ajax({
type: 'POST',
url: 'posts/{{ $auction->id }}/comment',
data: data,
datatype: 'JSON',
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
return false;
})
});
I just console.log-ing the outputs for now to see whether it works not.
In laravel, they use blade templating. I dont know where you put your ajax code, but these bracket: {{ }}, {!! !!} only will be considered as templating when you use the extension .blade.php.
In laravel you can use .php under resource/views as the html template, but the one inside {{ }}, {!! !!}, and other blade syntax will be treated as normal text instead of being interpreted again. If you need, usually i will make the layout will be something like this:
<html>
<head>
#yield("sytles")
#yield("additionalstyles")
#yield("includestyles")
................//as many as you need
</head>
<body>
<div>#yield("content")</div>//content here
#yield("scripts")
#yield("additionalscripts")
#yield("includescripts")
................//as many as you need
</body>
</html>
and then in the view, when i need to make ajax request, i will enclose it inside the #section("script") #stop or whichever the yield that haven't been used yet, so for example the view part of your code maybe will be like this after using this template:
#extends("layout")
#section("content")
#foreach($lists as $list)
//some views
<form class="commentForm">
<input type="text" class="commentBox" name="comment" />
<input type="submit" class="submitBtn" value="Comment" />
</form>
#endforeach
#stop
#section("additionalscript")
<script>
$(document).ready(function(){
$(document).on("submit", '.commentForm', function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
var data = $(this).serialize();
var me= this;
$.ajax({
type: 'POST',
url: 'posts/{{ $auction->id }}/comment',
data: data,
datatype: 'JSON',
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
return false;
})
});
</script>
#stop
In this way, your
url: 'posts/{{ $auction->id }}/comment',
will going to be rendered as something like
url: 'posts/hansishandsome/comment',
Hope this help
I recommend using jQuery's .data() feature, so in the foreach loop you do this:
<form class="commentForm" data-id="{{$list->id}}">
<input type="text" class="commentBox" name="comment" />
<input type="submit" class="submitBtn" value="Comment" />
</form>
Then one listener to rule them all:
$(document).on("submit", '.commentForm', function(e){
e.preventDefault();
var comment_id = $(this).data('id');
console.log('comment id = ',comment_id);
$.ajax({
type: 'POST',
url: 'posts/' + comment_id + '/comment',
//etc...
});
You can do following steps:
Add one hidden field with value as Listid in form like:
<input type="hidden" id="listId" value="{{$list->id}}" />
And then you can use it in ajax call like:
$listId = $("#listId").val();
These are the following ways you can do it
Create a hidden input
<input type="hidden" id="listid" name="listid" value="{{ $list->id }}">
and read the value through JQuery
var listid = $('#listid').val();
Create a JSON object and read it in your
<script>
var list = {
id : {{ $list->id }} //you can also add other variables in the object
}
</script>
And in your js file use the list object
NOTE: the list object must initialized before you run your script
$.post('list/' + list.id + '/comment', data);
I want to submit a form of checkboxes that represent the interests of an user. When clicking a checkbox, the value of the checked interest will be sent to the database "Followers" table and the user will begin following that interest. I couldn't find a way to have one form submit multiple rows, so i decided to make each checkbox a different form and use Ajax to send the information as the user goes through the form. However, When i attempt to make a POST using Ajax I get POST http://localhost/interest net::ERR_CONNECTION_REFUSED. or ERR 500. Can someone help me? I don't understand where i'm messing up. here is my code:
i have the meta tag
<meta name="_token" content="{{ csrf_token() }}"/>
html:
{!! Form::open(array('id'=> 'form2')) !!}
<div class = "form-group">
<div class="col-md-6">
{!! Form::label('title','Title:', ['class' => 'col-md-4 control-label']) !!}
{!! Form::checkbox('interest_id', '2', false, ['class' => 'formclick']) !!}
</div>
</div>
<input id = "submit" type="button" value="Click Me!" />
{!! Form::close() !!}
JS:
var base_url = 'http://localhost';
$('#submit').click(function(){
var interest = {
interest_id : $('.formclick').val()
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: base_url+'/interest',
data: interest,
dataType: 'JSON',
success: function() {
alert('new interest');
}
});
});
InterestController:
public function store(InterestRequest $interest)
{
$interest = new Follower(array(
'user_id' => $interest->get('interest_id'),
'follower_id' => Auth::id()
));
$interest->save();
}
Don't use the same variable name for an parameter and a local scope variable.
Are you using nginx or apache?
Have you setup your .htaccess file right?
What do you see when you go to http://localhost/interest/public
Enable the Laravel debug mode, there you have much more information which can be of help to you and us.
You should use proper path of URL to ajax call.
instead of use:
var base_url = 'http://localhost';
use:
var base_url = '{{ url() }}';
It will resolve your issue