I have this code:
html
<form method="post" id="idForm" name="frm1" action = "/myproject/save/"
enctype="multipart/form-data">
{% csrf_token %}
....
<input type="submit" name="save" id="save" value="Save">
</form>
<span class="status">Value: {{ request.mylist}} </span>
js code
$(document).on('submit', '#idForm',function(e){
$.ajax({
type: 'POST',
url: '{% url "myproject:save_form" %}',
data: {},
success:function(json){
$('.status').contents()[0].textContent = data.mylist
},
error : function(xhr,errmsg,err) {
alert("ajax error")
}
});
});
views
if request.method == 'POST' and 'save' in request.POST:
print("runs save form")
mylist= [5]
return JsonResponse({'mylist':mylist})
Question:
When I click on Save button, It is redirected to a page with
{"mylist": [5]}
How can I make it update only the status part, Value?
Use simple a button
<button type="button" onclick="sendData()">Save/button>
instead of this
<input type="submit" name="save" id="save" value="Save">
Make this a function
function sendData(){
$.ajax({
type: 'POST',
url: '{% url "myproject:save_form" %}',
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
formdata: JSON.stringify($("#idForm").serialize())
},
success:function(json){
let result = json.mylist[0];
$("#status").html(result);
},
error : function(xhr,errmsg,err) {
alert("ajax error")
}
});
}
You should also pass csrfmiddlewaretokentoken in data of ajax to csrf middle trust your request.
You can do the update in ajax success callback.
Update
At server side you can get the serialized data like this
if request.method == 'POST' and 'save' in request.POST:
print("runs save form")
data=json.loads(request.POST.get('formdata'))
mylist= [5]
return JsonResponse({'mylist':mylist})
Related
In html,I have a form and I want to know the form value without submitting it or refreshing the page. Once user will click on it, I want to get the value of the form and then pass it to view.py. Its working while I'm using type='submit' but not working if I'm disabling the submit button by using type='button'. Please let me know how to get the value of the form without submitting it.
URL:
url(r'^segmentation',include('segmentation.urls'))
VIEWS:
def index(request):
.......
.....
if request.method == 'POST': # If the form has been submitted...
html_node_number2=request.POST.get('url')
..........
......
return render(request, 'tree_home.html',context)
TREE_HOME.HTML:
.....
...
FORM1:
<form method="post" enctype="multipart/form-data" > {% csrf_token %}
{% for node in tuples %}
<button class="open-button" onclick="openForm()" name="html_node_number" value=
{{node.list1|safe}} type="button" id="test"> </button>
<script type="text/javascript">
$(document).ready(function() {
var url = 12; 'Used 12 instead of html_node_number to cross check but even 12 is not also passed to views.'
$("#test").click(function() {
$.ajax({
url: "/segmentation",
type: "POST",
<!-- dataType: "json", -->
data: {
url: url,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
alert("Successfully sent the URL to Django");
},
error : function(xhr,errmsg,err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
});
</script>
</form>
ERROR: Its generating html_node_number = NONE value
I keep receiving 'Not Ajax' as a response during my form submission. I have to be missing something small but I cannot see it...
class VideoLikeView(View):
def post(self, request):
if request.is_ajax():
message = 'Ajax'
else:
message = 'Not Ajax'
return HttpResponse(message)
The AJAX code looks like this:
$(function () {
$("#like-form").submit(function (event) {
$.ajax({
type: "POST",
url: form.attr('action'),
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'pk': $(this).attr('value')},
success: function(response) {
alert('Video liked');
},
error: function(rs, e) {
alert(rs.responseText);
}
}
});
});
});
And my HTML:
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}">
<button type="submit">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
</form>
One question to add to this; how can I use an <input> in my form without using a <button>? I would like to use fontawesome icons but it seems I have to use a button to get the form to submit.
I found one answer on the internet that seems to work but I don't understand what the issue was. Seems like some type of serialization needed (?)... Anyways, here is what worked:
var frm = $('#like-form');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
return false;
});
Would love to hear from people why this works and not the previous..
try change your btn type button and add ID for event click :
since putting the submit button goes directly to view.py without going through AJAX
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}" id="id_pk">
<button type="button" id="id_btn">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
in your script
$("#id_btn").click(function() {
$.ajax({
url:window.location.origin + 'your url'
type: 'POST',
data: {'pk':$(#id_pk).val(), 'accion':'guardar'},
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
});
and your view.py
def post(self, request):
if 'guardar' in request.POST['accion']:
print("")
I am trying to submit a form via ajax.My template is as follows:-
<form method="POST" id="form1" class="SignUP signupform">
<div class="classheading">Sign-up</div>
{% csrf_token %}
<input type="text" name="user" placeholder="Username" class="sinput" required="true" />
<input type="text"name="email" placeholder="Email" class="sinput" required="true"/>
<input type="password"name="password"placeholder="Password" class="sinput" required="true"/>
<input type="password"placeholder="Re-enter Password" class="sinput" required="true"/>
<button type="submit" class="subform">Sign Up</button>
</form>
while ajax view submitting this form is:-
$(document).ready(function(){
$('#form1').submit(function(){
console.log('form is submitted');
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var formdata={
'username':$('input[name=user]').val(),
'email':$('input[name=email]').val(),
'password1':$('input[name=password]').val(),
'password2':$('input[name=password1]').val(),
};
console.log("Formvalue is taken");
$.ajax({
type:'POST',
url:'/Submit/signingup',
data:formdata,
dataType:'json',
encode:true,
headers:{
"X-CSRFToken": csrftoken
},
})
.done(function(data){
console.log(data);
});
event.preventDefault();
});
});
On backend, i'm submitting this form using Django.Corresponding View is as follows:-
#csrf_protect
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse("Confirm your email.")
else:
return JsonResponse({'success': False,'errors': [(k, v[0]) for k, v in form.errors.items()]})
But it's showing 403 error.In command prompt, it's showing "CSRF_TOKEN missing or incorrect".
What could be the possible error?
put csrf_token right after from open tag like this. and try
<form method="POST" id="form1" class="SignUP signupform">{% csrf_token %}
try this
$.ajax({
url: url ,
dataType: "json",
type: "POST",
data:{
data: val ,
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
console.log(data)
}
})
im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log. Do i need to refresh the csrf_token every ajax post?
Below is my code
JS
$(document).on('submit','.registration-form',function(e){
e.preventDefault();
var form = $(this);
var form_url = $(this).attr("action");
var form_values = $(this).serialize();
$.ajax({
url:form_url,
type:'POST',
data:form_values,
dataType: 'json',
async:false,
success: function(result){
console.log(result);
if(result['status']==true){
location.href = result['redirect'];
}
else{
form.find(".form-details").show().html(result['message']);
}
},
error: function(ts) {
console.log(ts.responseText)
}
});
});
HTML
<form action="{{ url('login') }}" method="POST" class="registration-form">
{{ csrf_field() }}
<input type="text" name="username" class="input" placeholder="Email">
<input type="password" name="password" class="input" placeholder="Password">
<button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>
Are u sure that each time that is send in ajax?
data: {
"_token": "{{ csrf_token() }}",
}
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
public function regenerateToken(){
session()->regenerate();
return response()->json([
'msg'=>'success',
'token'=>csrf_token()
]);
}
$('#form').submit(funtion(event) {
event.preventDefault(event);
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
if (response.msg === 'success') {
$('#token').val(response.token);
console.log($('#token').val());
}
}
$('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
});
I have a page with multiple elements and some jQuery code to send when one of the forms are clicked.
form:
<form method="post" action="">
{% csrf_token %}
<input id="vote" name="vote" type="hidden" value="up">
<input id="post_id" name="post_id" type="hidden" value="{{submission.id}}"/>
<input type="submit" class="arrowup" value=""/>
</form>
jQuery javascript:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/button_form/",
dataType: "json",
data : {
post_id : encodeURIComponent(document.getElementById('post_id').value),
vote : encodeURIComponent(document.getElementById('vote').value),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#result').html( 'post id: ' + json.post_id + ' voted: ' + json.up_or_down);
},
error: function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
The first button works as expected and gets the server's json response, however all the other buttons don't work.
I'm led to think this might be because there are multiple vote and post_id form inputs, but can't figure out an alternative strategy, or if that's really the issue.
Any help is greatly appreciated.
Thanks
I think you can iterate through all your forms and submit each one separetely on their submit event:
$("#formID").submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
// All other ajax code for submitting form data
});
});