Newbie to Javascript, jQuery and Ajax

JavaScript and client side scripting.

Moderator: General Moderators

User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Newbie to Javascript, jQuery and Ajax

Post by Celauran »

Pavilion wrote:It is assembling one array at a time and pushing it out of the each to the "main" array for lack of a better word.
Precisely. It creates an array of arrays. That should give you the multidimensional array you need to send to block_data so you can then use a foreach loop on $_POST['bind_array']
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Celauran:

THANK YOU SO MUCH!!!!! I'm feeling so much better about all this now. Your suggestion has worked. In addition, I've figured out how to use the foreach statement to populate an html table and return it to block.php. Following is my block_data.php code:

Code: Select all

<?php
session_start();
// include database connection file, if connection doesn't work the include file will throw an error message
include '../schedule/include/db_connect.php';

if (!empty($_POST['bind_array']))
{
	$array = $_POST['bind_array'];
}
else
?>
<!DOCTYPE html>
<html>
<table name='timelist' border='1'>
<tr>
<th>User</th>
<th>Block_ID</th>
<th>Segment Date</th>
<th>Segment Time</th>
<th>Status</th>
<th>Record Date</th>
</tr>

<?php
$a = $array; 
foreach ($a as $b) 
{  
	echo "<tr>";   
	echo "<td>". $b[0] ."</td>";   
	echo "<td>". $b[1] ."</td>";   
	echo "<td>".$b[2]."</td>";
	echo "<td>". $b[3] ."</td>";   
	echo "<td>".$b[4]."</td>";   
	echo "<td>".$b[5]."</td>";
	echo "</tr>";   
$i++;   
}   
echo"</table>";
?>
</html>
Again - thank you so much. But... now I have another question. Ultimently - the goal is to insert this data into mySQL tables. The reason I generated a block_id is that I will be using it to connect data between multiple tables (in many-to-many relationships).

Right after a user blocks out time, data will have to be inserted into at least two tables. This means I will need to pull selected values from the array for each INSERT STATEMENT.

Following is a sample INSERT statement from the original register.php file in this application:

Code: Select all

$query = "INSERT INTO UserTbl (FName, LName, EmailAddress, Password, 1stContact, Activation) VALUES ('{$fname}', '{$lname}', '{$email}', '{$hash}', '{$firstcontact}', '{$activation}')";
So... do I encase the applicable INSERT statement within a foreach statement, in such a way that the INSERT Statement is run "foreach" row?

By encasing the INSERT within a foreach, then I can name variables as follows:

Code: Select all

$user = $b[0];
$block_id = $b[1]; /// etc.....
and use these variables within the INSERT Statement.

Am I heading in the right direction?[/color]

Celauran, I just want to check this out before pushing forward. After the last several days, I just want to know I'm onn the right path BEFORE pushing forward.

Thanks again - Pavilion.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Newbie to Javascript, jQuery and Ajax

Post by Celauran »

Running queries inside any kind of loop is almost always the wrong solution. You can build the query outside the loop, then add the values inside the loop, then execute the query after the loop has terminated.

Code: Select all

$query = "INSERT INTO table_name (colA, colB, colC) VALUES ";
foreach ($foo as $bar)
{
    $query .= "($bar[0], $bar[1], $bar[2]), ";
}
$sql->query($query);
Or you can make use of prepared statements and bound parameters.

Also, I've noticed you passing data around from one variable to another for no apparent reason. For example, in your last code snippet, you had

Code: Select all

$array = $_POST['bind_array'];
...
$a = $array;
...
foreach ($a as $b)
whereas you could have simply used

Code: Select all

foreach ($_POST['bind_array'] as $something)
Now don't get me wrong, if you find this helps with clarity or provides some other benefit to you, then by all means continue. I just wanted to make sure you realized it wasn't necessary.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Hello Celauran:
Celauran wrote:Running queries inside any kind of loop is almost always the wrong solution. You can build the query outside the loop, then add the values inside the loop, then execute the query after the loop has terminated.

Code: Select all

$query = "INSERT INTO table_name (colA, colB, colC) VALUES ";
foreach ($foo as $bar)
{
    $query .= "($bar[0], $bar[1], $bar[2]), ";
}
$sql->query($query);
Thank you - this does help. On a gut level, I was a bit concerned about the approach I outlined.
Also, I've noticed you passing data around from one variable to another for no apparent reason. For example, in your last code snippet, you had

