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>
Related
I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
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 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.
I'm new to MooTools and trying to send Ajax request with form content to the url.
<form method="post" enctype="multipart/form-data" action="<?= $PHP_SELF; ?>" name="fn" id="fn">
<input name="user_name" id="user_name">
<input name="user_mail" id="user_name">
<input name="user_text" id="user_name">
<input type="file" name="attach">
<input id="button" type="button" value="Submit">
</form>
<script type="text/javascript">
$('button').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
});
});
</script>
When I click on button, nothing happens. How right transferring data from form?
Your code looks good, you had a } missing but aside from that you just forgot to add a .send();
Like req.send();, and you can actually pass the data as a argument to that method.
Test that and check here about the .send() method.
Suggention to how your code could look like:
<script type="text/javascript">
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
} // < --- You actually missed this one
});
$('button').addEvent('click', function(event) {
req.send();
});
</script>
Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>