Hi All,
I am working on internal django project where, i select the option from dropdown in the form page and pass that value to the views.py using AJAX. in views.py i use the text from dropdown and want to throw the text into same form pages text field but that does not work. When i try to pass some constant string from views.py to template form page that works. Below is the code snippet
form.html
---------------
<h1>New Hot Fix Request</h1>
<!--<p>This session is of a –> {{request.session.requestor}} <-- type user</p>-->
<label>Product * </label>
<select class="dropdown" id="dropdown" name="product">
<option value="" selected="selected"></option>
<option value="Product1">Product1</option>
<option value="Product2">Product2</option>
</select><br>
<script>
$(document).ready(function(){
$('#dropdown').on('change',function(e){
var e = document.getElementById("dropdown");
var productName = e.options[e.selectedIndex].value;
console.log("Dropdown Product Name: "+productName);
$.ajax({
url:"",
method:'GET',
// send selected data to the newHPReq method which is in views.py
data : {'product' : $(this).val()}, // 'product' will be used in request.GET.get('product') which is in views.py, $(this).val() is selected item,
success:function(data){
//console.log(data);
}
});
});
});
</script>
views.py
---------------
def newHPReq(request):
# name = request.session['requestor']
if request.method == 'GET':
prod_name = request.GET.get('product') # we are getting selected item with this line. we defined 'product' in ajax file
print("Product name from dropdown: %s " % prod_name)
context_dict = {'product_name': prod_name}
print("Product Name is: %s " % context_dict['product_name'])
return render(request, 'FormPage/form.html', (context_dict)) # Expecting product1 to be sent to form.html but doesnt.
I want to capture 'Product1' from dropdown to below text field of fom.html
<label for="productName">Selected Product</label>
<input type="text" name="productName" id="productName" size="38" value=""><br>
<script>
$(document).change(function() {
console.log('I am here'); // This gets printed every time when I change the dropdown value
getSelectValue();
});
</script>
<script type='text/javascript'>
function getSelectValue() {
field = document.querySelector('#productName');
var name = "{{product_name}}"; // This always gives None when select product from dropdown
console.log("Received name from view: " + name);
field.value = name;
}
</script>
I need some help, how can I propagate the dynamic change text from views.py to template form.html page.
Thank you in advance