Laravel delete link for items within a foreach loop - php

I am attempting to delete an item within a foreach loop. In this loop, there are several images within $property. For each image ($propimg), I want to delete each image using it's id. However the link doesn't work. How do I get it to delete the individual image?
#foreach($property->images as $propimg)
<li>{{ $propimg->id }}<br/>{{ $propimg->image_url }}</li>
Delete
#endforeach

You need to perform an Ajax request, please try this:
$("[data-method='delete']").click(function(event) {
event.preventDefault();
$.ajax({
type: "DELETE",
url: $(this).prop("href")
}).always(function () {
location.reload();
});
});
If you get 500 HTTP error, due to CSRF token mismatch, please add this:
$.ajaxSetup({
headers: {
"X-XSRF-TOKEN": document.cookie.match('(^|; )XSRF-TOKEN=([^;]*)')[2]
}
});

Related

Returning value from ajax in vuejs

Im trying to pass an integer (id) to a function which calls an api. The api then checks if the id passed matches any data in the database and returns the name associated with the id. I'm using vue.js for this along side laravel. Below is my code.
<tr v-for="store in storeList" :key="store.id">
<td>{{ getNodeName(store.store_name) }}</td>
</tr>
getNodeName(nodeId)
{
axios.get('api/store/getNodeName/'+nodeId).then(function (response){
return response.data[0].name;
});
}
Now the question is how do I get the result to print inside the td tag. apparently return from ajax doesnt work and I tried pushing it all to an array and printing it again but it didnt work either.
thanks
Assuming your API works, the first thing you are doing wrong is that you are returning from the callback when the Promise is resolved and not from the getNodeName method.
One simple way to achieve what you want, is to loop through your storeList (assuming it's a prop) inside the mounted lifecycle hook (using arrow functions here)
...
<tr v-for="node in nodes" :key="node.id">
<td>{{ node.name }}</td>
</tr>
...
data() {
return {
nodes: []
};
},
mounted() {
this.storeList.forEach(store => this.getNodeName(store.store_name));
},
methods: {
getNodeName(nodeId) {
axios.get('api/store/getNodeName/' + nodeId)
.then(response => this.nodes.push({ id: nodeId, name: response.data[0].name }))
}
}
...
You probably also want to turn this into one API call if possible, since you are making storeList.length calls.
You can make a loop of storelist and get nodeId from there and then do the API calls.
<tr v-for="store in storeData" :key="store.id">
<td>{{store.name}} </td>
</tr>
data(){
return{
storeData : []
};
},
created(){
for(var i=0; i<this.storeList.length; i++){
axios.get('api/store/getNodeName/' + this.storeList[i].store_name)
.then(response => this.storeData.push({ id: this.storeList[i].store_name,
name: response.data[0].name
}))
}
}

Ajax get request laravel 5.4 resource controller

I've been searching for similar question in a while but I couldn't find what would actually help my issue.
Using Laravel 5.4.
So I have a resource controller and its index method that returns a view with some data attached to it.
Then I want to make an ajax request from the view returned which is a search request.
e.preventDefault();
let q = $('#inputserver').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/servers",
type: 'GET',
data: {'data': q},
success: function(response){
console.log('Successo');
}
})
That, for how a resource controller's methods are structured should invoke the index method, in which I want to identify if I have an Ajax request incoming.
If I do, I'll search with a query in an Eloquent Model for the data retrieved by the search form and of course I want to show only the matching results.
This is my controller code:
if(!$request->ajax()){
$colonna = 'id';
$servers = Server::orderBy($colonna, 'desc')->paginate(10);
return view('servers.index', array('servers' => $servers));
}
else{
$servers= Server::where('name', '=', $request->data)->paginate(10);
return view('servers.index', array('servers' => $servers));
}
The issue is that nothing is happening, so the ajax request isn't even considered, can someone help me with this? I'm almost sure the issue is some obvious things I forgot or didn't consider.
Thank you in advance, I'll edit if you would need some more info about it.
EDIT:
This is the route I have Route::resource('servers', 'ServerController');
EDIT2:
I'm sorry ids are in Italian, but I of course select them correctly when using jQuery.
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon">
<span>
<i class="fa fa-search"></i>
</span>
</div>
{{Form::text('search', null, array('class' => 'form-control', 'id' => 'inputserver' , 'placeholder' => 'Cerca..'))}}
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="cercaserver">Go!</button>
</span>
The blade file is messy.Try to create a form open and form close and make the button submit of type. And try to change your ajax to this:
$(document).ready(function() {
$('#cercaserver').on('submit', function (e) {
e.preventDefault();
var input = $('#inputserver').val();
$.ajax({
type: "GET",
url: './servers',
data: {input: input},
});
});
});
make sure you are loading jquery.
What do you mean by nothing's happening? What was shown in the console when the ajax request was fired?
Also, you're returning a view, you might want to return a json array of your results?
return $servers;
Laravel will automagically convert it into a JSON response
https://laravel.com/docs/5.4/responses#creating-responses
Or if you want to be specific:
return response()->json($servers);
https://laravel.com/docs/5.4/responses#json-responses
Edit:
I think I already know the problem, in your resource controller function index, is there a parameter called $request? It might be non existing and for sure will throw a 500 internal server error because you used it in your condition.

Laravel sessions with sweet alert Session Loops

