trying to get property on non object in laravel using ajax - php

I'm coding a simple comment section on my project and from now it's working pretty good except at the moment of edit or delete a fresh new comment. I can create, edit and delete all the comments using ajax but to delete or edit a new comment i have to refresh the page. Reason? Trying to get property of non object. Looks like i can't get the comment id of new comments, to get those id's i have to refresh the page..
This is my ajax.
Create a new comment:
$('.send').click(function(e){
e.preventDefault();
var dataSerialize = $('#add-comment').serialize();
var $btn = $(this).button('loading');
$.ajax({
method: 'post',
url: urlPostComment,
data: dataSerialize,
dataType: 'json',
success: function (data) {
console.log(data);
if( data.success )
{
$('#post-comments').append(
"<section class='comment-list"+data.id+"'><article class='row'><div class='col-md-3 col-sm-3 hidden-xs'><figure class='thumbnail'><img class='img-responsive' src='/uploads/avatars/"+data.picture+"' /></figure></div><div class='col-md-8 col-sm-8'><div class='panel panel-default arrow left'><div class='panel-body'><header class='text-left'><div class='comment-user'><i class='fa fa-user'></i> "+data.name+" "+data.lastname+" <time class='comment-date p-l-10'><i class='fa fa-clock-o'></i> "+data.timestamp+"</time></div></header><div id='comment-post' data-commentid='"+data.id+"'><p id='display-comment' class='store-comment p-t-10'>"+data.comment+"</p></div></div><div class='panel-footer list-inline comment-footer'><a href='#' data-toggle='modal' data-target='edit-comment' class='edit-comment' data-id='"+data.id+"' data-name='"+data.comment+"'>Editar</a> <a href='#' data-toggle='modal' data-target='delete-comment'class='delete-comment' data-id='"+data.id+"' data-name='"+data.comment+"'>Eliminar</a></div></div></div></article></section>"
);
toastr.success('Comment created.', '', {timeOut: 7000})
$('#comment-new').val('');
}
else {
toastr.warning(" "+ data.message +" ", '', {timeOut: 7000})
}
},
error: function () {
toastr.warning('Message couldn't be sent, Try again.', '', {timeOut: 7000})
},
complete: function () {
$btn.button('reset');
}
});
});
My update Ajax:
var commentId = 0;
var divcomment = null;
$('body').on('click', '.edit-comment', function(event){
event.preventDefault();
divcomment = this.parentNode.parentNode;
commentId = $("#comment-post",event.target.parentNode.parentNode).data('commentid');
var commentBody = $(divcomment).find('#display-comment').text();
$('#comment').val(commentBody);
$('#edit-comment').modal();
});
$('body').on('click', '#modal-save', function(){
var $btn = $(this).button('loading');
var comment = $('#comment').val();
$(this).button('loading');
$.ajax({
method: 'PUT',
url: urlEdit,
data: {
comment: comment,
commentId: commentId,
_token: token,
_method: 'PUT',
},
dataType: 'json'
})
.done(function (msg){
if (msg.success === true) {
$(divcomment).find('#display-comment').text(comment);
}
$btn.button('reset');
$('#edit-comment').modal('hide');
toastr.success('Comentario editado.', '', {timeOut: 7000})
});
});
And my Delete Ajax code:
$('body').on('click', '.delete-comment', function(){
$('#delete-comment').modal();
$('#comment-value').text($(this).data('id'));
});
$('body').on('click', '#comment-delete', function(e){
e.preventDefault();
var $btn = $(this).button('loading');
$(this).button('loading');
$.ajax({
type: 'delete',
url: urlDelete,
data:{
'id': $('#comment-value').text(),
'_method': 'delete',
'_token': token
}
})
.done(function(response){
$('.comment-list' + $('#comment-value').text()).remove();
$('#delete-comment').modal('hide');
toastr.success(" "+response.success+" ", '', {timeOut: 7000})
$btn.button('reset');
})
.fail(function(){
$btn.button('reset');
$('#delete-comment').modal('hide');
toastr.warning('Message couldn't be sent, try again.', '', {timeOut:
7000})
})
});
UPDATE:
Variables:
var token = '{{ Session::token() }}';
var urlPostComment = '{{ url('comments/' .$post->id) }}';
var urlEdit = '{{ url('comments/update') }}';
var urlDelete = '{{ url('comments/' .$comment->id) }}';
About this last one var urlDelete = '{{ url('comments/' .$comment->id) }}'; i don't know why if post doesn't have a comment it gaves me an error "undefined variable id" or "undefined variable comment"
Controller Logic:
public function store(Request $request, $post_id)
{
if(!$request->has('comment') || empty($request->comment))
{
return response()->json([
'message' => 'No puedes enviar un comentario vacĂ­o.',
'success' => false
]);
}
$post = Post::find($post_id);
$comment = new Comment();
$comment->comment = $request->comment;
$comment->approved = true;
$comment->user_id = auth()->id();
$comment->user->profilepic = $comment->user->profilepic;
$comment->post_id = $post_id;
$comment->save();
return response()->json([
'comment' => $comment->comment,
'user_id' => $comment->user_id,
'post_id' => $comment->post_id,
'picture' => $comment->user->profilepic,
'name' => $comment->user->name,
'lastname' => $comment->user->last_name,
'timestamp' => $comment->created_at->diffForHumans(),
'post_slug' => $post->slug,
'success' => true
]);
}
public function update(Request $request)
{
$this->validate($request, [
'comment' => 'required'
]);
$comment = Comment::find($request['commentId']);
if (Auth::user() != $comment->user) {
return response()->json([
'errorupdate' => 'No hemos podido actualizar tu comentario, intenta nuevamente',
'success' => false], 200);
}
$comment->comment = $request['comment'];
$comment->save();
return response()->json(['new_comment' => $comment->comment, 'success' => true], 200);
}
public function destroy(Request $req)
{
$response = [];
$comment = new Comment;
$comment = Comment::find($req->id);
if (Auth::user() != $comment->user) {
return redirect()->back();
}
if ($comment->delete()) {
$response['success'] = 'Comentario eliminado.';
$response['subject'] = $comment;
}
return response()->json($response);
}

