Page 1 of 8

Newbie to Javascript, jQuery and Ajax

Posted: Wed Apr 04, 2012 8:10 pm
by Pavilion
  1. My Goal - learn how to write and use event functions in jQuery.
  2. My immediate problem - figure out how to include SQL queries in jQuery functions.
I've found a few jQuery demos showing how to use event functions. But no decent explanation of how to include SQL queries within the function. So... I'm going to go at this in baby steps. My first question, in order to include SQL Queries in jquery functions can I use my existing database link (written in php), or do have to write a dedicated link in jQuery. Following is some sample code I found:

Code: Select all

<?php 
 
/* 
 
 
        In this class we instantiate an SQL Connection object. Connection details are assinged to  
 
        object variabes so that they can be used when connecting to the database. The two main  
 
        functions are conn() and disc(). They are for connecting and disconnecting to the SQL database. 
 
 
*/ 
 
class doConnect 
 
{ 
 
        private $databasehost; 
 
        private $databasename; 
 
        private $databaseusername; 
 
        private $databasepassword; 
 
         
 
        function __construct() 
 
        { 
 
                $this->setRes(); 
 
                $this->conn(); 
 
        } 
 
         
 
        function setRes() 
 
        { 
 
                $this->databasehost = "localhost"; 
 
                $this->databasename = "vehicles"; 
 
                $this->databaseusername ="cars"; 
 
                $this->databasepassword = "car123"; 
 
        } 
 
         
 
        function conn() 
 
        { 
 
                $con = @mysql_connect($this->databasehost,$this->databaseusername,$this->databasepassword) or die(mysql_error()); 
 
                @mysql_select_db($this->databasename) or die(mysql_error()); 
 
 
        } 
 
         
 
        function disc() 
 
        { 
 
                mysql_close(); 
 
        } 
 
} 
 
?>
At this point in my learning process, I've a php link file already, a handful of php files recently converted to php PDO (thank you Celauran). The SQL queries are now operating within PDO constraints. All of this is on my mind as I review the very few samples of jquery code.

But, unless someone can convince me there is a better way, I feel a strong need to learn about event functions. In writing classical databases I use event procedures constantly. They make it possible to create a user-friendly database - with a lot of code action happening on AfterUpdate, OnClick, OnClose, OnOpen, BeforeUpdate. The users don't even know what is happening, data just appears at important points in the process (cascading lists for example) with no effort on their part. As of yet, I've not found anything similar in php. So... jquery seems to be a necessary learning curve.

Any help or advice is appreciated.

Thanks Much - Pavilion

Re: Newbie to Javascript, jQuery and Ajax

Posted: Wed Apr 04, 2012 8:15 pm
by Celauran
Typically, you'll have an event trigger a jQuery function, which sends a request to a PHP page. The PHP page handles the request, including DB query, returns the results to the jQuery function, which then updates the page in real time.

Google Code University explains it pretty well.

I also found a pretty basic tutorial/example that might help.

Re: Newbie to Javascript, jQuery and Ajax

Posted: Wed Apr 04, 2012 9:14 pm
by Pavilion
Hello Celauran -
Typically, you'll have an event trigger a jQuery function, which sends a request to a PHP page. The PHP page handles the request, including DB query, returns the results to the jQuery function, which then updates the page in real time.
Thank you for jumping in here, you have absolutely no idea how relieved I was to read your above statement. The thought of having to write separate files (like database connections) for javascript made no sense at all to me. So.. php files handle all the data processing, that is good to know.

