0

The user selects one of the options and submits the form.

Then without submitting the form, I need to display data from json file.

I am storing ajax call in a global variable display_this and calling that variable as a function after form is submitted.

When I select option and press submit I get this error:

TypeError: display_this is not a function

When I refresh the page, it displays the data.

My code:

<form id="form">
  <select name="op" id="op">
    <option value="A">A</option>
    <option value="B">B</option>
  </select>
  <input value="Submit" type="submit" id="submit">
</form>

My JSON data:

[ 
  {"key":"A","val":"apple"},
  {"key":"A","val":"orange"},
  {"key":"B","val":"carrot"},
  {"key":"B","val":"onion"}
]

My jQuery code:

$(document).ready(function () {
  var output;
  var display_this = function () {
    var val = $("#op").val();

    $.ajax({
      async: 'false',
      type: 'post',
      url: 'abc.php',
      data: {
        "val": val
      },
      dataType: 'json',
      success: function (response) {
        var data = JSON.stringify(response);
        var resp = JSON.parse(data);

        $.each(resp, function (i, item) {
          if (val == "A" && resp[i].key == "A") {
            output += resp[i].val + "</br>";
          } else if (val == "B" && resp[i].key == "B") {
            output += resp[i].val + "</br>";
          }
        });
        return results.html(output);
      }
    });
  }();

  $('#form').submit(function (e) {
    e.preventDefault();
    display_this();
  });
});  
techno
  • 3
  • 4
  • This should not be a return `return results.html(output);` And move the ajaxing function outside the $(function() {}) or just make it an anonymous function of the form submit – mplungjan Sep 24 '17 at 06:40
  • Can you add an "onclick=function" to display the data as the user progresses through the form? – whitebeard Sep 24 '17 at 06:43
  • Not sure this is a duplicate. OP asks, "Then **without** submitting the form, I need to display data from json file." – whitebeard Sep 24 '17 at 06:45
  • I reopened. The `return` made me think it was a dupe – mplungjan Sep 24 '17 at 06:45

1 Answers1

0

You function is not available to your form submit. I suggest this

$(function () {
  $('#form').submit(function (e) {
    e.preventDefault();
    var output;
    var val = $("#op").val();

    $.ajax({
     // async: 'false', // do NOT use async false
      type: 'post',
      url: 'abc.php',
      data: {
        "val": val
      },
      dataType: 'json',
      success: function (resp) {
        $.each(resp, function (i, item) {
          if (val == "A" && resp[i].key == "A") {
            output += resp[i].val + "</br>";
          } else if (val == "B" && resp[i].key == "B") {
            output += resp[i].val + "</br>";
          }
        });
        $("#results").html(output);
      }
    });
  });
});  
mplungjan
  • 169,008
  • 28
  • 173
  • 236