Related

How to send JSON value to tui calendar using ajax

I am using Tui calendar https://ui.toast.com/tui-calendar and i have already get booking date related to room id in ajax response but i want to send json value to tui calendar using ajax response i don't know how can i show json data inside calendar please help me how can i resolve that ? thank u.
please check error
https://flareapp.io/share/bP9YaMMP
BookingController
public function getBookingSlot(Request $request){
$userBookings = Booking::where('room_id',$request->room_id)-
>where('booking_status',1)-
>get();
foreach($userBookings as $booking){
$events [] = [
'id' => $booking->id,
'calendarId' => $booking->id,
'title' => 'Booked',
'category' => 'time',
'dueDateClass' => '',
'start' => $booking->start_datetime,
'end' => $booking->end_datetime,
];
}
return \Response::json([
'events' => $events
]);
}
script
var Calendar = tui.Calendar;
var calendar = new Calendar('#calendar', {
defaultView: 'month',
taskView: false,
useCreationPopup: false,
useDetailPopup: true,
allDaySlot: false,
droppable: false,
template: {
monthDayname: function(dayname) {
return '<span class="calendar-week-dayname-name">' + dayname.label + '</span>';
}
}
});
document.getElementById('my-today-button').addEventListener('click', function() {
calendar.today();
});
document.getElementById('my-next-button').addEventListener('click', function() {
calendar.next();
});
document.getElementById('my-prev-button').addEventListener('click', function() {
calendar.prev();
});
document.getElementById('weekView').addEventListener('click', function() {
calendar.changeView('week', true);
});
document.getElementById('monthView').addEventListener('click', function() {
calendar.changeView('month', true);
});
$(".butonSubmit").click(function(){
let room_id = $(".carousel-item.active .room_id").val();
$.ajax({
url: "{{route('get-booking-slot')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
room_id:room_id,
},
success:function(response){
var $bookingUser = #json($events);
},
error: function(response) {
console.log(error);
},
});
});
calendar.createSchedules(
events= $bookingUser
);
calendar.on('beforeUpdateSchedule', function(event) {
var schedule = event.schedule;
var changes = event.changes;
calendar.updateSchedule(schedule.id, schedule.calendarId, changes);
});

