Ajax Delete Function in Laravel doesn't work - php

I tried to make an ajax delete functionality in Laravel.
I cant figure out why it isnt working... There is no error but nothing happens -
Thanks for any help!
My route:
Route::post('/deleteWithAjax', 'eventController#deleteWithAjax');
My delete Button:
<button value="{{$event->id}}" class="btn btn-danger btn-dell">Delete</button>
My javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('document').on('click', '.btn-dell', function() {
var id = $(this).val();
var el = $('#{{$event->id}}');
$.ajax({
type: 'post',
url: "deleteWithAjax",
data: {
'id': id
},
success:function(data){
el.remove();
}
})
})
});
My Controller Method:
public function deleteWithAjax(Request $r){
eventModel::find ( $r->id )->delete();
return response()->json();
}
The element i want to remove is a div:
<div id="{{$event->id}}">
EDIT**
I changed the event Handler
document.getElementById("btn-dell").onclick = function()
now it gets fired - but i get an error in the console and the backend is still not called at all:
POST http://wt-projekt.test/index.php/deleteWithAjax 419 (unknown status)
send # app.js:29
ajax # app.js:29
document.getElementById.onclick # home:50

I solved the problems:
I placed the token part in the document ready function
--> No error anymore, record deleted in the DB but still in the view
I added dataType: 'text' to the ajax call
--> error also deleted in the View
Nevertheless thanks for your comments!

Related

loading url to bootstrap modal using ajax in Laravel not working