I'm just confused about my code. But I really thought that my code is correct. I'm trying to use with() method in Laravel 5.1 and then return to a view, then the sweet alert appears if the session that has been set is exists. Please see my code below:
PageController.php
return redirect()->route('list.view')->with('sweetalert', 'List has been created!');
view.blade.php
#extends('layout.master')
#section('container')
#foreach($lists as $list)
<li>{{ $list->name }}</li>
#endforeach
#stop
master.blade.php
<div class="container">
// some markup here...
</div>
#if(Session::has('sweetalert'))
<script>
swal('Success!', '{{ Session::get('sweetalert') }}', 'success');
</script>
#endif
I only want it to appear once, but if I try to click the back button, the message appears again. I have also tried the ff. code but nothings change:
#if(Session::has('sweet'))
<script>
swal('Success!', '{{ Session::get('sweetalert') }}', 'success');
</script>
<?php Session::forget('sweetalert'); ?>
#endif
Little help here?
a flash message has to be trigerred otherwise it will not make sense as you will set it everytime for the view
however you can use this code wherever the trigger is
Please Note :- I am just trigerring it everytime
Route::get('/', function () {
session()->flash('testing', 'I see this'); // Please have this line inside the trigger so the session does not get created everytime the view is called
return view('welcome');
});
Hope this helps

Ajax on JQuery drag event

I'm creating a nested list with data from database. On this list, I'm using the JQuery UI Drag effect. What I need to do is when the drag is over, it will update the database.
The list coints Professor's name and his ID, it has as sub-list with his classes, like:
John teaches Math & physics, Dwayne teaches English.
John
*Physics
*Math
Dwayne
*English
Let's say I want to give Math class to Dwayne. So I'll drag Math from John and drop it on Dwayne sub-list. It's working fine.
What I can't do is to make the update on database, because John no longer teaches Math instead John is going to teach it. So I need to make an update there or a delete+insert.
Obs: I'm using laravel
Here is my Code:
#extends('app')
#section('assets')
<script type="text/javascript" src="{{ URL::to('/js/jquery.mjs.nestedSortable.js') }}"></script>
#stop
#section('content')
<ol>
#foreach($professores as $prof)
<li data-id=" {{ $prof->id }}">
{{ $prof->nome }}
<ol class="list-disc">
#foreach($prof->disc as $disc)
<li data-id="{{ $disc->id }}">{{ $disc->nome }}</li>
#endforeach
</ol>
</li>
#endforeach
</ol>
<script type="text/javascript">
$(function(){
var old_teacher;
$('.list-disc').sortable({
connectWith: '.list-disc',
start: function (event, ui){
old_teacher = ui.item.parent().parent().attr('data-id');
},
stop: function (event, ui){
$.ajax({
type: "POST",
url: '{{ URL::to("/professor") }}',
data: {disc: ui.item.attr('data-id'), professor: ui.item.parent().parent().attr('data-id'), old: old_teacher},
success: function(data){
console.log(data);
}
});
}
});
})
</script>
#stop
With this currently code, When I drop the item I get:
Internal Server Error (500)
UPDATE
Route File:
Route::post('professor', [
'uses' => 'ProfessorController#postProfessorList'
]);
Controller File:
public function postProfessorList()
{
Professor::submit(Input::post('disciplina'), input::post('professor'), input::post('old'));
}
Log file: Update
local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Illuminate\Http\Request::post()' in F:\PathToProject\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:210
Internal Server Error (500) means that something is wrong with your server-side (laravel) code.
Can you provide us with the code which is used in POST: /professor ?
EDIT
You might want to check your logs in app/storage or storage/ (depending on the laravel version). They should give you a better description of the error that occurs.
Also, you should replace Input::post('...') with Input::get('...') laravel takes care of $_GET and $_POST variables automatically.
EDIT 2
The error you get is due to Laravels CSRF protection.
You will need to set the csrf token in your ajax request like that:
data: {disc: ....., _token: '{{csrf_token()}}' }

Symfony2 - Issue getting correct id to show/{id}

I have a view page which is passed all my active alerts. On each displayed row, I have a show button so you can see the individual alert
{% for alert in alerts %}
<tr>
<td>{{ alert[0].id }}</td>
<td>{{ alert[0].alertStatus }}</td>
<td>
<input type="button" value="Show" data-url="{{ path('NickAlertBundle_show', {id: alert[0].id}) }}" onclick="show_alert( {{ alert[0].id }} )" id="show"/>
</td>
</tr>
{% endfor %}
So when the button is clicked, the javascript function show_alert is called.
function show_alert(id){
alert(id);
$.ajax({
type: "POST",
url: $("#show").attr('data-url'),
data: {id: id},
success: function(data) {
if(data){
}else{
alert("Unknown Error!");
}
},
error:function(){
alert(id);
}
});
}
Now I do an alert at the top of that function, and that alert always displays the correct id. I think the problem is with the url part of the ajax call. It calls the data-url which should be correct. This is what it should be calling
NickAlertBundle_show:
pattern: /show-alert/{id}
defaults: { _controller: NickAlertBundle:Alert:show }
requirements:
_method: GET|POST
id: \d+
So this should then call the controller action
public function showAction(Request $request, $id)
{
var_dump($id);
if($request->isXmlHttpRequest())
{
$id = (int)$request->request->get('id');
}
return new JsonResponse('test');
}
At this point though, the var_dump in this action always outputs the id of the last added alert, and not the selected alert. And when I display the alert, it always displays the latest added alert.
So what is causing it to get the latest alert id instead of the selected id? As I say, it initially gets the correct id, but at some point this changes.
Thanks
You shouldn't declare duplicated ids, like id="show" in your template, better use class or declare your ids like id="show_1 ... n"

Categories