Remove previous data when executing AJAX request multiple times using ajax

I am using Toast tui calendar https://nhn.github.io/tui.calendar/latest/ and I have an issue with ajax calling. It works correct except one thing, when I try to get data with the same option more than one times returns the new response but also still return the data of the previous response. please help me how can i resolve that thank u.
I think that there is something that I've missed.
BookingController
public function getBookingSlot(Request $request){
$userBookings = Booking::where('room_id',$request->room_id)->where('booking_status',1)->get();
foreach($userBookings as $booking){
$events [] = [
'id' => $booking->id,
'calendarId' => $booking->id,
'title' => 'Booked',
'category' => 'time',
'dueDateClass' => '',
'start' => $booking->start_datetime,
'end' => $booking->end_datetime,
];
}
return \Response::json([
'events' => $events ?? null
]);
}
Html view
<div class="card mb-5 ">
<div id="calendar" style="height: 800px;"></div>
</div>
Script
<script type="text/javascript">
var Calendar = tui.Calendar;
var calendar = new Calendar('#calendar', {
defaultView: 'month',
taskView: false,
useCreationPopup: false,
useDetailPopup: true,
allDaySlot: false,
droppable: false,
template: {
monthDayname: function(dayname) {
return '<span class="calendar-week-dayname-name">' + dayname.label + '</span>';
}
}
});
document.getElementById('my-today-button').addEventListener('click', function() {
calendar.today();
});
document.getElementById('my-next-button').addEventListener('click', function() {
calendar.next();
});
document.getElementById('my-prev-button').addEventListener('click', function() {
calendar.prev();
});
document.getElementById('weekView').addEventListener('click', function() {
calendar.changeView('week', true);
});
document.getElementById('monthView').addEventListener('click', function() {
calendar.changeView('month', true);
});
$(".butonSubmit").click(function(){
let room_id = $(".carousel-item.active .room_id").val();
$.ajax({
url: "{{route('get-booking-slot')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
room_id:room_id,
},
success:function(response){
calendar.createSchedules(
result = JSON.parse(JSON.stringify(response.events))
);
console.log(result);
},
error: function(response) {
console.log(error);
},
});
});
calendar.on('beforeUpdateSchedule', function(event) {
var schedule = event.schedule;
var changes = event.changes;
calendar.updateSchedule(schedule.id, schedule.calendarId, changes);
});

How to refresh as well as savstate of datatable when status is updated in laravel

