How to fix 'Creating default object from empty value' in Laravel? - php

In blade I have this code:
#foreach ($employees as $key => $employee)
<tr id="{{$employee->id}}">
<td class="visibleemployee tdcenter">
<form action="{{route('admin.employees.cambiarVisible',$employee->id)}}">
<button type="button" id="buttonchangevisible" data-id="{{$employee->id}}">
#if ($employee->public == '1')
<i class="fa fa-check" aria-hidden="true" id="margindataemployee" class="cambiarsiporno"></i>
#else
<i class="fa fa-times" aria-hidden="true" id="margindataemployee"></i>
#endif
</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
</td>
</tr>
#endforeach
When I click the bottom the Ajax function is executed:
$("#buttonchangevisible").click(function(e){
e.preventDefault();
var button = $(this);
var id = button.data('id');
var formData = new FormData($(this)[0]);
$.ajax({
url:'employee/cambiarVisible/' + id,
type: 'PUT',
data: formData,
success: function() {
location.reload();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
And call to the next method:
public function cambiarVisible(Request $request, $id)
{
$employee = Worker::find($id);
if ($employee->public = 0){
DB::table('workers')->where('id',$id)
->first()
->$employee->public = 1;
}
else{
$employee->public = 0;
}
$employee->save();
}
Now don't appear any error, if I click in first row, make the call but don't the update of visible.
But if I click in other row, don't make the call.

I wrote a similar piece of code.
I generated the form dynamically, then called some JavaScript/jQuery.
Code to generate the button:
<button class="btn btn-danger btn-block deleteUserBtn" data-name="{{ $user->name }}" data-id="{{ $user->id }}" data-type="delete" onclick="return false;"><i class="glyphicon glyphicon-trash"></i> Delete</button>
Then using the following code, I executed the ajax call. The reason the click event is attached to the body is because there are multiple delete buttons (this was for an user overview with multiple delete buttons, one for every user). And these buttons can be generated with jQuery, the click event will not fire if you bind to the buttons.
$('body').on('click', '.deleteUserBtn', function() {
var button = $(this) // Button that triggered the event
var id = button.data('id');
var name = button.data('name');
var csrf = $('input[name=_token]').val(); // This token is already on the page, you need a token to prevent csrf
if( confirm('Are you sure you want to delete: ' + name + '?') ) {
var url = "{{ route('overview.users.destroy', ':id') }}";
url = url.replace(':id', id);
$.ajax({
method: "DELETE",
url: url,
data: {
'id': id,
'_token': csrf
},
}).done(function(response) {
// Check if it is successful
if(response == 'deleted') {
// Reload page
location.reload();
} else {
alert('error');
console.log(response);
}
}).fail(function(response) {
alert('error 2');
console.log(response);
});
}
});
As you can see I just passed the id as a parameter.
In your case, to update the user, you can just use the following piece of code:
public function cambiarVisible(Request $request, $id)
{
$employee = Worker::findOrFail($id);
$employee->public = ($employee->public == 1) ? 0 : 1;
$employee->save();
}

Looks like your form has a ajax submit which is using employee/cambiarVisible/{id} as URL. since the id wildcard is supposed to be a php variable (cannot see the variable in JS), it's not being passed to the controller.
Try something like
var id = {!! json_encode($employee->id) !!};
Then change the url as
url:'employee/cambiarVisible/' + id,

Related

How to write an ajax script to delete an entry?

Good day!
Please tell me how to correctly implement the method of deleting a record of Laravel through Ajax. I wrote a script, but somehow it works very crookedly.
The script from the part works, but when you click on the delete button, the record does not disappear. It disappears only after reloading the page. And when I try to delete a fresh record, a route error just flies.
Route
Route::delete('/id{id}/delete', 'ProfileController#delete')->name('deletePost');
Form
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-outline-dark btn-sm mt-4">Удалить</button>
</form>
And my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#delete').on('click', function(e) {
e.preventDefault();
var $this = $(this),
data = $this.data();
$.ajax({
url: "{{route('deletePost', ['id' => $post->id])}}",
method: 'POST',
data: data,
success: function(data) {
$( data ).remove();
},
error: function(d) {
console.log(d);
}
})
})
</script>
You must first remove the ID from the route:
Route::delete('/id/delete', 'ProfileController#delete')->name('deletePost');
You must assign a class name to each html record(or row).
Like the following code:
<table>
<tbody>
#foreach($records as $record)
<tr class="myRow">
...
</tr>
#endforeach
</tbody>
</table>
Also, it is better to create a hidden input in each deletion form to hold the record ID. Like the following:
<form method="post" id="formDelete">
<input type="hidden" name="id" value="{{$record->id}}">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-outline-dark btn-sm mt-4">Удалить</button>
</form>
Then, when a record is deleted by Ajax, you must delete the corresponding row by the specified class name in the success section of ajax code. Like the following code:
var data = $(this).closest("form").serialize();
$.ajax({
url: "{{route('deletePost')}}",
method: 'POST',
data: data,
success: function(data) {
$(this).closest("#myRow").remove();
},
error: function(d) {
console.log(d);
}
})
I hope it helps

Ajax script for deleting records from the database does not work

I wrote a script that should delete a specific entry. The problem is that when you click on the delete button, the record does not disappear, you have to reload the page to make it disappear. And only the first record in the database is deleted, for example, if I click delete the record with id = 2, then the record with id = 1 will be deleted. And I just can not understand why this is happening.
This is my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('data-id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deletePost',['id' => $post->id])}}",
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
}
});
return false;
});
});
</script>
Method
public function delete($id) {
$post = Profile::find($id);
$post->delete();
return response()->json([
'message' => 'deleted...'
]);
}
Route
Route::delete('/id{id}/delete', 'ProfileController#delete')->name('deletePost');
And html
<form action="{{route('deletePost', ['id' => $post->id])}}" method="post" id="formDelete">
#csrf #method('DELETE')
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
</form>
change
var id = $(this).data('data-id');
to
var id = $(this).data('id');
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#delete",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "delete/"+id,
type: 'DELETE',
data: {_token: token, id: id},
success: function (response){
$("#deletePost").html(response.message);
// call your data get function here for disappear record after delele
}
});
return false;
});
});
</script>
Change the route to :
Route::delete('delete/{id}', 'ProfileController#delete')->name('deletePost');
Delete Method are just fine.
There are no need form for delete button
<button type="submit" id="delete" class="btn btn-sm btn-outline-danger py-0 mt-4" data-id="{{ $post->id }}">Удалить</button>
You wrongly access attribute data-id of button delete.
It should be
var id = $(this).data('id');
Or
var id = $(this).attr('data-id');

