jQuery and Multiple Forms, only the first one works - javascript

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
});
});

Related

how to send form data in ajax with multiple files without refreshing?

in my form code there is text input, checkbox input, file input type...etc,
everything working fine except the file input it's only taking one value ( multiple files upload isn't sending through ajax call ) how can i send arrays inside the serialize() function ?
Code :
<form action="#" id="postAdd" enctype="multipart/form-data">
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file[]" multiple required>
<input autocomplete="off" type="text" class="form-control bg-white" name="discName[]">
<button id="postAdbtn" class="btn btn-primary d-block mt-2">Submit</button>
</form> $(document).ready(function() {
$('#postAdbtn').click(function() {
var form = $('#postAdd').serialize();
$.ajax({
url: 'add-product-done.php',
method: "POST",
data: {
form: form
},
success: function(data) {
$('.fetchData').html(data);
}
})
});
});
one more thing, how can i get the files in PHP ?
and thanks
Can you try something like this?
var form = new FormData($("postAdd"));
$.ajax({
url: 'add-product-done.php',
data: form,
contentType: "multipart/form-data",
type: 'POST',
success: function(data){
console.log(data);
},
error: function(err){
console.error(err);
}
});

DJANGO: How to get form value in views.py without submitting it

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

AJAX form submission in Django

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("")

Django: Update Page Information Without Redirecting

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})

Laravel csrf token mismatch on ajax post a second time

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');
});

Categories