Code: Select all

$array = $_POST['bind_array'];
...
$a = $array;
...
foreach ($a as $b)
whereas you could have simply used

Code: Select all

foreach ($_POST['bind_array'] as $something)
Now don't get me wrong, if you find this helps with clarity or provides some other benefit to you, then by all means continue. I just wanted to make sure you realized it wasn't necessary.
You hit the nail on the head. I am aware of the redundancy, but at this point in the learning process - actually assigning variables the way I do helps me track. Also.... just from years of coding typing "$_POST['anything]" repeatedly can lead to spelling errors. Assigning something like that to a variable helps cut down on spelling errors.
________________________________________

I'm out of the office all day today. So... will attempt my INSERT statements tonight. In the meantime I've a few other questions to shoot your direction:

Question 1 - applicable script:

Code: Select all

// document.ready function will not allow any functions to execute unless the page is fully loaded.
$(document).ready(function() {
	$(function () {
		/* Outer array. "pass_array" IS A VARIABLE. If it were preceded by "var" then "pass_array" would NOT be available for use outside this function. */
		pass_array = [];
		$( "#selectable" ).selectable({
			stop: function() {
				$( ".ui-selected", this ).each(function() {
					/* Inner array. "inner" IS A VARIABLE. If it were preceded by "var" then "inner" would NOT be available for use outside this function. */
                    inner = [];
					var index = $( "#selectable li" ).index( this );
					segment_time = $(this).text();
					if(segment_time) /* this if statement does not allow a push to occur unless there is a value in the var "segment_time" */
					{
					
					/* Creates a multidimensional array of user_id, block_id, segment_date, segment_time, "blocked", record_date passed through .each(function()). 1st line assembles the "inner" array and passes it onto the "outer" pass_array.push.*/
					inner.push(user, block_id, segment_date, segment_time, "Blocked", record_date);
					pass_array.push(inner);
					}
				});
				
				$.post("block_data.php",{bind_array:pass_array},function(data){
				$('#standFormRight').html(data);
				});

			}
		});
	});

				$('#test').click(function() {
					$.post("block_data.php",{bind_array:pass_array},function(data){
					$('#standFormRight').html(data);
					});
					alert("click event");
				});
});
- specific block:

