I have an issue with ajax request in laravel - ajax

I need your help on the following please:
I'm working on a Q&A website with laravel and I'm trying to make a stars rating system for the answers with ajax, here is the code:
Question view page which includes the answers:
//question code here
#foreach($answers->sortByDesc('created_at') as $answer)
<div>
<p>{{$answer->body}}</p></div>
<form method="POST" onsubmit="return saveRatings(this);">
#csrf
<input type="hidden" name="answer_id" value="{{$answer->id}}">
<input type="submit"></input>
<div class="starrr"></div> // Rating stars
</form>
Script:
<script>
$(function (){
var ratings = 0;
$(".starrr").starrr().on("starrr:change" , function(event , value){
var ratings = value;
});
});
function saveRatings(form){
var answer_id = form.answer_id.value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : "{{route('rating')}}",
method : "POST",
data : {
answer_id:answer_id,ratings:ratings,
},
success:function(response){
alert (response);
}
});
return false;
}
</script>`
Route:
Route::post('rating', 'RatingController#store')->name('rating');
when I submit the form it doesn't direct me to the URL in the ajax request and throws an error msg :
The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.
http://127.0.0.1:8000/questions/1

Related

After form submit redirect without refresh using Ajax in laravel 8

I am developing multi Step Form Submit without refresh. collect the data from 1st step 2nd step collect some date, 3rd step collect some date & finally submit data in the database. Can you tell me how to fix this.
My blade template.
<form id="post-form" method="post" action="javascript:void(0)">
#csrf
<div>
<input class="form-input" type="text" id="ptitle" name="ptitle" required="required"
placeholder="What do you want to achieve?">
</div>
<button type="text" id="send_form" class="btn-continue">Continue</button>
</div>
</form>
Ajax Script
$(document).ready(function() {
$("#send_form").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var ptitle = $('#ptitle').val();
$.ajax({
url: "{{route('create.setp2') }}",
method:'POST',
data: {_token:_token,ptitle:ptitle},
success: function(data) {
alert('data.success');
}
});
});
Web.php router
Route::post('/setp2', [Abedoncontroller::class, 'funcsetp1'])->name('create.setp2');
Controller method
public function funcsetp1(Request $request) {
$postdata=$request->input('ptitle');
return response()->json('themes.abedon.pages.create-step-2');
}

Refresh the likes counter without reloading the Ajax page

It was necessary to write a method for salting posts in php and decorate the whole thing with ajax so that the page would not reload. The method was written, likes are put, but for the changes to be visible, you need to reload the page. I suspect I made a mistake in the area of success
This is part of the post, you need to update the button with id = "likebtn {{$ post-> id}}"
html form
<form action="{{route('likePost', ['id' => Auth::user()->id, 'postId' => $post->id])}}" method="POST" id="likepostform{{$post->id}}">
#csrf #method('PATCH')
<button data-id="{{$post->id}}" id="likebtn{{$post->id}}" type="submit" class="likebtn button-delete-post-2">
<img src="{{asset('img/footer/like.png')}}" class="img-fluid" width="25"><small class="text-muted mr-4">{{$post->likepost}}</small>
</button>
<input type="hidden" value="{{Auth::user()->id}}" id="user_id">
</form>
Ajax
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click",".likebtn",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
var user_id = $("#user_id").val();
$.ajax({
url: "id"+user_id+"/"+id+"/like",
type: 'PATCH',
data: {_token: token, id: id, user_id: user_id},
success: function (data){
$("#likebtn"+id).html($(data).find("#likebtn"+id).html());
},
error: function() {
alert('error');
}
});
});
});
</script>

Django csrf_token works in one form but not in other

I have a page with two lists: for tasks (tareas) and sales (ventas). When you click their links each one opens it´s own modal and retrieves the info with AJAX.
One works with no problem (tareas). The other one gives me a csrf_token error.
I thought maybe it was a problenm of using two tokens in the same template, but I´m doing it in other templates with no problem.
And if I completely remove the tareas part, the ventas one still get´s the same error.
Venta form call
<form name="ventas_form" action="#" id="form_venta_{{operacion.comprobante}}" method="POST">
{% csrf_token %}
<input name="id" id="venta_id_submit" type="text" value="{{operacion.comprobante}}" hidden="true"/>
<a style="padding-left: 1rem;" href="" id="{{operacion.comprobante}}" class="show_venta" data-toggle="modal" >{{operacion.comprobante}}</a>
</form>
Tarea form call
<form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST">
{% csrf_token %}
<input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/>
<a style="padding-left: 1rem;" href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >{{ tarea.titulo }}</a>
</form>
Venta Ajax
<script>
$(function(){
$('.show_venta').on('click', function (e) {
e.preventDefault();
let venta_id = $(this).attr('id');
$.ajax({
url:'/catalog/ventas-detail/',
type:'POST',
data: $('#form_venta_'+venta_id).serialize(),
success:function(response){
console.log(response);
$('.show_venta').trigger("reset");
openModalVentas(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModalVentas(venta_data){
$('#fecha').text(venta_data.venta.fecha);
$('#comprobante').text(venta_data.venta.comprobante);
$('#cliente').text(venta_data.venta.cliente);
$('#vendedor').text(venta_data.venta.vendedor);
$('#lista').text(venta_data.venta.lista);
$('#prod_codigo').text(venta_data.venta.prod_codigo);
$('#prod_nombre').text(venta_data.venta.prod_nombre);
$('#uds').text(venta_data.venta.uds);
$('#vu').text(venta_data.venta.vu);
$('#subtotal').text(venta_data.venta.subtotal);
$('#bonif').text(venta_data.venta.bonif);
$('#modal_ventas').modal('show');
};
</script>
Tarea Ajax
<script>
$(function(){
$('.show_tarea').on('click', function (e) {
e.preventDefault();
let tarea_id = $(this).attr('id');
$.ajax({
url:'/catalog/tareas-detail/',
type:'POST',
data: $('#form_tarea_'+tarea_id).serialize(),
success:function(response){
console.log(response);
$('.show_tarea').trigger("reset");
openModal(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModal(tarea_data){
$('#creador').text(tarea_data.tarea.creador);
$('#destinatario').text(tarea_data.tarea.destinatario);
$('#titulo').text(tarea_data.tarea.titulo);
$('#tarea').text(tarea_data.tarea.tarea);
$('#resuelto').text(tarea_data.tarea.resuelto);
$('#fecha_creacion').text(tarea_data.tarea.fecha_creacion);
$('#fecha_limite').text(tarea_data.tarea.fecha_limite);
$('#fecha_resuelto').text(tarea_data.tarea.fecha_resuelto);
$('#empresa').text(tarea_data.tarea.empresa);
$('#persona_empresa').text(tarea_data.tarea.persona_empresa);
$('#modal_tareas').modal('show');
};
</script>
Venta view
def VentaDetailView(request):
ID = request.POST.get('id')
ventas_todas = Ventas.objects.filter(pk=ID).get()
venta = {
"fecha": ventas_todas.fecha,
"comprobante": ventas_todas.comprobante,
"cliente": ventas_todas.cliente,
"vendedor": ventas_todas.vendedor.nombre,
"lista": ventas_todas.lista,
"prod_codigo": ventas_todas.prod_codigo,
"prod_nombre": ventas_todas.prod_nombre,
"uds": ventas_todas.uds,
"vu": ventas_todas.vu,
"subtotal": ventas_todas.subtotal,
"bonif": ventas_todas.bonif,
}
return JsonResponse({'venta': venta})
Tarea view
def TareaDetailView(request):
ID = request.POST.get('id')
tarea_select = Tareas.objects.filter(pk=ID).get()
tarea = {
"creador": tarea_select.creador.username,
"destinatario": tarea_select.destinatario.username,
"titulo": tarea_select.titulo,
"tarea": tarea_select.tarea,
"resuelto": tarea_select.resuelto,
"fecha_creacion": tarea_select.fecha_creacion,
"fecha_limite": tarea_select.fecha_limite,
"fecha_resuelto": tarea_select.fecha_resuelto,
"empresa": tarea_select.empresa.Nombre,
"persona_empresa": tarea_select.persona_empresa.nombre,
}
return JsonResponse({'tarea': tarea})
No idea why the tareas part works ... but for sure I would add 'X-CSRFToken' header to both ajax calls:
$.ajax({
url:'/catalog/ventas-detail/',
type:'POST',
data: $('#form_venta_'+venta_id).serialize(),
headers: {'X-CSRFToken': getCookie('csrftoken')}
...
});
where:
function getCookie(name) {
var value = '; ' + document.cookie,
parts = value.split('; ' + name + '=');
if (parts.length == 2) return parts.pop().split(';').shift();
}
You can add CSRF token to header like that too :
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
Then you didn't need to manually add your CSRF token to all your ajax request.

Laravel ajax return 404

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.

How get the value from a link and send the form using mootools?

I have a such form with many links:
<form name="myform" action="" method="get" id="form">
<p>
My link
</p>
<p>
My link 2
</p>
<p>
My link 3
</p>
<input type="hidden" name="division" value="" />
</form>
I would like to send the form's value from the link that was clicked to php script and get the response (not reloading the page).
I'm trying to write a function that gets the value from a link:
<script type="text/javascript">
window.addEvent('domready', function() {
getValue = function(division)
{
var division;
division=$('form').getElements('a');
}
</script>
but I don't know how to write it in a right way. Next I would like to send the form:
$$('a.del').each(function(el) {
el.addEvent('click', function(e) {
new Event(e).stop();
$('form').submit();
});
});
How I should send it to get the response from a php file not reloading the page?
Instead of putting in javascript inline in the HTML, I would suggest using a delegated event instead. I would also send the form using an ajax call instead of a form submit.
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var formEl = document.id('form');
formEl.addEvent('click:relay(.del)', function() {
var value = this.getProperty('data-value');
new Request.JSON({
url: '/path/to/your/listener',
onSuccess: function(data) {
// ...
}
}).get({
value: value
});
});
</script>
This works for me:
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var links = document.id('form').getElements('a');
links.each(function(link) {
link.addEvent('click', function(e) {
e.stop();
var value = link.getProperty('data-value');
var req = new Request.HTML({
url: "/path/to/your/listener",
data: value,
onRequest: function(){
$('display').set('text', 'Search...');
},
onComplete: function() {
},
update : $('display')
}).get(
{data: value}
);
});
})
</script>

Resources