In my project, I want to refresh as well as savestate of the data table (datatable saveState) while updating the status in Laravel, the status is getting updated into the database but the data table is not refreshed nor the savestate is done, I am not able to understand where I am doing the mistake, below here is the code that I am using
Route
Route::get('/list-category', [CategoryController::class, 'listcategory'])->name('listcategory');
Controller
public function changestatus($id){
$cat_statuss = Category::find($id);
if (!empty($cat_statuss)) {
// dd('Record is available.');
$cat_status = Category::where('id',$id)->first();
$status = $cat_status->status;
$statuss = 'active';
if($status=='active'){
$statuss = 'inactive';
}else{
$statuss = 'active';
}
$cat_status->status = $statuss;
if($cat_status->update()){
// return redirect('/list-category')->with('status_change','Updated Successfully.');
return response()->json(array(
'success' => true,
'message'=> 'Status Changed Successfully.',
'errors' => false
), 200);
}else{
return response()->json(array(
'success' => false,
'errors' => array('status_change_err'=>'Oops! There is an error.')
), 400);
}
}else{
// dd('Record is not available.');
return response()->json(array(
'success' => false,
'errors' => array('status_change_err'=>'Category Not Found.')
), 404);
}
}
List Category Page
<td>
<?php if($cate->status=='active'){ echo 'Active'; }else{ echo 'Inactive'; } ?>
</td>
<script>
var table = $('#example2').DataTable( { stateSave: true } );
$(document).on('click','.status_button',function(e){
e.preventDefault();
var statusid = $(this).attr('data-id');
url = $(this).attr('href');
$.ajax({
url:url,
method:"GET",
data:{"_token": "{{ csrf_token() }}"},
dataType:'json',
success:function(response){
// console.log(response);
swal({
title: "Added",
text: response.message,
type: "success"
}, function () {
});
},
error: function(response) {
swal("Error", response.responseJSON.errors.status_change_err, "error");
}
});
});
</script>

How to validate input data using ajax in laravel

testAjax function inside PostsController class:
public function testAjax(Request $request)
{
$name = $request->input('name');
$validator = Validator::make($request->all(), ['name' => 'required']);
if ($validator->fails()){
$errors = $validator->errors();
echo $errors;
}
else{
echo "welcome ". $name;
}
}
inside web.php file:
Route::get('/home' , function(){
return view('ajaxForm');
});
Route::post('/verifydata', 'PostsController#testAjax');
ajaxForm.blade.php:
<script src="{{ asset('public/js/jquery.js') }}"></script>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Name<input type="text" name="name" id="name">
<input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
}
});
/**Ajax code ends**/
});
});
</script>
So when click on submit button by entering some data then the output message(echo "welcome ". $name;) is printing. But when I click on submit button with empty text box then it does not print the error message from the controller and it throws a 422 (Unprocessable Entity) error in console. Why my approach is wrong here and how can I print the error message then. Please help. Thank you in advance.
Your approach is actually not wrong, it's just, you need to catch the error response on your ajax request. Whereas, when Laravel validation fails, it throws an Error 422 (Unprocessable Entity) with corresponding error messages.
/**Ajax code**/
$.ajax({
type: "post",
url: "{{ url('/verifydata') }}",
data: {name: name, _token: token},
dataType: 'json', // let's set the expected response format
success: function(data){
//console.log(data);
$('#success_message').fadeIn().html(data.message);
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
$('#success_message').fadeIn().html(err.responseJSON.message);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
}
}
});
/**Ajax code ends**/
On your controller
public function testAjax(Request $request)
{
// this will automatically return a 422 error response when request is invalid
$this->validate($request, ['name' => 'required']);
// below is executed when request is valid
$name = $request->name;
return response()->json([
'message' => "Welcome $name"
]);
}
Here's a better approach to validation:
In your controller:
public function testAjax(Request $request)
{
$this->validate($request, [ 'name' => 'required' ]);
return response("welcome ". $request->input('name'));
}
The framework then will create a validator for you and validate the request. It will throw a ValidationException if it fails validation.
Assuming you have not overriden how the validation exception is rendered here's the default code the built-in exception handler will run
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput($request->input())->withErrors($errors);
}
Again this is handled for you by the framework.
On the client side you should be able to do:
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
},
error: function (xhr) {
if (xhr.status == 422) {
var errors = JSON.parse(xhr.responseText);
if (errors.name) {
alert('Name is required'); // and so on
}
}
}
});
/**Ajax code ends**/
});
});
</script>
best way for handle in php controller :
$validator = \Validator::make($request->all(), [
'footballername' => 'required',
'club' => 'required',
'country' => 'required',
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
return response()->json(['success'=>'Record is successfully added']);
The code for form validation in Vannilla Javascript
const form_data = new FormData(document.querySelector('#form_data'));
fetch("{{route('url')}}", {
'method': 'post',
body: form_data,
}).then(async response => {
if (response.ok) {
window.location.reload();
}
const errors = await response.json();
var html = '<ul>';
for (let [key, error] of Object.entries(errors)) {
for (e in error) {
html += `<li>${error[e]}</li>`;
}
}
html += '</ul>';
//append html to some div
throw new Error("error");
})
.catch((error) => {
console.log(error)
});
Controller
use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
'file' => 'image|mimes:jpeg,png,jpg|max:1024',
'field1' => 'required',
'field2' => 'required'
];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
session()->flash('flash', ['status' => 'status', 'message' => 'message']);
Jquery Code:
let first_name= $('.first_name').val();
let last_name= $('.last_name').val();
let email= $('.email').val();
let subject= $('.subject').val();
let message= $('.message').val();
$('.show-message').empty();
console.log('clicked');
$.ajax({
type : 'POST',
url : '{{route("contact-submit")}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
first_name,
last_name,
email,
subject,
message,
},
success: function(data) {
console.log('data',data);
$('.show-message').html('Form Submitted');
},
error : function(data,data2,data3)
{
let response=data.responseJSON;
let all_errors=response.errors;
console.log('all_errors',all_errors);
$.each(all_errors,function(key,value){
$('.show-message').append(`<p>${value}</p>`);
});
}
});
Controller Code:
$validator=Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email',
'subject'=>'required',
'message'=>'required',
]);
if($validator->fails())
{
return response()->json([
'success'=>false,
'errors'=>($validator->getMessageBag()->toArray()),
],400);
}
return response()->json([
'success'=>true,
],200);
See More Details at: https://impulsivecode.com/validate-input-data-using-ajax-in-laravel/

