Ajax POST error using Laravel - php

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

Related

laravel - target class does not exist error when using ajax to update form with formdata

I am using Laravel with AJAX to send form update request. With other method such as POST request, everything works fine. I managed to do Update method as well but with a different method which is defining it on data field one by one. But since my new form has a lot of input field, I try to serialize it using FormData, but then the error of target class does not exist came out. The error in specific is
Target class [App\Http\Controllers\Form] does not exist
The Controller that I am trying to send to is named FormController, somehow from the error it removes the "Controller" part.
I am not sure what causes it, hope someone would enlighten me on this issue, thank you.
Laravel Blade
<form enctype="multipart/form-data" id="formUpdate">
#csrf
<input type="hidden" name="flowId" id="flowId" value="1">
<input type="hidden" name="formId" id="formId" value="{{ $formData->id }}">
#component('components.form.form-section-a', ['formData' => $formData, 'projectMember' => $projectMember])
#endcomponent
<div class="grid w-full">
<div class="sm:px-1 md:px-0">
<button class="border-green-600 bg-green-600 w-full py-2 rounded mt-3 text-white submitForm" type="submit">Update</button>
</div>
</div>
</form>
AJAX Script
$("#formUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
// dataType:'json',
processData: false,
success: function (response) {
console.log(response);
// return false;
},
});
});
in your button add data-url="route('Form')" or console.log(url); first then check

How to submit a blade.php form with AJAX

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>

Laravel POST via Ajax

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

Laravel 5.3 Ajax url not found

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') }}'
}

Reload data without refreshing the page using Ajax and Twig

I have a page where a user can write a comment and post it by a simple form.
I'm trying, without success, to do this with ajax using twig.
I can send the ajax request to my controller without problem and the comment is saved in my database.
My issue is to reload a part of my twig template without refreshing the whole page.
The return of my controller:
return $app['twig']->render('#views_suivi/suivi_affaire.html.twig', array('cache' => false,
'auto_reload' => true,
'affaire' => $affaire,
'comments' => $comments
));
$comments countains all the comments of an article. When I send an ajax request, my table comment is updated. Is there a way to update the variable $comments and re-send it to my twig without refreshing the whole page?
Edit: sorry, here's the code of my controller (it just insert a comment in my db)
function addCommentAjax(Application $app, Request $request)
{
$cmt = new CommentaireQueries($app);
$postParams = $app["request"]->request->all();
//var_dump($postParams);
if(isset($postParams['files'])) unset($postParams['files']);
return !empty($postParams) ? $cmt->insertCommentAffaire($app,$postParams) : false;
}
Ajax: 'AjoutCommentaire' is the route to my controller addCommentAjax
$(document).ready(function() {
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type : "POST",
url : "AjoutCommentaire",
data: $(this).serialize(),
success : function() {
alert('success');
}
});
});
});
My form:
<form role="form" method="POST">
<div class="form-group">
<textarea class="summernote" id="contents" rows="10" name="comment"></textarea>
</div>
<input type="hidden" name="phase" value="1" />
<input type="hidden" name="id_affaire" value="{{ affaire.id }}" />
<center><button type="submit" class="btn btn-link btn-block">Envoyer</button></center>
</form>
Basically, I just want to add a comment without refreshing the page.
Thank you !
url in ajax request is not defined properly. You can't just specify route name, you should generate url by route:
$.ajax({
type: "POST",
url: "path('AjoutCommentaire', {})",
...

Categories