In Laravel -Controller name is ProductController, method is showproductinmodal .
I tried this, javascript code it worked.
Web Route:
Route::get('admin/product/show/{id}', 'Admin\ProductController#showproductinmodal');
JS:
<script>
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$(".modal-body").load("{{URL::to('admin/product/show/')}}"+"/"+productid);
});
</script>
Url loaded and returned some text to modal.
But this Javascript code not worked, i want to use code below:
$(document).ready(function(){
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$.ajax({
url: '{{route('admin.showproductinmodal')}}',
type: 'post',
data: {id: productid},
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
My web route code
Route::post('admin/product/show/', 'Admin\ProductController#showproductinmodal')->name('admin.showproductinmodal');
My Controller code:
public function showproductinmodal(Request $id)
{
return "Your test id:" . $id;
}
My a tag
Any ID test
Modal works normal, pops up when I use first javascript code everything works ok data loading, but second javascript code is necessary for me. I inserted alert also in $.ajax request but it didn't work.
Might be you are missing crsf token in you case:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Set csrf token for ajax call once then call N number of ajax:
$(document).ready(function () {
$('.showinfo').click(function () {
var productid = $(this).data('id');
let url = "{!! route('admin.showproductinmodal') !!}"
// AJAX request
$.ajax({
url: url,
type: 'post',
data: {
id: productid
},
success: function (response) {
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
And it will me more better, if you will use bootstrap model event, and use base url with javascript global variable.

Laravel ajax form data not posting to controller

I finally got my AJAX function working and it correctly posted data to the controller. But it only worked when the data being sent was included in the form action- /UoE/buy-product/{{product_id}}. But I only want the form action to be /UoE/buy-product/, as otherwise I am essentially sending the data twice. Once here, and once in my ajax function.
Here is my view
<form class="buy-product-form" id="{{$product->id}}" action="{{url('/UoE/buy-product')}}" method="POST">
{{csrf_field()}}
<button class="pull-right btn btn-primary">BUY NOW</button>
</form>
Here is my AJAX function
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).closest("form").attr("id");
$.ajax({
url: $(this).closest("form").attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'JSON',
success: function () {
window.alert($(this).closest("form").attr('action'));
}
});
}));
});
Here is the first line of my controller (everything else here works fine)
public function buyProduct(Request $request){
$product_id = $request->id;
And here is my routes.php file
Route::post('/{university_code}/buy-product', 'UserController#buyProduct');
Managed to fix it, I changed the routes file and removed that when a button was clicked.

How to prevent page reload while bookmarking it?

I am making a book library site using laravel. I am trying to add bookmark functionality. I have tried doing something like that on click of bookmark button, page no is being send to database and it is working. Issue is that on return from controller page is getting reload causing book to back on page no 1. Is there is any way that data sends to database without page reload??
I know a bit that ajax do this, but I am using JavaScript in my application and I tried to deploy ajax with it but no luck.
I am showing up my code. Any good suggestions would be highly appreciated.
My javascript function:
function bookmark()
{
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
count is defined up in script.
My route:
Route::post("save_bookmark/{b_id}/{p_no}",'BookmarkController#create')->name('save_bookmark');
My controller:
public function create($b_id, $p_no)
{
$b=new bookmark;
$b->u_id=Auth::user()->id;
$b->book_id=$b_id;
$b->p_no=$p_no;
$b->save();
return response()->json([
'status' => 'success']);
}
My html:
<li><a id="bookmark" onclick="bookmark()" >Bookmark</a></li>
Note: There is a navbar of which bookmark is a part. There is no form submission.
try this: use javascript to get the book id
$("#btnClick").change(function(e){
//console.log(e);
var book_id= e.target.value;
//$token = $("input[name='_token']").val();
//ajax
$.get('save_bookmark?book_id='+book_id, function(data){
//console.log(data);
})
});
//route
Route::get("/save_bookmark",'BookmarkController#create');
you need add event to function and add preventDefault
<button class="..." onclick="bookmark(event)">action</button>
in js:
function bookmark(e)
{
e.preventDefault();
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
in controller you ned use it:
use Illuminate\Http\Request;
...
...
public function create(Request $request)
{
$b=new bookmark();
$b->u_id=Auth::user()->id;
$b->book_id=$request->get('b_id');
$b->p_no=$request->get('p_no');
$b->save();
return response()->json([
'status' => 'success']);
}
in route use it:
Route::post("save_bookmark/",'BookmarkController#create')->name('save_bookmark');
Well, assuming your bookmark() JavaScript function is being called on a form submit, I guess you only have to prevent the form to be submitted. So your HTML code would looks like this:
<form onsubmit="event.preventDefault(); bookmark();">
Obviously, if you're handling events in your script.js it would rather looks like this:
HTML
<form id="bookmark" method="POST">
<input type="number" hidden="hidden" name="bookmark-input" id="bookmark-input" value="{{ $book->id }}"/>
<input type="submit" value="Bookmark this page" />
</form>
JavaScript
function bookmark(book_id, count) {
$.ajax({
type: "post",
url: "save_bookmark",
data: {
b_id: book_id,
p_no: count
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
let form = document.getElementById('bookmark');
let count = 1;
console.log(form); //I check I got the right element
form.addEventListener('submit', function(event) {
console.log('Form is being submitted');
let book_id = document.getElementById("bookmark-input").value;
bookmark(book_id, count);
event.preventDefault();
});
Also I would recommend you to avoid as much as possible to insert PHP code inside your JavaScript code. It makes it hard to maintain, it does not make it clear to read neither... It can seems to be a good idea at first but it is not. You should always find a better alternative :)
For example you also have the data-* to pass data to an HTML tag via PHP (more about data-* attributes).

Laravel 5.3 Ajax - Retrieve data sent in the ajax request from the controller

index.html
<form id="my-form">
<select id="my-select">
<option value="1">Tom</option>
<option value="2">Jerry</option>
</select>
<input type="submit" value="send data!">
</form>
Controller.php
public function getValue(Request $request)
{
return User::find($request->input('select_id'));
}
ajax.js
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var showUser = $('#show-user');
$('#my-form').on('submit', function () {
var select_id = $('#my-select').val();
$.ajax({
method: "POST",
url: "ajax",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
"select_id": select_id
},
error: function (data) {
//something went wrong with the request
alert("Error");
},
success: function (data) {
inner = "";
data.forEach(function (el, i, array) {
inner += "<div>" + el.name + "</div>";
});
showUser.html(inner);
}
});
event.preventDefault();
});
});
web.php
Route::post('ajax','Controller#getValue');
Update:
#Mahdi Youseftabar -> Thanks for it, according to the documentation I should use input() to get the request!
Problem 1: Error: 500 (TokenMismatchException);
What I did?
Add meta to :
<meta name="csrf-token" content="{{ csrf_token() }}">
I set the headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
...
headers: {
'X-Auth-Token' : token
},
...
});
What I need to do?
Retrieve the id sent in the ajax request from the controller [SOLVED]
Validate the token by the ajax request** Error 505 (Problem 1) [SOLVED]
Return from the controller is Empty [SOLVED]
Output the Users into the <div class="showUser"></div> [SOLVED]
Github Documentation of my project:
(Many to many relationships - Laravel 5.3, Ajax)
https://github.com/39ro/StudentSchoolProject
your problem is in route :
Route:post('ajax','Controller#getValue');
you use post method in your jQuery but in route you define that route method 'get' ...
in this case when you request with ajax, laravel respond you a empty response
another issue is in getting your user_id from request, you should use this in your controller:
return User::find($request->input('user_id');
Two things check
In js
data: {"userid" : userid}
method: "POST",
in controller
$value_select = User::where($request->userid)->first();
return $value_select;
Now check the response and tell me if it works
If you don't get an error, and the result is null then you probably missing something.
Remember that find() function you use in your controller is searching for primary key only.
And its an ajax request so you wont see it in the browser. To see the return value you should look in the
Developer tools > Network > and then find the request to see the
preview and response
Add relationship to Controller.php
My problem was the relationship with the other two table.
I update my main Question with the link to my GitHub Project, where I applied all your suggestions! Thanks everyone, I solved it!
For the token I solved adding what I showed in Ajax.js.
And to retrieve the data from the relationship I just make it:
public function getValue(Request $request)
{
return User::find($request->input('select_id'))->relationship_table;
}

Why isn't my ajax call completing, it's sending, but I receive a 404 in response from CakePHP?

I have the following ajax call:
$("#welcome a.close").click(function(e) {
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
e.preventDefault();
}
});
});
Aimed at the following piece of my site:
<div id="welcome">
<h2>Welcome <a class="close" href="Javascript:;"></a></h2>
<div class="left">
</div>
<div class="right">
<div class="loginElement">
</div>
</div>
<div class="clear"></div>
</div>
With the following code to answer the ajax request:
<?php
class VisitorsController extends AppController {
function hide_welcome() {
if($this->RequestHandler->isAjax()) {
$this->Session->write('Welcome.hidden', true);
echo 'Success.';
}
else {
echo 'I am, in fact, here.<br>';
$this->autoRender = false;
}
}
}
?>
It's pretty straight forward. It calls to /visitors/hide_welcome to set a session variable noting that they've hidden the welcome. But it doesn't seem to complete. If I place alerts on either side of it, like so:
$("#welcome a.close").click(function(e) {
alert("Begin.");
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
e.preventDefault();
}
});
alert("End.");
});
They will trigger. But alerts placed in success are ignored. The same goes for error and complete. This was working just fine on my test machine. The page in question is definitely there, I can reach it with out ajax. Firebug reports nothing, neither does the error console. Success simply never fires.
The strangest part is that often if I reload manually the welcome disappears, indicating that the ajax call did fire. It just never returned. What is going on here? I'm at wits end. Any one see any trees I haven't barked up yet?
SOLUTION:
CakePHP is supposed to auto detect ajax calls. But in this instance, it wasn't. As a result it was running the code I had for the Ajax, but then returning a 404 when it failed to find a view. The solution was to append $this->autoRender= false; to the end of the ajax handling controller function. After that everything worked beautifully.
I think given your symptoms, you're redirecting to whatever URL the <a class="close"> you're clicking on pointed to - since the default behavior isn't prevented.
The e.preventDefault() call should happen in the base method, not a callback, like this:
$("#welcome a.close").click(function(e) {
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
}
});
e.preventDefault();
});
Try adding data to your success callback like so:
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(data){
$("#welcome").hide(0);
e.preventDefault();
}
});
EDIT:
Try supplying the absolute path of your url:
$.ajax({
type: "GET",
url: "http://fridgetofood.com/visitors/hide_welcome",
success: function(data){
$("#welcome").hide(0);
e.preventDefault();
}
});

Categories