title: Calling PHP functions in Javascript using AJAX
body: <p>I have a javascript file and I want to call a function on the php server side and return the result back to the client side using ajax, but I am not sure how to make the request to the specific php function.</p>
  
  <p>Here are my files:</p>
  
  <p>The javascript file basically retrieves the username from the html form, and I want to send that username to php and check against the database for availability.</p>
  
  <p>In <code>something.js</code>:</p>
  
  <pre><code>function check_availability()
  {
      var username = $.trim(document.getElementById('usernameField').value);
      var xmlhttp= new XMLHttpRequest();
  
      // not sure how to make the request here to check_availability() under php
  }
  </code></pre>
  
  <p>The PHP file will just check the username thats being passed from the js file against the database, if its available return true, else false.</p>
  
  <p>In <code>something.php</code>:</p>
  
  <pre><code>    class Something_Model {
      private $data;
      private $table;
  
      public function __construct() {
          $this-&gt;data = new udata(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME);
      }
  
      # check for username availability
      public function check_availability()
      {
          // make the check here, but needs to retrieve username from js file
          echo "here";
      }
  }
  </code></pre>
  
  <p>So, inside the Something_Model class, I want to make the check_availability() call from javascript, can someone give me an example to make this ajax call?  Also, how do I return the result back to the javascript?  Do I need to encode it as a JSON obj?</p>
  
  <p>Thanks a lot.</p>