I also took a quick look at your links and they help some. But so much of what I read in these tutorials is like reading french. My background is classical databases and the tutorials assume I have a basic understanding of common php, html, ajax, javascript terminology (and I don't). And that is why I keep coming back here. :D

Anyway, it seems the first thing I need to understand before actually experimenting with code are basic fundamentals. For instance the process of passing variables. A VB function passes variables within the function itself. For instance I might write a function called:

FindLastVisit()

Within the () of FindLastVisit() I will include variable names. If there are multiple variables, then the variables are separated by comas. So the start of the function looks something like this:

FindLastVisit(VarUserID, VarVisitDate)

Then when I "call" the function and "bind" the variables the syntax is as follows:
FindLastVisit([UserID],[VisitDate])

At any... when I first started reading about jquery events and functions, I thought it would be a similar process. But the link you sent me to, and other samples I've found... show this way of passing variables.
Ajax - Passing Variables via Query String

A query string is a way of passing information by appending data onto the URL. You may have often seen it on the web, it's all the information that appears after a question mark "?". When you submit a form using GET it builds a query string, all we're doing here is manually building our own.

http://www.tizag.com/somescript.php?var ... le2=value2

The left side of the equals operator is the variable name and the right side is the variable's value. Also, each variable is separated with an ampersand &.

For example, if we wanted to send the variables age, sex, and wpm with values 20, f, 40 to our PHP script ajax-example.php then our URL would look like:

http://www.tizag.com/ajax-example.php?a ... x=f&wpm=40

Now we need to build a new PHP script to take these variables and run a MySQL query for us.
This approach makes me nervous because it is displaying information in the browser (and just on a gut level) that feels wrong. Is this approach the only way to pass variables while handling event procedures? Or is there something more akin to what I described above?

Thank you - your help is sincerely appreciated.

Pavilion

Re: Newbie to Javascript, jQuery and Ajax

Posted: Wed Apr 04, 2012 9:23 pm
by Celauran
Because jQuery initiates the request directly, the user never actually sees it. The examples you listed are using GET requests but can be made to work every bit as well with POST requests.

As an aside, these aren't function calls per se. These examples simply show data being sent from one page to another, much like form processing. Function signatures and function calls in PHP behave as you described.

Definitions look like

Code: Select all

function myFunction($arg1, $arg2)
{
    // do stuff here
}
and then the function calls like

Code: Select all

$whatever = myFunction('foo', 'bar');

Re: Newbie to Javascript, jQuery and Ajax

Posted: Wed Apr 04, 2012 9:40 pm
by Pavilion
Celauran wrote:Because jQuery initiates the request directly, the user never actually sees it. The examples you listed are using GET requests but can be made to work every bit as well with POST requests.

As an aside, these aren't function calls per se. These examples simply show data being sent from one page to another, much like form processing.

So... POST requests can be used... that helps. But... how????

Function signatures and function calls in PHP behave as you described.

Definitions look like

Code: Select all

function myFunction($arg1, $arg2)
{
    // do stuff here
}
and then the function calls like

Code: Select all

$whatever = myFunction('foo', 'bar');
It's good to know that function calls in PHP behave as I described. But... in the context of jQuery and events aren't we using jQuery (or Ajax) functons? Or are they all the same???

Pavilion

Re: Newbie to Javascript, jQuery and Ajax

Posted: Wed Apr 04, 2012 9:56 pm
by Pavilion
On to the nuts and bolts. Last night I downloaded jquery ui fles and successfully installed a datepicker in my blocktime.php file. Right now I just want to get a handle on what is happening in the script. So, I'll post the script here with my questions in comment lines.

Code: Select all

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Block Time</title>
        <link rel="stylesheet" type="text/css" href="../####/include/formats.css"/>
		<link rel="stylesheet" href="../java_ui/themes/custom-theme/jquery.ui.all.css">
		<!--- These lnes are simply calling or including different jquery files -->
		<script src="../java_ui/jquery-1.7.1.js"></script>
		<script src="../java_ui/ui/jquery.ui.core.js"></script>
		<script src="../java_ui/ui/jquery.ui.widget.js"></script>
		<script src="../java_ui/ui/jquery.ui.datepicker.js"></script>
		<!---- the following script is a function "call". "$("#datepicker")" references the input with an id="datepicker"?  and ".datepicker()" is actually the name of the function?-->
		<script>
		$(function() {
			$("#datepicker").datepicker();
		});
		</script>
    </head>
    <body>
		<div class="shadow"><div class="header"></div></div>
		<div class="shadow">
			<?php
			// include menu file
			include '../######/include/menu.php';
			?>
		</div>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		<h1>Block Time ....</h1>
		<span><fieldset id="standardForm">
		<div id="standFormLeft">
			<label>Begin Date</label>
			<!---- this input with the id "datepicker" is referenced in the above function call? --->
			<input tabindex="1" type="date" id="datepicker" name="date1" /><br />
			<input tabindex="3" type="submit" value="Submit" />
		</div>
		<div id="standFormRight">
			<table name="timelist" border='1'>
			<tr>
			<th>Meet Date</th>
			<th>Meet Time</th>
			</tr>
			<?php
			while($row = mysql_fetch_array($result))
			{
			echo "<tr>";
			echo "<td>" . $row['newdate'] . "</td>";
			echo "<td>" . $row['newtime'] . "</td>";
			echo "</tr>";
			}
			echo "</table>";
			?>
		</div>
		</fieldset></span>
	</form><br />
	</body>
</html>
Celauran - I know these questions are extremely basic. But... I learn best when I'm working on an actual project.

Thanks again for all your help.

Pavilion

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 5:20 am
by Celauran
Pavilion wrote:

Code: Select all

		<!--- These lnes are simply calling or including different jquery files -->
		<script src="../java_ui/jquery-1.7.1.js"></script>
		<script src="../java_ui/ui/jquery.ui.core.js"></script>
		<script src="../java_ui/ui/jquery.ui.widget.js"></script>
		<script src="../java_ui/ui/jquery.ui.datepicker.js"></script>
		<!---- the following script is a function "call". "$("#datepicker")" references the input with an id="datepicker"?  and ".datepicker()" is actually the name of the function?-->
		<script>
		$(function() {
			$("#datepicker").datepicker();
		});
		</script>
Yes and yes.
Pavilion wrote:

Code: Select all

			<!---- this input with the id "datepicker" is referenced in the above function call? --->
			<input tabindex="1" type="date" id="datepicker" name="date1" /><br />
Also yes.

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 5:21 am
by Celauran
Pavilion wrote:
Celauran wrote:Because jQuery initiates the request directly, the user never actually sees it. The examples you listed are using GET requests but can be made to work every bit as well with POST requests.

As an aside, these aren't function calls per se. These examples simply show data being sent from one page to another, much like form processing.

So... POST requests can be used... that helps. But... how????
I understood your trepidation to be caused by parameters being passed in the URL, which the POST method eliminates. If I've misunderstood you, please try explaining again.

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 6:24 am
by Pavilion
So... POST requests can be used... that helps. But... how????
I understood your trepidation to be caused by parameters being passed in the URL, which the POST method eliminates. If I've misunderstood you, please try explaining again.
Sorry for the confusion, Celauran. Sometimes I need to muss things over a bit. If we go at this from "nuts and bolts" it will probably work better.

If the following is a function call:

Code: Select all

<!---- the following script is a function "call". "$("#datepicker")" references the input with an id="datepicker"?  and ".datepicker()" is actually the name of the function?-->
<script>
$(function() {
$("#datepicker").datepicker();
});
</script>
Then would the following syntax be correct in passing $_POST data?

Code: Select all

$("#datepicker").datepicker($_POST["date1"]);
where the input name is date1?

I know this is really basic baby-step stuff here. But, I'd prefer to do this right, rather than beat my head against a brick wall because I simply didn't pass a variable correctly.

Thanks again - Pavilion

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 6:32 am
by Celauran
Pavilion wrote:Then would the following syntax be correct in passing $_POST data?

Code: Select all

$("#datepicker").datepicker($_POST["date1"]);
where the input name is date1?
No. What is it you're trying to do here, exactly?

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 7:19 am
by Pavilion
No. What is it you're trying to do here, exactly?
Following is my current blocktime.php file script.

Code: Select all

<?php
session_start();
if(!isset($_SESSION['user_id'])){
header("Location: login.php");
}
// include database connection file, if connection doesn't work the include file will throw an error message
include '../######/include/db_connect.php';
	$today = date('Y-m-d');
    $date1 = $_POST['date1'];
	
// strtotime() will convert nearly any date format into a timestamp which can be used to build a date with the date() function.
$timestamp = strtotime($date1);
$start_date = date("Y-m-d", $timestamp);

$result=mysql_query("
SELECT DATE_FORMAT(List_Dates.DB_Date, '%m/%d/%Y') as newdate, DATE_FORMAT(List_Time.TFM_Time,'%h:%i %p') as newtime
FROM List_Dates, List_Time
WHERE DATE(DATE_FORMAT(List_Dates.DB_Date,'%Y-%m-%d')) LIKE '" . $start_date . "%'
ORDER BY List_Time.TFM_Time
");

?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Block Time</title>
        <link rel="stylesheet" type="text/css" href="../schedule/include/formats.css"/>
		<link rel="stylesheet" href="../java_ui/themes/custom-theme/jquery.ui.all.css">
		<script src="../java_ui/jquery-1.7.1.js"></script>
		<script src="../java_ui/ui/jquery.ui.core.js"></script>
		<script src="../java_ui/ui/jquery.ui.widget.js"></script>
		<script src="../java_ui/ui/jquery.ui.datepicker.js"></script>
		
		<script>
		$(function() {
			$("#datepicker").datepicker();
		});
	</script>
    </head>
    <body>
		<div class="shadow"><div class="header"></div></div>
		<div class="shadow">
			<?php
			// include menu file
			include '../schedule/include/menu.php';
			?>
		</div>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
		<h1>Block Time ....</h1>
		<span><fieldset id="standardForm">
		<div id="standFormLeft">
			<label>Begin Date</label>
			<input tabindex="1" type="date" id="datepicker" name="date1" /><br />
			<input tabindex="3" type="submit" value="Submit" />
		</div>
		<div id="standFormRight">
			<table name="timelist" border='1'>
			<tr>
			<th>Meet Date</th>
			<th>Meet Time</th>
			</tr>
			<?php
			while($row = mysql_fetch_array($result))
			{
			echo "<tr>";
			echo "<td>" . $row['newdate'] . "</td>";
			echo "<td>" . $row['newtime'] . "</td>";
			echo "</tr>";
			}
			echo "</table>";
			?>
		</div>
		</fieldset></span>
	</form><br />
	</body>
</html>
The script works great. When I hit the submit button, the SELECT query picks up the posted date and returns appropriate data to the table. But... that should be happening on an event. The user should NOT have to press submit. I want to reserve the Submit actions for AFTER the user has selected a block of time from the table. (Well eventually I want to use some jQuery UI drag and drop functionality - but that is another problem and can wait).

At any rate, ideally... I'd like to:
  1. Break out the php script from the above file.
  2. Insert the said php script into it's own file.
  3. Use a jQuery function to trigger the new php script (rather than a submit button)
  4. Build submit actions within THIS file to process block time requests
Am I heading in a legitimate direction.

And

if functions in php, jquery act the same as functions in VB then why is this ...

Code: Select all

$("#datepicker").datepicker($_POST["date1"]);


Wrong?

Isn't $_POST["date1"] a variable?
Isn't datepicker() a function call?

Thank you for your patience here Celauran, your answer sort of threw me. I thought there might be syntax issues - or something of the sort. When you said php functions act like VB functions, then I thought my understanding was opening up, only to find out I still don't have a clue. :banghead: :)

Pavilion

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 7:24 am
by Pavilion
Celauran - it should also be noted that my SQL block is NOT compliant with PDO in this script. This is because I'm doing all my testing, rewriting code, etc... in the first files I built (BEFORE moving to PDO). Once I get the basics figured out, I can make it PDO compliant and move it to my main file structure.

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 8:08 am
by Celauran
Pavilion wrote:if functions in php, jquery act the same as functions in VB then why is this ...

Code: Select all

$("#datepicker").datepicker($_POST["date1"]);


Wrong?

Isn't $_POST["date1"] a variable?
Isn't datepicker() a function call?
I suppose it could work depending on the contents of $_POST['date1']. Take a look at datepicker's available methods.

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 8:25 am
by Celauran
So looking at your form, what I think you'd want to do is the following:
  • Add an onchange listener for #datepicker
  • Listener function grabs the value of #datepicker and sends it to some PHP script
  • PHP script processes the SQL query and returns a string containing formatted results
  • jQuery updates the form

Re: Newbie to Javascript, jQuery and Ajax

Posted: Thu Apr 05, 2012 9:35 am
by Celauran
Here's a very simplistic example of what I mean

Code: Select all

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Foo</title>
        <link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui.css" />
        <style type="text/css">
            div#hidden
            {
                display: none;
            }
        </style>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/jquery-ui.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#date').change(function() {
                    $.post('ajax.php', { date: $(this).val()}, function(data) {
                        $('#hidden').html(data);
                        $('#hidden').css('display', 'inline');
                    });
                });
            });
        </script>
    </head>
    <body>
        <form id="someForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <fieldset>
                <input type="text" name="date" id="date" />
            </fieldset>
        </form>
        <div id="hidden">

        </div>
    </body>
</html>
ajax.php

Code: Select all

<?php

if (!empty($_POST['date']))
{
    $date = new DateTime($_POST['date']);
    echo $date->format('d/m/Y');
}
Rather than creating a DateTime object, you'd run your query here, but I think this demonstrates the general principle well enough.