Search result breaks delete action - laravel

I have a page where I display campaigns. I wont show all the code but the basic structure is like so
#foreach ($campaigns as $campaign)
{!! Form::open(array('class' => 'form-inline delete', 'method' => 'DELETE', 'route' => array('campaigns.destroy', $campaign->id))) !!}
<div class="panel panel-default">
#if (!empty($campaign->campaignName))
<div class="panel-heading campaignPanelHeading">
<h4>{{ $campaign->campaignName }}</h4>
</div>
<div class="panel-footer">
<a href="{{ route('campaigns.destroy', $campaign->id) }}" class="btn btn-danger" id="deleteCampaign" data-method="delete" data-token="{{ csrf_token() }}">
Delete
</a>
</div>
#endif
</div>
{!! Form::close() !!}
#endforeach
If I try to delete an item, the following is triggered.
$("#deleteCampaign").on("submit", function(){
return confirm("Do you want to delete this item?");
});
Now on this page where I display all campaigns I have a search box. You start typing and an autocomplete list displays. When you select an option, this is triggered
select: function (event, ui) {
$.ajax({
url: "/returnDataForCampaigns",
type: "GET",
datatype: "html",
data: {
value : ui.item.value
},
success: function(data) {
$('.container').html(data.html);
$('.selectpicker').select2();
}
});
},
This essentially calls a function which gets the selected Campaign, and injects it into the following partial
#if(!empty($campaign))
{!! Form::open(array('class' => 'form-inline delete', 'method' => 'DELETE', 'route' => array('campaigns.destroy', $campaign->id))) !!}
<div class="panel panel-default">
#if (!empty($campaign->campaignName))
<div class="panel-heading campaignPanelHeading">
<h4>{{ $campaign->campaignName }}</h4>
</div>
<div class="panel-footer">
<a href="{{ route('campaigns.destroy', $campaign->id) }}" class="btn btn-danger" id="deleteCampaign" data-method="delete" data-token="{{ csrf_token() }}">
<span class="glyphicon" aria-hidden="true"></span>
Delete
</a>
</div>
#endif
</div>
{!! Form::close() !!}
#endif
Finally, this data is then injected into the page's container. Now this all works fine. When I check the source after it has been injected everything looks correct.
I have 2 other buttons which I removed above which show or edit the campaign, these work fine. The thing that is not working is the delete button for the searched campaign. For some reason when I click this it goes to the campaigns show page. This button works when I display all campaigns, its only when search is performed it does not work.
I have checked the code for the delete button for when all campaigns are displayed vs a searched campaign. Everything is the same apart from the Javascript which has been applied to the delete button when all campaigns are shown as well as some hidden inputs
<a data-token="dsfsd" data-method="delete" id="deleteCampaign" class="btn btn-danger" onclick=" if ($(this).hasClass('action_confirm')) { if(confirm($(this).data('message') || "Are you sure you want to do this?")) { $(this).find("form").submit(); } } else { $(this).find("form").submit(); }">
Delete
<form style="display:none" method="POST" action="http://localhost:8000/campaigns/43">
<input type="hidden" value="delete" name="_method">
<input type="hidden" value="dsfsd" name="_token">
</form>
</a>
This is a searched button
<a data-token="dsfsd" data-method="delete" id="deleteCampaign" class="btn btn-danger" href="http://localhost:8000/campaigns/9">
Delete
</a>
So my main question is why this may be happening? I would also like to try and find out why the searched version of the delete button also takes you to the show page?
Any advice appreciated
Thanks

Try this for your delete jquery code:
$(document).on("submit", "#deleteCampaign", function(e){
e.preventDefault();
return confirm("Do you want to delete this item?");
});
Its because you are adding content after DOM load.

Related

Delete nested object from array in Vue