Retrieve the value of data id through jquery and ajax of one button out of two of button with class upload

I am able to get the value of data id in the second script, However, the code is not able to retrieve the value in the first script.
$(function() {
$(document).on('click', '.upload', function(e) {
e.preventDefault();
$('#uploaddocument').modal('show');
var value = $(this).data('id');
$.ajax({
type: 'POST',
url: 'users_upload.php',
data: {
id: value
},
dataType: 'json',
success: function(response) {
$('.userid').val(response.value);
}
});
});
});
Above script is not working while below one is working
$(function() {
$(document).on('click', '.transact', function(e) {
e.preventDefault();
$('#transaction').modal('show');
var id = $(this).data('id');
$.ajax({
type: 'POST',
url: 'transact.php',
data: {
id: id
},
dataType: 'json',
success: function(response) {
$('#date').html(response.date);
$('#transid').html(response.transaction);
$('#detail').prepend(response.list);
$('#total').html(response.total);
}
});
});
$("#transaction").on("hidden.bs.modal", function() {
$('.prepend_items').remove();
});
});
HTML BUTTONS IS BELOW
<button type="button" class="btn btn-info btn-sm btn-flat upload" data-value="".$row["id"].""><i class="fa fa-upload"></i> Upload</button>
I think the problem is in the button's html line where you are trying to concatenating the value for data element from your php variable.
Try changing it to use single quote for the value and wrap your php variable into curly braces like this
<button type="button" class="btn btn-info btn-sm btn-flat upload" data-value='{$row["id"]}'><i class="fa fa-upload"></i> Upload</button>
Edit:
Just realized, you are getting wrong data element in the first script part. It should be like
var value = $(this).data('value');

Ajax No Refresh when Deleting Data in a Table - Laravel

