-1
@app.route('/loadsubcat', methods =\['GET'\])
def loadsubcat():
  sub_cat = request.args.get('category_id')
  sub_cat_data = subcategories.query.filter(subcategories.categoryID == sub_cat).all()
  sub_data = "example"
  return jsonify({"hello": sub_cat_data})
<script type="text/javascript">
  $("#parent_cat").change(function() {
    var cat_id = $(this).val();
    $.ajax({
      type: 'GET',
      url: "/loadsubcat",
      data: { category_id: cat_id },
      contentType: 'application/json',
      dataType: 'json',
      success: function(sub_cat_data){
        alert(sub_cat_data);
        for (var i = 0; i < data.length; ++i) {
          console.log(data[i].subcategory_name);
        }
        $("#sub_cat").empty();
        var output = "";
        $.each(JSON.parse(data), function(a,b){
          // console.log(data);
          output += "<option value='"+b.id+"'>"+b.subcategory_name+"  </option>"
          $("#sub_cat").append(output);
        });
      }
    });
  });
</script>

I am trying to send first dropdown value to route then fetch results and based on that first dropdown value i am passing i am trying to load my second dependent dropdown.

I am stuck how to send data back through get api which is fetched through database.

Arnas
  • 635
  • 8
  • 18
Roy
  • 3
  • 1

1 Answers1

0

The problem is jsonify does not directly convert a object to json therefore we need to write an encoder

you can use marshmallow

Otherwise I found an encoder code to make your code as it is

download the code and save as json_serializable.py, then import use the encoder as below, then your code will work

from json_serializable import JSONSerializable

db = SQLAlchemy()
app = Flask(__name__)
JSONSerializable(app)

Fine tune you javascript code as below

$( document ).ready(function() {
        $("#parent_cat").change(
            function() {
                var cat_id = $(this).val();
                $.ajax({
                    type : 'GET',
                    url : "/loadsubcat",
                    data : {
                        category_id : cat_id
                    },
                    contentType : 'application/json',
                    dataType : 'json',
                    success : function(data) {
                        alert(data);
                        $("#sub_cat").empty();
                        for (var i = 0; i < data.length; ++i) {
                            output = "<option value='"+data[i].id+"'>"
                            + data[i].subcategory_name + "  </option>"
                            $("#sub_cat").append(output);
                        }
                    }
                });
            });
      });
Dickens A S
  • 3,824
  • 2
  • 22
  • 45
  • TypeError: Object of type subcategories is not JSON serializable – Roy Jan 08 '23 at 06:36
  • @app.route('/loadsubcat', methods =['GET']) def loadsubcat(): sub_cat = request.args.get('category_id') sub_cat_data = subcategories.query.filter(subcategories.categoryID == sub_cat).all() sub_data = "example" return str(sub_cat_data) when i printing results using str(sub_cat_data) I am able to fetch results but how to send same results to javascript using resturn jsonify? – Roy Jan 08 '23 at 06:38
  • from javascript you are already sending to server `$("#parent_cat").change(function() { var cat_id = $(this).val(); $.ajax({ type: 'GET', url: "/loadsubcat", data: { category_id: cat_id },` – Dickens A S Jan 08 '23 at 06:55
  • from server you are already receiving as `success: function(sub_cat_data){ alert(sub_cat_data);` – Dickens A S Jan 08 '23 at 06:56
  • you are doing both, but you are asking how, after doing it ? what is the actual issue you are facing ? – Dickens A S Jan 08 '23 at 06:57
  • TypeError: Object of type subcategories is not JSON serializable The data is not loaded in javascript – Roy Jan 08 '23 at 07:02
  • @app.route('/loadsubcat', methods =['GET']) def loadsubcat(): sub_cat = request.args.get('category_id') sub_cat_data = subcategories.query.filter(subcategories.categoryID == sub_cat).all() sub_data = "example" return jsonify({"hello": sub_cat_data}) – Roy Jan 08 '23 at 07:04
  • $("#parent_cat").change(function() { var cat_id = $(this).val(); $.ajax({ type: 'GET', url: "/loadsubcat", data: { category_id: cat_id }, contentType: 'application/json', dataType: 'json', success: function(sub_cat_data){ alert(sub_cat_data); var data = sub_cat_data.hello for (var i = 0; i < data.length; ++i) { console.log(data[i].subcategory_name); } } }); }); – Roy Jan 08 '23 at 07:05
  • `TypeError: Object of type subcategories is not JSON serializable The data is not loaded in javascript` this is your actual issue, put it in your question please – Dickens A S Jan 08 '23 at 07:26
  • what is `subcategories.query.filter` mongodb ? or mysql ? postgresql ? – Dickens A S Jan 08 '23 at 07:29
  • subcategories.query.filter is postgresql – Roy Jan 08 '23 at 07:32
  • writing code for you, will share in few hours – Dickens A S Jan 08 '23 at 08:23
  • will be waiting – Roy Jan 08 '23 at 09:43
  • jsonify is the problem, you can try `marshmellow` --- https://flask-marshmallow.readthedocs.io/en/latest/ – Dickens A S Jan 08 '23 at 10:45