Store specific value in javascript when multiple forms are present - javascript

I've got a list of 10-20 objects on each page creating these forms:
<div id="routeTable">
{% for route in route_list %}
<div id="routeDone">
<form class="doneForm" action="/route/complete/" method="post">
<input type="hidden" name="route_id" value="{{ route.route_id }}" />
<input type="hidden" name="next" value="{{ request.get_full_path }}" />
<input type="submit" value="Done" class="doneButton" />
</form>
</div>
{% endfor %}
</div>
And I'm trying to add some jquery to the page in order to intercept the usual form submit and instead do so using ajax as below. (I already have a view that returns an html chunk which will be swapped out for the above div#routeTable. The problem is line 4 "var route_ID...":
<script>
$(document).ready(function() {
$(".doneForm").submit(function() {
var route_id = $(this).attr('input[name=route_id]').val()
$.ajax({
type: "post",
url: "/route/complete/",
data: route_id,
success: function(data) {
$("#routeTable").html(data);
}
});
return false;
});
});
</script>
Unfortunately I'm having trouble passing the proper route_id into the js variable named route_id. I expect it will require use of the 'this' keyword, but I haven't been able to figure out exactly how.
Any suggestions on how to fix up my javascript would be greatly appreciated.

Try to change
var route_id = $(this).attr('input[name=route_id]').val()
to
var route_id = $(this).find('input[name=route_id]').val()
The reason being that input[name=route_id] is not an attribute, but a selector that represent a tag input and an attribute on that tag [name=route_id].
You could also do
var route_id = $('input[name=route_id]',this).val()

var route_id = $(this).attr('input[name=route_id]').val()
Should be something like:
var route_id = $(this).find('input[name=route_id]').val()

Related

Django: can't trigger AJAX call and send values back to my form

I need to run an AJAX call to perform a quick calculation in my django view and return the result in my html page, inside a tag.
I'm very new to Javascript so I don't understand why my AJAX call hasn't been triggered. This is my html and JS code:
<input type="text" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<span>{{estimation}}</span>
<script type="text/javascript">
function calculate () {
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
SHm2: $('#SHm2').val(),
STm2: $('#STm2').val()
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation").innerHTML = estimation;
}
});
}
</script>
And this is my views.py:
def homepage(request):
if request.method == 'POST' and request.is_ajax and 'estimation' in request.POST:
SHm2 = request.POST.get('SHm2')
STm2 = request.POST.get('STm2')
estimation = float(SHm2) + float(STm2)
estimation = json.dumps(estimation)
return HttpResponse(estimation, content_type='application/json')
The problem is that the AJAX code isn't triggered since I don't receive the alert. Nevertheless, the code in my django view is running anyway (which is strange, since I specified to run if 'request.is_ajax', which doesn't seem to be recognized on the other hand). It loads a new page where it correctly displays the result. But it's not what I want since I need the result to be in my form within the span tag where {{estimation}} is my variable.
Could you please tell me what I'm doing wrong? Thanks!
UPDATE:
Thanks to your answers, it's getting better. I've replaced in views.py 'request.is_ajax' by 'request.is_ajax()'. I've added the 'id' attribute to my input boxes. This helped me to trigger the AJAX call and not to load stuff in a new page. There is one last thing though. I'm still not able to display in my span tag the value of the estimation variable. I realised that it had no 'id' attribute so I did the following change:
<span id="estimation2">{{estimation}}</span>
Also in my JS code, I replaced in the success part the last line to:
document.getElementById("estimation2").innerHTML = estimation;
Basically I replaced "estimation" by "estimation2".
Unfortunately the span tag is not updated. Any idea what I am missing?
Change name to id. because #means id of the field. Like from name="SHm2" to id="SHm2"
<input type="text" id="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<span>{{estimation}}</span>
<script type="text/javascript">
function calculate () {
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
SHm2: $('#SHm2').val(),
STm2: $('#STm2').val()
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation").innerHTML = estimation;
}
});
}
</script>
1st
request.is_ajax is a function
2nd
'estimation' in request.POST
You have it in your statement but you did not pass it to view. Add it to data or remove from statement
It seemed that the issue came from the fact that I didn't declare the type of my button in my html code. The default value (i.e. "submit") prevented it from triggering my AJAX code as needed. So in the end I had to set it to 'type="button"' to make it work.

