title: Using XMLHTTPRequest to extract data from Database
body: <p>I want to extract some data from the database without refreshing a page. What is the best possible way to do this? </p>
  
  <p>I am using the following XMLHTTPRequest function to get some data (shopping cart items) from <code>cart.php</code> file. This file performs various functions based on the <code>option</code> value.
  For example: <code>option=1</code> means get all the shopping cart items. <code>option=2</code> means delete all shopping cart items and return string <code>"Your shopping cart is empty."</code>. option=3, 4...and so on.</p>
  
  <p>My XHR function:</p>
  
  <pre><code>    function getAllCartItems()
      {
          if(window.XMLHttpRequest)
          {
              allCartItems = new XMLHttpRequest();
          }
          else
          {
              allCartItems=new ActiveXObject("Microsoft.XMLHTTP");
          }
  
          allCartItems.onreadystatechange=function()
          {
              if (allCartItems.readyState==4 &amp;&amp; allCartItems.status==200)
              {
                  document.getElementById("cartmain").innerHTML=allCartItems.responseText;
              }
              else if(allCartItems.readyState &lt; 4)
              {
                   //do nothing
              }
          }
          var linktoexecute = "cart.php?option=1";
          allCartItems.open("GET",linktoexecute,true);
          allCartItems.send();
      }
  </code></pre>
  
  <p><strong>cart.php</strong> file looks like:</p>
  
  <pre><code>    $link = mysql_connect('localhost', 'user', '123456'); 
      if (!$link)
      {
          die('Could not connect: ' . mysql_error());
      }
      mysql_select_db('projectdatabase');
      if($option == 1) //get all cart items
      {
          $sql = "select itemid from cart where cartid=".$_COOKIE['cart'].";";
          $result = mysql_query($sql);
          $num = mysql_num_rows($result);
              while($row = mysql_fetch_array($result))
              {
                   echo $row['itemid'];
              }
      }
      else if($option == 2)
      {
              //do something
      }
      else if($option == 3)
      {
              //do something
      }
      else if($option == 4)
      {
              //do something
      }
  </code></pre>
  
  <p><strong>My Questions:</strong> </p>
  
  <ol>
  <li>Is there any other way I can get the data from database without
  refreshing the page?</li>
  <li>Are there any potential threats (hacking, server utilization,
  performance etc) in my way of doing this thing? I believe a hacker
  can flood my server be sending unnecessary requests using option=1,
  2, 3 etc.</li>
  </ol>