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");
}
});
Related
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.
I have made this ajax request to show the validation errors and prevent the page to reload
$(document).on('mousedown', ':submit', function() {
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
All is fine with this code! The problem is that after successfull submit i have 2 inputs in DB...how can i prevent this?
Are you sure the form isn't actually submitting and saving the values once by post and once by ajax? Usually if you're capturing a submit event you listen for the forms submit even not the mousedown event of the submit button e.g.
$('form').on('submit', function(e) {
// Stop the forms default submit action
e.preventDefault();
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){
},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}
});
});
Also the e.preventDefault() will prevent the form from submitting itself along with your ajax action. Also you'd best off selecting your form by an ID or class name.
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>
I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded
i have a page loaded via jquery tabs ajax, i have a form within this page that i want to show form response via ajax. response is loading from this code:
$('#whois').submit(function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: $('#whois').attr('/lib/domainchecker.php'),
success: function(response) {
$('#reply').html(response);
}
});
return false;
);
but my form submit to parent page instead of /lib/domainchecker.php. so i see headers of my page instead of response!
any idea what makes this happen?
When you are loading content on the page via AJAX and you need to apply events to the loaded content you need to use the jquery live().
$('#whois').live('submit', function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: $('#whois').attr('/lib/domainchecker.php'),
success: function(response) {
$('#reply').html(response);
}
});
This of course goes on the main host page rather than the loaded content page.
problem is solved, no thing related to loading page via ajax but there was an error with code, i shouldn't post to $('#whois').attr('/lib/domainchecker.php') but just '/lib/domainchecker.php'
corrected code:
$('#whois').live('submit', function() {
$.ajax({
data: $('#whois').serialize(),
cache:false,
type: "POST",
url: '/lib/domainchecker.php',
success: function(response) {
$('#reply').html(response);
}
});