trying to delete a nested object from an array. I've done some research and came across an example similar to mine, Vue.js Remove a Nested Object from Array.
However my issue is a slight more complex as I am trying to delete the object with ajax request. Essentially my engagement array contains nested objects of questions
so here is how I am displaying the list of questions for the engagement
<div v-for="question in engagement.questions" :key="question.id">
<div>
<div ">
{{ question.question }}
</div>
<div >
<span>Answered: </span>
<input type="checkbox" v-model="question.answered">
</div>
</div>
</div>
this is the button that will delete the question
<b-btn #click="deleteQuestion(engagement, question)">Confirm</b-btn>
and this is method that dispatches to the store
deleteQuestion(engagement, question) {
this.$store.dispatch('deleteQuestion', id)
.then(() => {
this.$router.push({path: '/engagement/' +this.engagement.id , query: {alert: 'The Question Was Succesfully Deleted'}});
})
},
and this is the store method
deleteQuestion(context, id) {
axios.delete('/questions/' + id)
.then(response => {
context.commit('deleteQuestion', id)
})
.catch(error => {
console.log(error)
})
},
Right now my alarm is getting “id is not defined” although I have other variations of this code where I will get a 500 internal server error which makes me think that I am not properly capturing the id of the question so it knows which one to delete…
below is the alarm I am getting in the console. I also did which is what the first arrow is pointing to for the observer
console.log(question)
the issue was that the b-model element that contained the #click="deleteQuestion" was outside of the div that contained the v-for so when I would click on the b-modal button it wasn't grabbing the id of the question. So I moved the b-modal to that div and it worked. Thank you for the help.
<div class="card mb-3" v-for="(question, index) in engagement.questions" :key="index">
<div class="card-header">
<div class="h6 m-0 justify-content-between d-flex">
<router-link class="btn btn-sm btn-primary mr-3" to="#" ><i class="far fa-edit mr-2"></i>Edit</router-link>
<b-btn class="outline-secondary" size="sm" v-b-modal.myQuestion><i class="fas fa-trash"></i><span class="ml-2">Delete</span></b-btn>
</div>
</div>
<div class="card-body bg-light d-flex justify-content-between">
<div class="h4 mr-5 text-left">
{{ question.question }}
</div>
<div class="ml-5 d-flex align-self-center">
<span class="font-weight-bold mr-2">Answered: </span>
<input class="mt-2" type="checkbox" v-model="question.answered">
</div>
</div>
<!-- this is the modal for deleting a question -->
<b-modal id="myQuestion" ref="myModalQuestion" hide-footer title="Delete Question">
<div class="d-block text-left">
<h5>Are you sure you want to delete question?</h5>
<br>
<p><strong>*Warning:</strong> Can not be undone once deleted.</p>
</div>
<div class="d-flex">
<b-btn class="mt-3" variant="danger" #click="hideModal">Cancel</b-btn>
<b-btn class="mt-3 ml-auto" variant="outline-success" #click="deleteQuestion(engagement, question.id)">Confirm</b-btn>
</div>
</b-modal>
</div>

Laravel 5.5 redirect to url with anchor and with data

In my footer.blade.php i have the following code about subscribing
<!--Subscription-->
#if(Session::has('success'))
<div class="form-group has-success">
<input class="form-control form-control-success" type="text" id="input-success">
<div class="form-control-feedback">{{ Session::get('success') }}</div>
</div>
#elseif(Session::has('failed'))
<div class="form-group has-danger">
<input class="form-control form-control-danger" type="text" id="input-danger">
<div class="form-control-feedback">{{ Session::get('failed') }}</div>
</div>
#else
{!! Form::open(['route'=>'subscribe.store', 'class' => 'subscribe-form', 'novalidate' => 'novalidate']) !!}
<div class="clearfix">
<div class="input-group input-light">
{!! Form::email('email', old('email'), ['class'=>'form-control ', 'placeholder'=>'Your e-mail']) !!}
<span class="input-group-addon"><i class="icon-mail"></i></span>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" name="b_c7103e2c981361a6639545bd5_1194bb7544" tabindex="-1">
</div>
<button class="btn btn-primary" type="submit">
<i class="icon-check"></i>
</button>
</div>
{!! Form::close() !!}
<span class="form-text text-sm text-white opacity-50">Subscribe to our Newsletter to receive early discount offers, latest news, sales and promo information.</span>
#endif
In my controller i have the following function which receives the email and subscribes it correctly
public function registerNewsletter( Request $request )
{
$email = $request->input( 'email' );
$isSub = Newsletter::hasMember($email);
if($isSub) {
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.');
} else {
Newsletter::subscribe($email);
return redirect()->back()->with('success', 'You have been registered in our Newsletter system.');
}
}
Although everything works good, i would like to page to scroll down to the footer because now it reloads and stays on top.
I've found the return redirect()->to(app('url')->previous(). '#hashid');
But there is no way to pass data among the id of the footer.
And also i've tried
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.'). '#sitefooter';
and it didn't scroll down.
Any idea or workaround?
I've just tested this code. It will redirect you, scroll down to the anchor and will pass the data:
session()->flash('someVariable', $someData);
return redirect(url()->previous() . '#hashid');
To get stored data:
$someData = session('someVariable');
Or in a view:
{{ session('someVariable') }}

