Laravel ajax delete request - javascript

so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button

I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>

You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"

Related

How to pass the id of the element user clicked on back to Flask using AJAX

I am trying to work on this website that shows a list of records, and when a user clicks on one of them, he will be navigated to another page that shows the details of the record. The logic behind it is, each 'li' tag has an "id" attribute that is unique, and I can use that id to call API and fetch the detailed info for that record. However, it seems that nothing was passed back to Flask...
HTML code:
<ul class="list-group list-group-flush">
{%for i in range(0,length)%}
<li class="list-group-item" id={{res.value[i].id}}>
<h4 class="itemName">Name:{{res.value[i].name}}</h4>
<p class="itemAssetType">{{res.value[i].assetTypes[0]}}</p>
<p class="itemQualifiedName">{{res.value[i].qualifiedName}}</p>
</li>
{%endfor%}
</ul>
JavaScript code:
$(function(){
$('li').click(function(){
var elementID = this.id
var datatosend = JSON.stringify({"guid":elementID})
$.ajax({
url: '/details',
data: datatosend,
type: 'POST',
success: function(response){
window.location.href = '/details'
console.log(response); //for stackoverflow: this shows None in console
},
error: function(ts) { alert(ts.responseText) }
});
});
});
Flask code:
#app.route('/details',methods=['POST','GET'])
def details():
print (request.json) #this gives: None
print (request.data) #this gives: b''
print (request.args.get("guid")) #this gives: None
return str(request.json)
Just wondering how am I supposed to pass that id into flask?? Why is it always empty???
I am kinda new to the front end, any help is greatly appreciated.
i think you remove this part
success: function(response){
window.location.href = '/details'
console.log(response);
}
because you get some data from server and then you go another page? but your data still stands in previous page!
You need to keep stay in current page and use your data like this:
success: function(response){
console.log(response);
}
$(function () {
$('li').click(function () {
var elementID = this.id;
console.log(this.id)//for stackoverflow: this shows the id as I expected
$.ajax({
url: '/details',
data: { guid: this.id },
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log('failed');
console.log(error);
console.log('element id =======>',elementID)//it is work now!!!
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="xyz">##click me##</li>
<script src="app.js"></script>

Django/Ajax/Jquery running two ajax requests in the same event.

I think I'm really close to getting this working but I need some help with the Jquery as everything works as intended on the second click and beyond. It just doesn't work on the first click.
I'm basically trying to replicate the youtube like and dislike buttons. So you click the thumbs up, it shows +1 and if you click it again it subtracts one. All that logic works until I get into the AJAX and Jquery portion.
I have one ajax request that adds the user to the "liked" ManyToManyField. Then I have one apiview that I'm connecting to just produce the upvote and downvote count, then displaying that into the template.
This all works, but again the first click produces the correct result in the console. The second click produces the "opposite" result in the template and correct result in the console. Then of course if I reload every time I click "up" it works as intended but i'm trying to prevent reloading.
template - Jquery/Ajax
$(".upvote-btn").click(function(e){
e.preventDefault()
var this_ = $(this)
var upvoteToggleUrl = this_.attr("data-href")
var voteCountAPIUrl = "{% url 'streams:vote-count' streampost.pk %}";
$.ajax({
url: upvoteToggleUrl,
method: 'GET',
data: {},
success: function(data){
}, error: function(error){
console.log(error)
console.log("error")
}
})
$.ajax({
url: voteCountAPIUrl,
method: 'GET',
data: {},
success: function(data){
console.log(data.upvotes)
console.log(data.downvotes)
$('.upvote-count').text(data.upvotes);
}, error: function(error){
console.log(error)
console.log("error")
}
})
})
HTML
<p>
Upvotes
<div class="upvote-count" data-href="{% url 'streams:vote-count' streampost.pk %}">
{{ streampost.upvotes.count }}
</div>
<a class="upvote-btn" data-href='{{ streampost.get_api_upvote_url }}'
href='{{ streampost.get_upvote_url }}'>Up</a>
Downvotes {{ streampost.downvotes.count }}
</p>
It seems to me like you want the upvote request to complete first before you retrieve the upvote count. To do that, you need to make the second request in the callback of the first:
$(".upvote-btn").click(function(e){
e.preventDefault()
var this_ = $(this)
var upvoteToggleUrl = this_.attr("data-href")
var voteCountAPIUrl = "{% url 'streams:vote-count' streampost.pk %}";
$.ajax({
url: upvoteToggleUrl,
method: 'GET',
data: {},
success: function(data){
$.ajax({
url: voteCountAPIUrl,
method: 'GET',
data: {},
success: function(data){
console.log(data.upvotes)
console.log(data.downvotes)
$('.upvote-count').text(data.upvotes);
}, error: function(error){
console.log(error)
console.log("error")
}
})
}, error: function(error){
console.log(error)
console.log("error")
}
})
})

Calling [HTTPPost] from Javascript ASP.NET

I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri

Transfer to another page in AJAX call

Hi there is it possible to redirect to another page using ajax? I have this piece of code that I have been working on to try this.
<script type="text/javascript">
$(document.body).on('click', '#btnPrintPrev', function() {
$.ajax({
url: '/pdfdatacal',
data: {
dummydata: "This is a dummy data"
},
});
});
</script>
Now it should be able to carry data to another page and redirect there. Problem is it doesn't.
This is what I am using in my route
Route::get('/pdfdatacal', 'GenerateReportController#pdfdatacal');
Then in the controller
public function pdfdatacal(Request $request) {
return $request->data['dummydata'];
}
My expected result should be a blank page containing the value of dummydata but it doesn't do that in my code. How do I accomplish this?
first your ajax must be something like
$.ajax({
url: '/pdfdatacal',
method: 'post',
data: { dummydata: "This is a dummy data" },
dataType: "JSON",
success: function(response){
console.log(response); // just to check if the data is being passed
// do something you want if ever .
}
});
then in your routes
Route::post('/pdfdatacal', 'GenerateReportController#pdfdatacal');
in your controller
public function pdfdatacal(Request $request) {
return response()->json($request->dummydata);
}
hope it helps ..
Use
window.location.href = "http://yourwebsite.com/pdfdatacal";
In your success call
The idea is that you send data to your controller, it sends back a response, then you redirect from javascript to where you want.
$.ajax({
url: '/pdfdatacal',
type : 'GET',
data : {
dummydata: "This is a dummy data"
},
success : function(data) {
window.location.href = "http://yourwebsite.com/pdfdatacal";
}
});
But if your controller does nothing with the data you send, then you don't need to use ajax at all, simple redirect using javascript.
you could use window.location.assign('your URL here!'); in the success.
success : function(data) {
window.location.assign('your URL here!');
}

How can I pass a Django template context variable to JS function

I am trying to create a simple web link toggle for following or unfollowing a question in my app. I got close using the info My Own Like Button: Django + Ajax -- How? but am not quite there.
My problem is that I cannot dynamically pass question.id to my JS function as the answer in the above link implies. Ie
The hard-wired JS code below DOES work. It passes '12' as a valid param for the view tied to /question/follow-unfollow-inline/. But when I try to replace '12' with a context variable '{{ question.id }}' from the template that calls this JS code, my function passes the string '{{ question.id }}' back to /question/follow-unfollow-inline/ rather than it's value. How do I fix this?
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': '12' },
success: function (e) {
alert('Success!');
}
});
});
});
For now, I'm using #csrf_exempt on my view, but I know I should pass it as data.
You could define it on your anchor tag with data- attribute:
Template:
<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>
Js file:
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': $(this).data('qid') },
success: function (e) {
alert('Success!');
}
});
});
});

Categories

Resources