Ajax in Django : url not found - ajax

I am coding a small Django project where an user can select an object and save it in a database. I am trying to implement an Ajax call on a button to delete this object if necessary.
I am doing it step by step, debugging with the console.
my urls:
app_name = 'register'
urlpatterns = [
path('<int:user_id>/', views.account, name='account'),
path('/delete/', views.delete, name='delete'),
]
my view.py:
def delete(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
print(product)
data['success'] = True
return JsonResponse(data)
my ajax.js:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
console.log('ok till this point')
$.ajax({
url: '{% url "register/delete" %}',
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});
My view isn't doing much for now but I haven't any knowledge about Ajax and I am doing it one step at a time.
This is the error I get in the console:
jquery.min.js:2 POST http://127.0.0.1:8000/register/6/%7B%%20url%20%22register/delete%22%20%%7D 404 (Not Found)
As far as I understand, Ajax can't find my url: '{% url "register/delete" %}'.
I have tried '{% url "register:delete" %}' with no luck either.

I found an answer after some tweaking, I defined my url before the Ajax call and then pass it in it:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var product = 'coca-cola'
var url = '/register/delete/'
console.log( url)
$.ajax({
url: url,
type: "POST",
data:{
'product':product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
console.log('working fine')
}
});
});

Also you can add just the string of url to "url" parameter without characters {% url %}. Maybe you copied the code from pattern Django and added it to JS-file. So it does not work.

Related

Laravel 8 Method Not Allowed 405 Ajax CRUD

I fixed my csrf
I fixed my route , route clear too
but still error show up .
I'm doing ajax form in modal :
My Route
Route::post('increp/store',[\App\Http\Controllers\IncrepController::class,'store'])->name('increp.store');
My ajax
// Create article Ajax request.
$('#submit_increp').click(function(e) {
e.preventDefault();
var data = $("#main-form").serialize();
$.ajax({
url: "{{ route('increp.store') }}",
type: 'POST',
data: data,
dataType: 'json',
beforeSend:function(){
$(document).find('span.error-text').text('');
},
success: function(result) {
if(result.errors) {
console.log(result.errors);
$('.alert-danger').html('');
$.each(result.errors, function(key, val) {
$('span.'+key+'_error').text(val[0]);
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
}
}
});
});
I doing this for days, i dont have idea how to fix this errors .
Network tab
Console tab

ajax post request to view

I am trying to make a simple ajax request to a view but keep having a not Found error for the given url:
Not Found: /myapp/start_session/1/scan_ports/
"POST /myapp/start_session/1/scan_ports/ HTTP/1.1" 404 5711
js
$(document).ready(function() {
$.ajax({
method: 'POST',
url: 'scan_ports/',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function (data) {
alert("OK!");
},
error: function (data) {
alert("NOT OK!");
}
});
});
url
url(r'^scan_ports/$',views.ScanPorts,name='scan_ports'),
view
#login_required
def ScanPorts(request):
user = request.user
if request.method == 'POST':
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
return HttpResponse('')
Is the ajax request not set properly?
Assuming you are in the "myapp" app, replace:
method: 'POST',
url: 'scan_ports/',
for this:
method: 'POST',
url: '/myapp/scan_ports/',
First check your urls, the url on which you posted is incorrect hence 404 not found error.
Try to define your url in your JS as: {% url 'scan_ports' %} which will search your urls with the name your provided in urls.py
In addition, this may not be a good approach to submit a form via ajax.
Your JS should be something like this:
$('.form-class-name').on('submit', function (e) {
e.preventDefault();
console.log("ajax is called");
$.ajax({
type: $(this).attr('method'),
url: "/url-name/",
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(data) {
alert("Failure");
}
})
}
e.preventDefault() prevents the natural/default action, and prevents from submitting the form twice.
.serialize(), serializes the form data in a json format.
append a "/" before and after your action url.
Your view must return a dictionary as ajax deals with JSON format.
Edit your view like this:
if request.method == "POST":
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
a = {'data':'success'}
return HttpResponse(json.dumps(a))
This will return a dictionary required by the ajax.

django using ajax in wistia

I build my django app to get watch video time.
I reveive data from wistiaApi and comfirm the video time from alert.
I comfirm the send signal when video_time='10' instead video_time = reuqest.POST.get('video_time'), but using ajax, there are no success message. Where is problem?
view
if request.method == 'POST' and request.is_ajax():
video_view.send(
request.user,
video_time=request.POST.get('video_time'),
primary_obj_video=obj,
secondary_obj_video=cat
)
template
wistiaEmbed = jQuery(".wistia_embed")[0].wistiaApi;
var time = wistiaEmbed.duration();
alert(time);
$.ajax({
type: "POST",
data: {video_time: time},
success: function(){
alert ("hi");
}
});
url is missing inside ajax():
$.ajax({
url: '/your_url/', #<-----------------
type: "POST",
data: {video_time: time},
success: function(){
alert ("hi");
}
});

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

Resources