My problem is I can click the button but it is needed to refresh to delete it . it there something that is making my ajax code a problem why it is refreshing? I want a button when click delete it will automatically delete without refreshing.
my Button
<button type="button" data-client_id="{{ $client->id }}" class="btn-archive btn btn-info">Active</button>
<button type="button" data-client_id="{{ $client->id }}" class="btn-delete fa fa-trash btn btn-danger"></button>
my AJAX
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).on('click','.btn-archive',function(){
var clientID=$(this).attr('data-client_id');
var url='/admin/clients/archTrash/'+clientID;
callAjax(url);
});
$(document).on('click','.btn-delete',function(){
var clientID=$(this).attr('data-client_id');
var url='/admin/clients/archTrashPermanent/'+clientID;
callAjax(url);
});
function callAjax(url){
$.ajax({
url:url,
dataType:'json',
type:'GET',
success:function(response){
console.log(response);
},
error:function(err){
console.log(err);
}
});
}
</script>
Table Structure
`
class Client extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
// Table Name
protected $table = 'clients';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;`
This is what I am doing:
When creating the table, I attach a unique id (user-id in this case) to every row that can be deleted. This is how I do it in blade:
#foreach ($visitors as $visitor)
<tr class="data-user-id-{{$visitor->id}}">
<td class="text-left">
{{$visitor->name}}
</td>
<td class="text-left" data-original-value="11">
{{$visitor->email}}
</td>
<td class="text-left">
<a href="#" data-user-id="{{$visitor->id}}" class="btn btn-small btn-info btn-visitor-enable-disable">
Enable
</a>
</td>
<td class="text-left">
<a href="#" data-user-id="{{$visitor->id}}" class="btn btn-small btn-danger btn-visitor-delete">
X
</a>
</td>
</tr>
#endforeach
Then, in the success method of my .ajax call, I just select that row using the unique id of the row that was deleted and remove the row. This is how I do it.
$(".btn-visitor-delete").on('click',function(e) {
e.preventDefault();
const userId = $(this).attr('data-user-id');
var confirmation = confirm("Are you sure you want to delete this user?");
if (confirmation) {
$.ajax({
type:'GET',
url:'/dashboard/allwhitelistedusers/delete/' + userId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
// data:{user_id: userId},
success:function(data){
//Refresh the grid
$(".data-user-id-"+userId).remove();
alert(data.success);
},
error: function(e){
alert(e.error);
}
});
}
else{
//alert ('no');
return false;
}
});
if u want to delete a record in larval without refreshing the page using ajax so use the below code. I am using this code and its working fine
sending id to ajax in this button class which u can relate to yours id <button class="deleteRecord btn btn-danger" data-id="{{ $party->id }}" >Delete Record</button>
ajax codeis like this with sweet alert
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
var parent = $(this).parent();
swal({
title: "Wait..!",
text: "Are You sure, You want to delete Party?",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
$.ajax({
url: "delete_party/"+id,
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (){
parent.slideUp(300, function () {
parent.closest("tr").remove();
});
},
error: function() {
alert('error');
},
});
} else {
swal("Your Party is safe");
}
});
});
``
You are only doing half the work: Data is sent to the server and it seems everything is working as expected on that site. But then you want to "delete a client" (I assume you expect a table row to disappear) without reloading the page. You need to code this inside the success handler:
success: function(response) {
$('#client-data').remove();
console.log(response);
}
Note this example code will always remove the same element with the ID client-data. You'll probably need to use something like $(this).parent().remove(); as there seem to be multiple delete buttons on your page.

Submiting a form created inside an AJAX response

I have 3 steps to do:
Send some datas via AJAX to a PHP page
Retrieve results and show to user a button with popover which contains a form to save name of user search
Send this form in other PHP page via other AJAX
Points 1 and 2 work fine.
I put popover function in 'complete' section of ajax because popover is created only after results are retrieved.
For point 3, i am unable to catch last form with on.submit. When i click on submit button, it sends form (reload my page).
Here is my code:
HTML part:
<body>
<div class="row" id="results"></div>
</body>
JS part:
/* popover form for save search */
var search_box = '<div id="popover-content" class="hide">'+
'<form id="searchForm" class="form-inline" role="form">'+
'<div class="form-group has-warning">'+
'<input placeholder="Name" class="form-control" maxlength="50" type="text"> '+
'<button type="submit" class="btn btn-warning"><i class="fa fa-check"></i></button>'+
'</div>'+
'</form>'+
'</div>';
/* function to retrieve results and show button with popover */
function searchresults() {
if(select_data !== ''){
$.ajax({
type: "POST",
dataType: 'json',
url: "search.php",
data: { q: select_data },
cache: false,
success: function(data) {
if($.isPlainObject(data) && data.state === 200){
// here is code to retrieve results...
// show button with popover and form
saveButton ='<button type="button" class="btn btn-outline btn-warning btn-lg" data-toggle="popover" data-placement="auto top" data-title="Enter name for your search"><i class="fa fa-star"></i> Save selection</button>'+search_box;
$("div#results").html(saveButton);
}
},
complete: function (jqXHR, status) {
$("[data-toggle=popover]").popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
/* ******** PART DOES NOT WORK ******** */
$("#searchForm").on('submit', function(e) {
e.preventDefault();
alert('passed');
/* code ajax here */
return false;
});
}
});
}return false;
}
How to correct this?
Try to add $(document) .... Let me know if it works I didnt test
$(document).on('submit', 'form#yourFormID', function(e) {
e.preventDefault();
alert('passed');
/* code ajax here */
return false;
});

Categories