Ajax request showing error message while successfull updation laravel

In the laravel update form The code for controller is:
public function edit(){
$inputValue = [
'id' => Input::get('id'),
'name' => Input::get('name'),
'parent_id' => Input::get('parent_id'),
'color' => Input::get('color'),
'description' => Input::get('notes')
];
$validator = \Validator::make( $inputValue, \Resource::getEditFolderRules() );
// Validate the input and return correct response
if ($validator->fails()){
return Response::json([
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
]);
}
$resource = $this->repo->updateFolderBasicDetail($inputValue);
return Response::json([
'success' => true,
'url' => \URL::route('folder-detail', $inputValue['id'])
]);
}
and js is:
<script type="text/javascript">
$(function(){
$("#edit-folder").on('submit', function(e){
e.preventDefault();
if($("#edit-folder").valid() == true){
var description = CKEDITOR.instances.edit_folder_ckeditor1.getData();
$('#notes').val(description);
$.ajax({
url: "{{ URL::to('folder/edit') }}",
type: "POST",
data: $( this ).serialize(),
dataType: "json",
success:function(data) {
var errorString = '<ul class="msg msg_unsuccess">';
var success = 'Folder is updated.';
errorString += '<li>' + success + '</li>';
errorString += '</ul>';
$('#sucessmsg').html(errorString).delay(3000).fadeOut();
$('.modal-content').delay(3000).fadeOut();
$('.fade').delay(3000).fadeOut();
},
error:function(data) {
var errorString = '<ul class="msg msg_success">';
var error = 'Folder is not updated.';
errorString += '<li>' + error + '</li>';
errorString += '</ul>';
$('#sucessmsg').html(errorString).delay(3000).fadeOut();
$('.modal-content').delay(3000).fadeOut();
$('.fade').delay(3000).fadeOut();
setTimeout(function(){location.reload();},3000);
}
});
}
});
});
</script>
but when I update the folder it is updating and message is displaying from error:function.
don't understand where I am wrong Please help me out.
I use AJAX in Laravel 5.2 with routes, created variable url and variable token(if need), in php file where views, before included script
<script>
var token = '{{ Session::token()}}';
var url = '{{ route('select_cafe') }}';
</script>
<script src="{{asset('/script/select_cafe.js')}}" ></script>

Categories