title: AJAX call from inside a Widget in Yii2?
body: <p>I would like to create a Widget for my Yii2 project that will based on a few parameters given in the View create an AJAX call that updates a portion of my View.</p>
  
  <p>Basically I have a Postcode field that when updated will look up the corresponding town in a different PHP file. I created something that works, but I was wondering if this is the right (or only?) way to do what I'm looking for. I don't want to have to rewrite the AJAX call as I want to be able to reuse this functionality on several forms and thus fields in my project.</p>
  
  <p>I call the Widget in my View like this:</p>
  
  <pre><code>&lt;?= SearchWidget::Widget(['id' =&gt; 'customerform-postalcode', 
                            'dataTarget' =&gt; 'cities',
                            'targetId' =&gt; 'customerform-city',
                            'targetType' =&gt; 'dropdown']);?&gt;
  </code></pre>
  
  <p>and in the Widget I basically have only a run() function which echoes the AJAX call to the page.</p>
  
  <pre><code>public function run()
  {   
      $jScript = 
          '&lt;script&gt;'
              . '$("#' . $this-&gt;id . '").change(function(){'
                  .'$.ajax({'
                      . 'url: "../scripts/search.php",'
                      . 'data: {'
                          . 'needle: $("#' . $this-&gt;id . '").val(),'
                          . 'haystack: "' . $this-&gt;dataTarget . '"'
                      . '},'
                      . 'type: "POST"'
                  . '}).done(function(data){'
                      .'var targetType = "' . $this-&gt;targetType . '";'
                      .'if (targetType=="dropdown") {'
                          . '$("#' . $this-&gt;targetId . '").empty();'
                          . 'var obj = jQuery.parseJSON(data);'
                          . '$.each(obj, function(key, value) {'
                              . '$("#' . $this-&gt;targetId . '").append("&lt;option&gt;" + value + "&lt;/option&gt;");'
                          . '});'
                      . '} else {'
                          . 'var obj = jQuery.parseJSON(data);'
                          . '$("#' . $this-&gt;targetId . '").val(obj);'
                      . '}'
                  . '});'
              . '})'
          .'&lt;/script&gt;';
      echo $jScript;
  }
  </code></pre>
  
  <p>First off, I've only just started working with Yii and frameworks so I'm really unsure if this is the correct way to go about it. My first instinct says this is too messy and there should be a better way to do it. Any help is appreciated.</p>