Passing data to textarea inside bootstrap modal that uses TINYMCE WYSIWYG

I am creating a blog now and I want to update a comment,
I want to pass the current data of the comment to the textarea that uses TINYMCE WYSIWYG editor.
The problem is if I use tinymce for the textarea the current data will NOT show on the textarea.
here is how I do it
This is the button that will trigger the modal:
<button type="button" class="btn btn-success btn-xs" data-toggle="modal" data-target="#myModal" data-id="{{ $comment->id }}" data-comment=" {{ $comment->comment }}"><i class="fa fa-pencil"></i></button>
This is the modal
<!--UPDATE COMMENT Modal -->
<div class="modal fade modal-md" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content modal-success">
{{ Form::open(['route' => ['comments.update'], 'method' => 'PUT']) }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title"><b>Update Comment </b></h5>
</div>
<div class="modal-body">
<div id="comment-form" class="">
<div class="row">
<div class="col-md-12">
{!! Form::hidden('id', '', ['id' => 'comment-id']) !!}
{{ Form::textarea('comment', '', ['id'=>'comment-comment','class' => 'form-control', 'rows' => '3']) }}
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success"><b>Update</b></button>
<button type="button" class="btn btn-default" data-dismiss="modal"> <b>Cancel</b></button>
</div>
{{ Form::close() }}
</div>
</div>
</div>
here is my js:
<script type="text/javascript" charset="utf-8">
tinymce.init({
selector: 'textarea',
menubar: false,
toolbar: false,
statusbar: false,
height: 10
});
<!--UPDATE COMMENT MODAL-->
$(function() {
$('#myModal').on("show.bs.modal", function (e) {
$("#comment-comment").val($(e.relatedTarget).data('comment'));
$("#comment-id").val($(e.relatedTarget).data('id'));
});
});
// Prevent bootstrap dialog from blocking focusin
$(document).on('focusin', function(e) {
if ($(e.target).closest(".mce-window").length) {
e.stopImmediatePropagation();
}
});
$('#open').click(function() {
$("#dialog").dialog({
width: 800,
modal: true
});
});
</script>
{!! Form::hidden('id', $data->id , ['id' => 'comment-id']) !!}
{{ Form::textarea('comment', $data->coment, ['id'=>'comment-comment','class' => 'form-control', 'rows' => '3']) }}
If you are using form open that case you need to specify a value like "$data->coment". And if you are using Form model that case it's not required to specify any value just need to add null. Check below link.
https://laravel.com/docs/4.2/html#form-model-binding

Laravel href with POST

I'm trying to pass some data to my controller with an action href. I don't know why, but laravel passes the data with GET method, but instead of GET I need a POST. I don't really understand why laravel does that and coulnd't find an answer. I did that multiple times and my syntax seems to be correct. Can somebody have a look over it?
Blade:
<td>
#foreach($products as $product)
<a href="{{ action('ProductsController#delete', $product->id ) }}">
<span class="glyphicon glyphicon-trash"></span></a>
{{ $product->name }},
#endforeach
</td>
My Route:
Route::post('delete', ['as' => 'delete', 'uses' => 'ProductController#delete']);
In my Controller is just a:
public function delete()
{
return 'hello'; // just testing if it works
}
Error:
MethodNotAllowedHttpException in RouteCollection.php line 219....
I know it's a get method, cause if I'm trying to pass the data to my controller, my URL looks like this:
blabla.../products/delete?10
Is anything wrong with my syntax? I can't really see why it uses the get method.
I also tried a: data-method="post" insite of my <a> tag but this haven't worked either.
Thanks for taking time.
When you make a link with an anchor like <a href=example.com> your method will always be GET. This is like opening a URL in your browser, you make a GET request.
You should use a form to make that POST request to the delete method of the controller. Assuming you have the Illuminate HTML package for HTML and forms, you could do this:
{!! Form::open(['method' => 'DELETE', 'route' => $route]) !!}
{!! Form::submit('delete', ['onclick' => 'return confirm("Are you sure?");']) !!}
{!! Form::close() !!}
EDIT:
With a button tag:
{!! Form::open(['method' => 'DELETE', 'route' => $route]) !!}
<button type="submit"><i class="glyphicon glyphicon-remove"></i>Delete</button>
{!! Form::close() !!}
Here's your problem:
<a href="{{ action('ProductsController#delete', $product->id ) }}">
Anchor tags are always submitted over GET. It's a HTTP built in and is not Laravel specific.
POST is used when a form is submitted that specifies the POST HTTP Verb or the HTTP method is invoked by an AJAX request that specifies POST as the HTTP Verb.
Instead consider a submit type button in a form that submits what you need.
<td>
#foreach($products as $product)
<form method="POST" action="{{ route('delete') }}">
<input type="hidden" name="product_id" value="{{ $product->id }}">
{!! csrf_field() !!}
<button type="submit" class="btn">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
{{ $product->name }},
#endforeach
</td>
And then in your controller:
public function delete()
{
// 'Die Dump' all of the input from the form / request
dd( request()->input()->all() );
// 'Die Dump' the specific input from the form
dd( request()->input('product_id') );
}
You will begin to see how GET and POST requests differ in sending of key/value pairs.
For more information:
http://www.tutorialspoint.com/http/http_methods.htm
Best for laravel 7. First define the form with given form id.
#auth
<form id="logout-form" action="{{ route('logout') }}" method="POST"
style="display: none;">
#csrf
</form>
#endauth
Then you can use the anchor tag for logout operation.In background,javascript working.Wherever the logout was fire then action to given form method of post method and logout route was working.
<a class="nav-link dropdown-toggle text-muted waves-effect waves-dark"
href="{{ route('logout') }}" onclick="event.preventDefault();document.getElementById('logout-form').submit();"
id="2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="mdi mdi-logout"></i>
</a>
Most benefit is the form was not loaded unnecesory.If the user was
logged in so far its load otherwise not
Laravel 7
By jQuery:
<form id="form" action="{{route('route_name')}}" method="POST">#csrf</form>
By JS:
<form id="form" action="{{route('route_name')}}" method="POST">#csrf</form>

how to clear cache search results from server in laravel 5?

i'm new to laravel and i've created a simple search to query my database.
the problem is that everytime i refresh the page all the results from my last search are still showing. also when i load the page after couple of days,results are the. it seems like there is a cache working which i dont know about.
i want to clear these results/cache without clearing the cache for all my app.
Here is the code.
in my routs file:
Route::get('men',function()
{
$query=Request::get('q');
if ($query)
{
$users= \App\User::where('first_name','LIKE',"%$query%")
->orwhere('last_name','LIKE',"%$query%")
->get();
}
else
{
}
return view('page')->withUsers($users);
});
My View:(page.blade.php)
{!! Form::open(['method' => 'GET']) !!}
<div class="container col-lg-6 form-group" style="float:none;margin:auto">
<div class="input-group">
{!! Form::input('search','q', null, ['placeholder' => 'search' ,
'class' => 'form-control', 'autocomplete' => 'off']) !!}
<div class="input-group-btn">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Search</button>
</div><!-- /btn-group -->
</div><!-- /input-group -->
</div>
{!! Form::close() !!}
<div class="container col-lg-6" style="float:none;margin:auto">
#if ($users->count())
<ul class="list-group" style="list-style-type: none;">
#foreach($users as $user)
<li class="list-group-item" style="cursor:pointer">
{{$user->first_name}} {{$user->last_name}}
</li>
#endforeach
</ul>
#else
<h3>Sorry,no users found...</h3>
#endif
</div>
</div> <!--container-->
any Ideas ??..
i've managed to clear last query string in the browser addess bar with:
within my view:
<head>
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
</script>
</head>
whenever i refresh the page it clears up the results since nothing is coming from the server.

Resources