title: Codeigniter, getting ajax to run on button press
body: <p>My original goal was to get a php file to execute on a button press. I used ajax.  When the javascript was in the view, it worked.</p>
  
  <p>However, I tried to switch the javascript to its own .js file and include it in the header.  It doesn't work anymore.  I am confused. </p>
  
  <p>the model code: </p>
  
  <pre><code>public function insert_build($user_id)
  {
      $query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
      mysql_query($query) or die ('Error updating database');
  }
  </code></pre>
  
  <p>Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate.  As in, it simply doesnt load.  When I replace $user_id with a static value (i.e. '7') it works no problem.  </p>
  
  <p>This is my view code : </p>
  
  <pre><code>&lt;div id="structures"&gt;
      &lt;h1&gt;Build&lt;/h1&gt;
      &lt;form name="buildForm" id="buildForm" method="POST"&gt;
          &lt;select name="buildID" class="buildClass"&gt;
          &lt;option value="0" selected="selected" data-skip="1"&gt;Build a Structure&lt;/option&gt;
  &lt;?php foreach ($structures as $structure_info): ?&gt;
      &lt;option name='&lt;?php echo $structure_info['str_name'] ?&gt;' value='&lt;?php echo $structure_info['str_id'] ?&gt;' data-icon='&lt;?php echo $structure_info['str_imageloc'] ?&gt;' data-html-text='&lt;?php echo $structure_info['str_name'] ?&gt;&lt;i&gt;
          &lt;?php echo $structure_info['timebuildmins'] ?&gt; minutes&lt;br&gt;&lt;?php echo $structure_info['buy_gold'] ?&gt; gold&lt;/i&gt;'&gt;&lt;?php echo $structure_info['str_name'] ?&gt;&lt;/option&gt;
  &lt;?php endforeach ?&gt;
          &lt;/select&gt;
          &lt;div id="buildSubmit"&gt;
              &lt;input id ="btnSubmit" class="button" type="submit" value="Submit"/&gt;
          &lt;/div&gt;
      &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Heres my .js file : </p>
  
  <pre><code>$(".button").click(function(e){
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: "&lt;?php $this-&gt;structure_model-&gt;insert_build($user_id) ?&gt;",         //the script to call to get data          
      data: "",                        //you can insert url arguments here to pass to api.php
                                          //for example "id=5&amp;parent=6"
      dataType: 'json',                //data format      
      success: function(data)          //on receive of reply
      {
      alert("success!");
      } 
      });
  }); 
  </code></pre>
  
  <p>I am almost sure I know the problem:  That <code>structure_model->insert_build($user_id) ?></code> doesn't work when its outside the view.  Though, I dont know the alternative. </p>
  
  <p>I excluded the header file.  I confirmed that the .js file is indeed being directed to the correct path.</p>
  
  <p>Could someone please explain the correct way to do this? Thank you!</p>