AJAX is not parsing Data and not using PATCH method

I am relatively new to Ajax, my problem is I am trying to submit the form as PATCH, and parse url, which is sent by Mustache {{add_member_url}}, I do not get any errors, and backend works, I have tried it. The server receives GET, although my form method="PATCH", and Ajax method="PATCH", there are two functions in Ajax first get - I render the form second is PATCH to submit the form.
JavaScript
$('.list').on('click', '#add', function(event){
event.preventDefault();
var url_send = $(this).data("add_url")
// $("#yourModal").modal({"backdrop": "static"});
$.get(''+$(this).data("add_url"), function(data){
console.log(this);
var template = $("#add_member_template").html();
console.log("T",template);
data.add_member_url = url_send;
console.log(data.add_member_url);
var rendered = Mustache.render(template, data);
console.log(rendered);
$('.contain').html(rendered);
});
});
$('.contain').on('submit', '#add_member', function(event){
event.preventDefault();
console.log('U',$(this).data("add_url"));
$.ajax({
url:''+$(this).data("add_url"),
method: 'PATCH',
data: $(this).serialize(),
success: function(data) {
console.log(method);
}
});
});
});
HTML Form
<div id="forma" class="contain" ></div>
<script id="add_member_template" type="mustache/template">
<form id="theForm" action="" method="PATCH">
{% csrf_token %}
{% verbatim %}
<p> {{pk}} </p>
<p><label for="ssn">SSN:</label>
<input id="ssn" type="text" name="tename" data-add_url="{{add_member_url}}" value="{{tename}}"></p>
<button id="add_member" data-add_url="{{add_member_url}}" type="submit" value="save" class="btn blue">Submit</button>
{% endverbatim %}
</form>
</script>
Your event binding is wrong. The submit event only occurs on forms, not on the submit button. You need to bind to the button's click event:
$(".contain").on("click", "#add_member", function(event) {... });

Django and Ajax - Submitting Formsets

I've a problem trying to submit a formset through Ajax. A little informaton of what I'm doing is that the user enters a word and through Ajax I get the length of of it and produce a formset according to that number. I then print it out with a for loop and each form has a valid button that its suppose to submit that specific format to validate it. So its a single form submit for each button. Here is my code:
<div id="example1" type="hidden">
{{ exampleForm.management_form }}
{% for form in exampleForm %}
<form onsubmit="return false;" method="GET" id="{{ form.prefix }}" >
( {{ form.letterOfWord }} + {{ form.keyToUse }} ) MOD 26 =
{{ form.letterToFill }} <button name="action" id="validateButton" value="validate"> Validate </button> <br>
</form>
{% endfor %}
And my javascript file:
$("#validateButton").on({
click : function() {
// var variable = document.getElementById('id_plaintext');
// console.log(variable.value)
console.log("Inside validate button function")
var serializedData = $('form').serialize();
console.log(serializeData);
$.ajax( {
url: "/exampleCaesar",
type : "GET",
data: { CSRF: 'csrf_token',
serializedData
},
success : function(exampleData) {
console.log(exampleData)
}
}); //END OF Ajax
} //END OF FUNCTION
}); //END OF validateButton
Thing is that when I click any of the validate buttons, nothing is submitted. I know this because I got a console.log in the javascript to know when it goes in. If that doesnt print out then it didn't actually go in.
Any tips? Been breaking my head all day for this. Thanks
you have multiple IDs validateButton. This might be source of your problems. As far as I know, or would guess, jquery will only trigger on the first button of the first form in this case.
Also, I'm not sure if jquery will serialize proper form when you use this code
var serializedData = $('form').serialize();
as again, you have multiple form in your html
Also, the managment_form should be inside of <form>, otherwise it won't get sent to Django. Check out the docs https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#using-a-formset-in-views-and-templates

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

Categories

Resources