-2

I am working on web cgi application using python. Where I have two dropdowns whose options are rendered from list. Now I want to dynamically updated content of the second dropdown based on the first dropdown value.

All the code is written in Python including HTML. I am able to call onchange event on the first dropdown and get the selected value into Javascript object, however I want to assign it to python variable so that I can populate the second dropdown based on the selected value.

    <label for="staticEmail" class="col-sm-2 col-form-label">State:</label>
    <div class="col-sm-6">
      <select name="state" class="form-select" autofocus id="select_facility" onchange="selectFacility()">
      <option value="XX">Select Facility</option>''')
  for r in stateList:
    print('<option value="'+str(r)+'">'+str(r))
  print('</select>')
  print('</div>')
  print('</div>')

  print('''<div class="mb-3 row">
    <label for="staticEmail" class="col-sm-2 col-form-label">Facility Name:</label>
    <div class="col-sm-6">
      <select name=state class="form-select" >
      <option value=XX>Select Facility</option>''')
  for r in facList:
    print('<option value="'+str(r['state'])+'|'+r['facility_npi']+'">'+r['name']+', '+r['city']+', '+r['state'])
  print('</select>')
  print('</div>')
  print('</div>')```

And Javascript code having onchange method defined is as follows:
```print('''<script>''')
print('function selectFacility(){return document.getElementById("select_facility").value}')
print('</script>''')```

But I am unable to obtain the selected value into Python variable.

2 Answers2

0

Your AJAX call is incorrect.

You are passing an object which has a property called column_name which contains a literal string "sortOrder".

Try something like this:

function sortby(selectObject) {
    var sortOrder = selectObject.value;
    $.ajax({
        url: "sort.php",
        method: "POST",
        data: { column_name: sortOrder },
        success: function(data) {
            $('#allProducts').html(data);
        }
    })
    console.log("called");
}

And then in PHP:

<?php
if(isset($_POST['column_name']) {
    // do something here
} else {
    echo 'No value was passed!';
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

You have to make following changes in your data object.

function sortby(selectObject) {
        var sortOrder = selectObject.value;
        $.ajax({
            url: "sort.php",
            method: "POST",
            data: { "sortOrder": sortOrder }, // the var you have get from DOM to sent to PHP code
            success: function(data) {
                $('#allProducts').html(data);
            }
        })
        console.log("called");
    }

sorOrder indes is looked into $_POST[] array but it can't found and hence it return you notice.

Vantiya
  • 612
  • 1
  • 4
  • 11