[syntax=php$('#test').click(function() {
$.post("block_data.php",{bind_array:pass_array},function(data){
$('#standFormRight').html(data);
});
alert("click event");
});[/syntax]

If I place this block inside the function() block above - it does not work. It does work placed where it is now - but the data returned only shows for a second and then disappears. I am assuming the disappearing data is due to misplacement of the .click function.

Where should this block be placed so that returning data from block_data.php stays on screen?

Thanks Celauran:

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Newbie to Javascript, jQuery and Ajax

Post by Celauran »

No idea why the text would just disappear. Maybe someone who knows jQuery a little better will have some insight.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Celauran - and anyone else reading this:

I found the solution. All I had to do was include a

Code: Select all

return false
at the end of my .click(function(). Now the function looks like this:

Code: Select all

$('#set_block').click(function() {
$.post("block_data.php",{bind_array:pass_array},function(data){
$('#standFormRight').html(data);
});
return false
});
After inserting return false the page no longer refreshes upon execution of the $.post script, and the resulting table does not disappear.

Now - onto cleaning some other things up and writing my INSERT statements.

Thanks so much for all your help - Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Celauran wrote:Running queries inside any kind of loop is almost always the wrong solution. You can build the query outside the loop, then add the values inside the loop, then execute the query after the loop has terminated.

Code: Select all

$query = "INSERT INTO table_name (colA, colB, colC) VALUES ";
foreach ($foo as $bar)
{
    $query .= "($bar[0], $bar[1], $bar[2]), ";
}
$sql->query($query);
Hello Celauran:

Well I've tried this approach - and as simple as the syntax is, I'm running into problems.

Following is my syntax:

Code: Select all

$foo = $_POST['bind_array'];
	
$query = "INSERT INTO Time_Segments (BlockID) VALUES ";

foreach ($foo as $bar)
{
$query .= "'($bar[1])', "; 
}
mysql_query($query) or die(mysql_error());
Firstly - when I started running into problems I ran the INSERT statement as follows (with $block_id = 205-49798):

Code: Select all

$query = "INSERT INTO Time_Segments (BlockID) VALUES ('{$block_id}')";
Then the INSERT works.

Something is wrong with the syntax in foreach, because the first part of the statement doesn't change when I run it as a whole statement.

Following is the error message that I receive:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''(205-49930)', '(205-49930)', '(205-49930)', '(205-49930)', '(205-49930)',' at line 1
Celauran - I've tried revising the syntax of $query .= "'($bar[1])', "; , but everything I attempt leads to errors.

What am I missing?

Thanks so much - Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

P.S.

When I run the snippet - as you first suggested:

Code: Select all

$foo = $_POST['bind_array'];
	
$query = "INSERT INTO Time_Segments (User_ID, BlockID, SegmentDate) VALUES ";

foreach ($foo as $bar)
{

$query .= "($bar[0], $bar[1], $bar[2]), ";

}

mysql_query($query) or die(mysql_error()); // this is the mysql_query call. No data will be inserted into the table without this call.
Here is the resulting error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Something is happening and I'm not able to figure it out. :?

Again - thanks so much.

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Newbie to Javascript, jQuery and Ajax

Post by Celauran »

There's an extraneous comma at the end.

Code: Select all

...
foreach ($foo as $bar)
{
    $query .= "($bar[0], $bar[1], $bar[2]), ";
}
$query = rtrim($query, ', ');
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Celauran wrote:There's an extraneous comma at the end.

Code: Select all

...
foreach ($foo as $bar)
{
    $query .= "($bar[0], $bar[1], $bar[2]), ";
}
$query = rtrim($query, ', ');
Thanks Celauran

That did the trick.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Under the heading of: If it's not one thing it's another .....

The INSERT is working great. However the formatting of the INSERTED time value is causing problems.
  1. mySQL List_Time table is storing time values in a 24 hour format
  2. In order to create a user-friendly format, I've been converting the Times in List_Time to 12 hour format for the select list.
  3. So.... times selected and submitted to javascript for an INSERT into the database are coming back in a 12 hour format.
  4. I thought this would easily be solved by reformatting the time BEFORE the INSERT statement. Common sense dictates catching the time in the javascript <script> BEFORE submission to the php routimes. So... I am using the following snippet of code w/ var segment_time as the submitted time after user selects it from the list.

Code: Select all

var d=segment_time;
var newTime = d.toString("HH:mm:ss");

alert(newTime + " test");
However, no matter what syntax I use within the toString() brackets - the only thing alert shows as a new time for 01:30 PM is 01:30 PM, when it should return 13:30:00.

The formatting will be important in situations where I need to compare values in my List_Time table to values in the table where I'll be storing user's selected time blocks.
_______________________
One other thing, I've also tried the toTimeString() method. The results are null with this method.

__________________
Edited at 10:12 PM - Well I did figure out one step:

Code: Select all

var d = (new Date (new Date().toDateString() + ' ' + segment_time));
alert(d + " test");
Now... how do I extract the time (in a 24 hour format) from the resulting string. When I try substring() I get null.
____________________
Any input on this problem would be greatly appreciated. Thanks in advance - Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Newbie to Javascript, jQuery and Ajax

Post by Pavilion »

Just posting this in case someone else has the same question. But I figured out the process of extracting a time from a Javascript DateTime object.
  1. Javascript does NOT have a Time object. So... in order to convert a 12 hour time format to a 24 hour time format, it is necessary to convert a time into a DateTime object, then extract the time in a 24 hour format.
Following is an example of the script I used:

Code: Select all

/* The following block formats segment_time in a 24 hour format for mySQL tables TIME cells. Steps of reformatting are as follows:
1. var d_time creates a Javascript DateTime object. Javascript does not have Time objects.
2. var seg_min extraxts minutes from the d_time object. If seg_min is <10 a 0 is added to the string.
3. var segtime creates the time string by a.) extracting hours, b.) adding colons and c.) adding minutes to the string*/
					
var d_time = (new Date (new Date().toDateString() + ' ' + segment_time));

var seg_min = d_time.getMinutes();
if (seg_min < 10){
seg_min = "0" + seg_min
}
var segtime = d_time.getHours() + ":" + seg_min + ":00";
// Now that we have a valid 24 hour formatted time string move onto creating a multidimentsional array for the INSERT statment. 
Post Reply