Ajax request showing error message while successfull updation laravel - php

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>

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>

trying to get property on non object in laravel using ajax

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);
}

How to set Ajax URL dynamically?

I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension

Categories