0

I have an ajax function that returns a value from a django function. I want to make the output global so that i can use it in a select dropdown.. here is my code.

$(document).ready(function () 
{ 
  function AjaxCall(HandleData) 
  {
    return $.ajax({
    url: "/evidence_values/",
    type: "post",
    data: {'evidence':document.getElementById('evidence').value},
    success: function(data){ HandleData(data);}
                   });
  }

    $("#save").click(function(){
       AjaxCall(function(output){filter_data = output});
                               });

    function CallAjax(DataHandle) 
    {
     return $.ajax({
                  url: "/get_evidence_items/",
                  type: "post",
                  success: function(data){DataHandle(data);}
                  });
    }

    $("#evidence_selected").click(function(){
       CallAjax(function(output){items_data = output});
                                             });

and the dropdown elsewhere in index.html

<select name="evidence_selected" id="evidence_selected" style="margin-right:20px;color:#5c89db;margin-top:20px;margin-left:40px;height: 2em;border-radius: 3px;">

<option value="selectedvidence" id="selectedvidence"name="selectedvidence">Select Evidence Number</option>

{% for item in items %}
<option value="{{item.evidence}}">{{ item.evidence }}</option>
{% endfor %}
<option id="new"value="new">New</option>

</select>
Stefan Laity
  • 130
  • 8
user3670066
  • 85
  • 1
  • 3
  • 8
  • If you have a variable in global scope, then you can write to it in the `success` functions you have defined. However, it is probably a better idea to use `success` to call an "update" function that rewrites the values in the select. Related: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call?rq=1 – Tom Fenech Jul 20 '14 at 10:16

1 Answers1

0

You could have your handle data function insert options into the select?

  $("#evidence_selected").append('<option value=1>' + dataStr + '</option>');

Or, store the values in an array:

 var evidenceArray = [];
 evidenceArray.push(dataStr);

And then create foreach from array:

$("#evidence_selected").empty();
$.each(evidenceArray , function() 
{
  $("#evidence_selected").append('<option value=1>' + this+ '</option>');
});

But if you are populating on ajax success I'm not sure why you would use a for-each and not insert?

Community
  • 1
  • 1
Stefan Laity
  • 130
  • 8