title: Connecting to a server-side SQL database via php with jquery
body: <p>I have been trying to look over an example to figure out how to connect to a server's SQL database from a client using JQuery, AJAX, and PHP, and though it is old it seems well done and straight forward: <a href="http://openenergymonitor.org/emon/node/107" rel="nofollow">Example Link</a>.A single folder contains all of my php files as well as the product version of jQuery (javascript-1.10.2.min.js).</p>
  
  <p><strong>Problem 3 - Fixed</strong></p>
  
  <p>JS console shows [Object, "parsererror", SyntaxError] at</p>
  
  <pre><code>var id = data.data[0];              //get id, data['data'][0] works here as well
  </code></pre>
  
  <p>in client.php. Object responseText shows ..."No Database Selected"... I have updated my client.php based on Daedalus' response and am still getting the same error. </p>
  
  <p>Error was in mislabeling a variable ($link instead of $con) in server-api.php</p>
  
  <p>-- Code --</p>
  
  <p>db-connect.php:</p>
  
  <pre><code>&lt;?php 
  
  //--------------------------------------------------------------------------
  // Example php script for fetching data from mysql database
  //--------------------------------------------------------------------------
  $host = "localhost";
  $user = "root";
  $pass = "password";
  
  $databaseName = "server-db";
  $tableName = "inventory";
  
  ?&gt;
  </code></pre>
  
  <p>server-api.php:</p>
  
  <pre><code>&lt;?php 
  
  //--------------------------------------------------------------------------
  // 1) Connect to mysql database
  //--------------------------------------------------------------------------
  include 'db-connect-99k.php';
  $con = mysql_connect($host,$user,$pass);
  $db_selected = mysql_select_db('zgc7009_99k_db', $con);
  $array = array('mysql' =&gt; array('errno' =&gt; mysql_errno($con), 'errtxt' =&gt;mysql_error($con)));
  
  //--------------------------------------------------------------------------
  // 2) Query database for data
  //--------------------------------------------------------------------------
  $result = mysql_query("SELECT * FROM $tableName");          //query
  $array['mysql'][] = array('errno' =&gt; mysql_errno($con), 'errtxt' =&gt;mysql_error($con));
  $array['data'] = mysql_fetch_row($result);                    //fetch result
  
  //--------------------------------------------------------------------------
  // 3) echo result as json 
  //--------------------------------------------------------------------------
  echo json_encode($array);
  
  ?&gt;
  </code></pre>
  
  <p>client.php</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
    &lt;script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;!-------------------------------------------------------------------------
  1) Create some html content that can be accessed by jquery
  --------------------------------------------------------------------------&gt;
  &lt;h2&gt; Client example &lt;/h2&gt;
  &lt;h3&gt;Output: &lt;/h3&gt;
  &lt;div id="output"&gt;this element will be accessed by jquery and this text replaced&lt;/div&gt;
  
  &lt;script id="source" language="javascript" type="text/javascript"&gt;
  
  $(function () 
  {
  
    //-----------------------------------------------------------------------
    // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
    //-----------------------------------------------------------------------
    $.ajax({                                      
      url: 'server-api.php',           //the script to call to get data          
      data: "",                        //you can insert url argumnets here to pass to api.php
                                     //for example "id=5&amp;parent=6"
      //dataType: 'json',                //data format  (comment out or get parsererror) 
  
      // Successful network connection
      // Successful network connection
      success: function(data)          //on recieve of reply
      {
        var id = data.data[0];              //get id, data['data'][0] works here as well
        var vname = data.data[1];           //get name
        //--------------------------------------------------------------------
        // 3) Update html content
        //--------------------------------------------------------------------
        $('#output').html("&lt;b&gt;id: &lt;/b&gt;"+id+"&lt;b&gt; name: &lt;/b&gt;"+vname); //Set output element html
        $('#error_code').html("Success!");
      },
    error: function() {
      console.log(arguments);
    }
    });
  }); 
  
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>Problem 1 - Fixed</strong></p>
  
  <p>Thanks to user help, I have managed to get rid of my original error of:</p>
  
  <pre><code>OPTIONS file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. jquery.js:8706
  XMLHttpRequest cannot load file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
  </code></pre>
  
  <p><strong>Problem 2 - Fixed [now running on temporary web server (see link at bottom)]</strong></p>
  
  <p>Now I am running WAMP (including phpmyadmin and apache) as my webserver. I can run my php page with script (client.php) no problem, it runs, can't seem to find any errors in my logs. However, I still never seem to hit the success function of my script. I am assuming that I have inappropriately set something somewhere (eg localhost/"my site".php) but I am not sure where. </p>
  
  <p>I also tried changing my AJAX function a bit, to include .done:</p>
  
  <pre><code>$.ajax({      
    url: 'localhost/server-api.php',           //the script to call to get data          
    data: "",                        //you can insert url argumnets here to pass to api.php
                                     //for example "id=5&amp;parent=6"
    dataType: 'json',                //data format   
  
    // Successful network connection
    success: function(data)          //on recieve of reply
    {
      var id = data[0];              //get id
      var vname = data[1];           //get name
      //--------------------------------------------------------------------
      // 3) Update html content
      //--------------------------------------------------------------------
      $('#output').html("&lt;b&gt;id: &lt;/b&gt;"+id+"&lt;b&gt; name: &lt;/b&gt;"+vname); //Set output element html
    }
  
  }).done(function() {
      $('#output').html("AJAX complete");
  });
  </code></pre>
  
  <p>but my output value never gets changed within the ajax call. I could be implementing .done incorrectly, but I just can't seem to figure out why I am not hitting anything and can't seem to find a log that is a help in finding the next step.</p>
  
  <p>On previous edit I removed localhost from php calls ('localhost/server-api.php' returned a 404) and now I am stuck again. I get a 304 Not Modified from my jQuery call, but I thought that, as of jQuery 1.5 ajax handled this as a success so I should still be hitting my html text update (correct?) and I don't.</p>
  
  <p>WAMP access Log:</p>
  
  <pre><code>127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /client.php HTTP/1.1" 200 2146
  127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /jquery.js HTTP/1.1" 304 -
  127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /server-api.php HTTP/1.1" 200 38
  </code></pre>
  
  <p>Note - this is the only log that updates when I refresh client.php in my browser. my js console stays blank. I have uploaded this to a temp site: <a href="http://zgc7009.99k.org/client-99k.php" rel="nofollow">zgc7009.99k.org/client-99k.php</a></p>