How to populate view with database information after AJAX request - php

Hi there once again SO community. I've been developing a site and so far it's going pretty well. But today after a long day searching for a solution I can't understand nor find what the right path is...
I want to click on a button and a profile page where you can edit the fields appear. I can redirect to the page I want but I don't know how to send the user data so I can populate the fields.
Here is my button code on my view
<button class="btn btn-xs btn-warning dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false" style="border-color: black" id="dados_{{ $user->username }}"> Alterar Dados Pessoais
<i class="glyphicon glyphicon-cog"></i>
</button>
Here is the button AJAX request handler
if((this.id).indexOf("dados") != -1){
var content = this.id.replace("dados_", "");
$.get('callPermissions', {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
And here is my callPermission Controller
public function callPermissions(Request $request)
{
if($request->ajax()){
$usernames = Input::get('usernameSend');
if(isset($usernames)){
$user = User::Where('username', '=', $usernames)->first();
$returnHTML = view('userOptions.settings')->render();
return view('userOptions.settings');
}else{
Log::warning("Username não existe na base de dados.");
}
}
}
and here my Settings Controller
public function settings(Request $request)
{
return view('userOptions.settings');
}
And here is the route
Route::get('/callPermissions', 'SidebarController#callPermissions');
I know the controller is wrong and from what I've read I should verify if the AJAX is successful and if it is handle i on the AJAX request. But from what I've understand I'm not using the Controller at all (even though it goes there). How should I send the user information (in this case the username, then I can get everything from the database) and then send it to the view? I've been searching and trying out stuff that doesn't work...since the return view("your_view") on the Controller doesn't work.
Sorry if I've been confusing and if you need additional information feel free to ask!
Thanks for your help!!
Edit: If I return this on the controller
return view('userOptions.settings', compact('user'));
and do a replace with the Ajax request as show above and add this to the settings view
<p> {{ $user->name }} </p>
I get the following error Undefined variable: user (View: C:\wamp64\www\siteXL\ideiasxl\resources\views\userOptions\settings.blade.php)
Is there anyway to send the parameters with a compact alike or I need to send it through the link? Was avoiding to show the username on the url.
Edit2: For further clarification, this works as intended
<button onclick="window.location='{{url('/settings/' . $user->username)}}'" type="button" id="dadosPessoais" class="btn btn-default">Alterar Dados Pessoais
<i class="glyphicon glyphicon-wrench"></i>
</button>
but I was trying not to send id's and usernames through the URL.
If this is not achievable it's ok, but if there's a way I can't find it, that's why I'm asking

I think you have to add a parameter in the Route and receive the data in the controller function. I'd do something like this:
Route:
Route::get('/callPermissions/{user}', 'SidebarController#callPermissions');
Controller:
public function callPermissions(Request $request, $user)
{
//get data related to $user
}
Ajax call:
$.get('callPermissions/'+userIdVariable, {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
This would send the user id through the route.
To get the user id with JavaScript, you can make a hidden field in the Blade file and set the user id as the value. For example, if you using Form helper:
{{ Form::hidden('user_id', $user->id, array('id' => 'js-user-id')) }}
And then, in the JavaScript, you can get the value using something like this:
var userIdVariable = $('#js-user-id')->val();

Related

Not found page when clicked detail to get data based on id

I have been fixing this trivial problem a few days, but it didn't solve either.
When I click the detail button on the table, it will display a 404 or not found message.
Controller method
public function detail($id)
{
$data = DB::table('lirik_lagu')->where('id', $id)->first();
return view ('admin.detail-lirik');
}
Route
Route::get('lirik-lagu/detail/{$id}', [LirikLaguController::class, 'detail']);
Blade
<a class="btn btn-success btn-sm" href="{{ url('admin/lirik-lagu/detail', $data->id) }}">Detail</a>
I will try to fix what i think it's wrong in your code.
First you should give the $data to your blade file
Controller method
public function detail($id)
{
$data = DB::table('lirik_lagu')->where('id', $id)->first();
return view ('admin.detail-lirik',['data'=>$data]);
}
Second, your should omit the $ in your Route id parameters
Route
Route::get('lirik-lagu/detail/{id}', [LirikLaguController::class, 'detail']);
Third, when you generate the url url(...) it seems to have an admin prefix but not your route declaration.
Blade
<a class="btn btn-success btn-sm" href="{{ url('lirik-lagu/detail', $data->id) }}">Detail</a>
You are not passing the variable to the view. This is how you do it:
return view('admin.detail-lirik', $data);
If you need to pass multiple variables you can pass an array in the second paramter like this:
return view('admin.detail-lirik, ["varname" => $var]);
I see several problems here, so I'm going to point them out. First one, you never returned the data to your view:
return view ('admin.detail-lirik', $data);
The other is the URL in your blade file. You called admin/lirik-lagu/detail but you defined route without admin in your web.php file. You can remove the admin from your url, or create a name for your route and call it that way:
Route::get('lirik-lagu/detail/{$id}', [LirikLaguController::class, 'detail'])->name('lirik-langu');
And then use it like this
<a class="btn btn-success btn-sm" href="{{ route('lirik-langu', $data->id) }}">Detail</a>

Disable multiple button clicks works but is not updating my data

I am trying to prevent a button to be clicked multiple times to avoid resending requests. The disabling works but my data to be sent or updated is not executed.
<form class="detail_form" method="POST" action="{{ url('update', $id) }}" enctype="multipart/form-data">
#csrf
<button class="btn btn-update accntfrm_btn" type="submit" id="btn-update">Update</button>
</form>
$("#btn-update").on('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true);
setTimeout(function(){el.prop('disabled', false); }, 3000);
});
How can I execute my updates and disallow the multiple clicks at the same time?
Use like this in action attribute of Form,
{{ route('update', ['id'=>$id]) }}
I guess it is your route,
Route::post('/update/{id}','YourController#your_function')->name('update');
and in your controller,
public function your_function(Request $request, $id){ // your code }
and if you want to go pure laravel,
use Form class
{!! Form::open(['route' => ['update', 'id'=>$id], 'files' => true, 'class' => 'detail_form']) !!}
event.preventDefault();
prevents default action of the form, this means that your form is not going to submit to the server. what you can do is use ajax or maybe axios if you have it installed to send your information to the server. Since you obviously have jquery, you can make an ajax request to your server to update your information like so
`const route = "{{ route('update', $id)}}";`
or
const route = "/route/to/your/server";
`$.post(route,
{//add a body if you need to send some information to the server
//it is optional},
function(data, status){// in this callback you can create a feedback
//from a successful trip to and from the server
//for your users
})`
.fail(function(error){
//in this callback you can handle errors from a failed trip
//to and from the server
});

laravel destroy just deletes last added stuff

I am a Laravel newbie. While writing and testing my code, I noticed that my destroy method isn't working right anymore and I cannot find the mistake I've made. So I hope you can help me out.
Whats my (software) target? I want to manage "projects". Every project has many reports. So I got a page with all created projects and I got a page with all reports listed in a table with buttons for "modify" and "delete". I finished all the CRUD stuff for projects and reports, when I recognized that, if I am hover over the delete-button of a report or project, the right ID of the chosen report or project is shown. If I am hitting the delete-button a dialog plopps up and a message is shown: "Do you really want to delete..." with "yes" and "no" buttons. So if I am pressing the "yes"-button Laravel is going to delete the last added database entry.
Even the projects as the reports too got their own controller. But both are using the same _messages.php. I think, that my mistake is in that file.
Excerpt from _messages.php:
#if(Session::has('sweet_alert.confirmDeleteReport'))
<div class="alert alert-warning" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div class="row">
<div class="col-xs-12">
<strong>Achtung!</strong> {{Session::get('sweet_alert.confirmDeleteReport')}}
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-8">
<a class="btn btn-danger" href="{{ route('reports.destroy', $report->id) }}" title="Löschen" data-token="{{csrf_token()}}" data-method="delete">Löschen</a>
<a class="btn btn-default" data-dismiss="alert">Abbrechen</a>
</div>
</div>
</div>
#endif
Excerpt from reportcontroller.php:
public function destroy(Report $report)
{
$report->delete();
Session::flash('sweet_alert.success','Der Bericht vom ' . $report->date . ' mit der Berichtsnummer ' . $report->reportNumber . ' wurde erfolgreich gelöscht.');
return redirect()->route('reports.index');
}
public function delete(Report $report) {
Session::flash('sweet_alert.confirmDeleteReport', 'Soll der Bericht vom ' . $report->date . ' mit der Berichtsnummer ' . $report->reportNumber . ' wirklich gelöscht werden? Dieser Vorgang kann nicht rückgängig gemacht werden.');
return redirect()->route('reports.index');
}
Might there be the fault within the session? I flushed the cache by executing php artisan config:cache but with no luck. Every idea is welcome.
Greetings
If I understand correctly you have a page which lists all reports. Each report has a delete button, and that button route maps to the delete() method you include above. That method flashes a msg to the session, and reloads your report index.
Now on your report index, all reports are listed again, probably inside something like #foreach ($reports as $report). At the bottom of the page, you have the extract you have shown. This uses $report->id, which on this page, after looping through all $reports, is just the last report in that collection. So all it will do is delete the last report.
There are a few solutions I can see:
1) Flash the id of the report you want to delete along with your message in the delete() method. I am not familiar with sweet_alert but can you flash an array, your msg and the id? Something like:
Session::flash('sweet_alert.confirmDeleteReport', [
'id' => $report->id,
'message' => 'Soll der Bericht ...'
]);
And then of course use that id in your alert:
<a class="btn btn-danger" href="{{ route('reports.destroy', Session::get('sweet_alert.confirmDeleteReport.id')) }}" ... </a>
Maybe the syntax is wrong, but I am assuming flashing an array is possible.
2) The way I usually do this kind of thing is use Javascript to populate the alert/modal/whatever with the required data when you click the delete button in the table. Eg your delete buttons (in the main table/list) could have a data-id attribute:
Delete
And some Javascript (pseudo code, implementation depends on how you have things set up):
$('a.delete').on('click', function(e) {
// Prevent the default behaviour of clicking a link
e.preventDefault();
// Find the id of the report clicked
var id = $(this).data('id');
// Update the href of the alert button so it will delete *that* report
$('div.alert a.danger').attr('href', 'reports/' + id);
// ... code to display the alert/modal
});
This way you avoid the page reload to get to your alert/modal. Note this makes your delete() method obsolete, it would not be used any more.
UPDATE
If you need to pass some variable from your view/controller to your external JS file, you can do something like this:
In the view
<script>
var url = "{{ route('reports.destroy', Session::get('sweet_alert.confirmDeleteReport.id')) }}";
</script>
In your external JS (must be loaded after the above inline script)
$('div.alert a.danger').attr('href', url);

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.

Can't query JSON (Laravel + VueJS)

my problem exactly smiliar with this one cant't query json data in laravel 5.2
Already try to implement the right answer from it but still, no luck.
I don't know why....
Previous, i found this Laravel 5.2 Codeception functional test issue with PUT / PATCH requests too, already try to use suggestion from him, but no luck too.
Here's my Laravel Controller
public function update(Request $request, $id)
{
$phonebook = Phonebook::findOrFail($id);
$phonebook->update($request->all());
// even i try this
// Phonebook::findOrFail($id)->update($request->all());
// return Response::json() or return response()->json();
// No luck
}
My function in vue script for update data
editContact: function(id)
{
this.edit = true
var contactid = this.newContact.ID
this.$http.patch('/api/contact/' + contactid, this.newContact, function (data) {
console.log(data)
})
},
Change my vue script to be like the right answer from question above, same result. No effect.
And my button to do edit like this
<form action="#" #submit.prevent="addNewContact">
<div class="form-group">
<label for="contactName">Name : </label>
<input type="text" v-model="newContact.CONTACTNAME" class="form-control" id="contactName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone number : </label>
<input type="text" v-model="newContact.PHONENUMBER" class="form-control" id="phoneNumber">
</div>
<div class="form-group">
<button class="btn btn-primary btn-sm" type="submit" v-if="!edit">Add new Contact</button>
<button class="btn btn-primary btn-sm" type="submit" v-if="edit" #click="editContact(newContact.ID)">Edit Contact</button>
</div>
</form>
Note :
My route file using resource or manual route always same
Route::resource('/api/contact/', 'PhonebookController');
or
patch('/api/contact/{id}', ['uses' => 'PhoneboookController#update']);
And then, there something strange.
(Maybe i am wrong) there no issue or error if we look the detail. But, if we change to response tab the result was empty
After all that process, nothing happen with the data.
CONTACTNAME should be "Mizukiaaaaaaaa" like first screenshot instead of "Mizuki"
Am I missing something??
Any advise?
Thanks
As I suggested to you, try to invert the params in your update method in your controller.
And to get a response, you have to send it back (with code 200, 400, 401, whatever you want).
public function update($id, Request $request)
{
$phonebook = Phonebook::findOrFail($id);
$phonebook->update($request->all());
// your treatment
return Response::json([
'param' => 'value'
], 200);
}
If you want to debug and see it in you response, you can make a dd('debug')in your method, you'll see it in the Ajax request response.
That should work for you !
After browsing and ask so much people about this, finally found it! There's nothing wrong with the request or response. My mistakes are mutator update that i used and my model.
Updated answer
Reason answered here and then I just changed update function on controller. Here the result
public function update(Phonebook $phonebook, Request $request, $id)
{
// You can add any fields that you won't updated, usually primary key
$input = $request->except(['ID']);
// Update query
$saveToDatabase = $phonebook->where('ID', '=', $id)->update($input);
return $saveToDatabase;
}
My previous answer updated all fields including the primary key, somehow it successful update data, but it leave error for sure (duplicate primary key). The query looks like UPDATE SET field = 'value' without condition.
This case is for model that doesn't have any relation with other models (tables), or the model act as master.

Categories