...

View Full Version : Javascript works in heredoc, but not when heredoc is put in for loop



milesdriven
07-23-2012, 07:14 PM
This is a php script that receives posted data from a login form, then sends a heredoc of javascript and html to the browser. This javascript works fine. It uses static values instead of php variables.

When I put this heredoc in a for loop and replaced the static values with php variables, the javascript stopped working. I had to delete much of this file to make it small enough to post, but hopefully there is enough left to diagnose.

The first screen of code directly below works fine. The screen that shows the code in the for loop (that doesn't work) is shown in the second screen below.



<?php
if(isset($_POST['user_id']))
{
if(isset($_POST['password']))
{
$conn = mysql_connect('localhost','user','xxxxxxxx');
mysql_select_db('daily_schedule');

$user_id = $_POST['user_id'];
$password = $_POST['password'];

$user_id_escaped = mysql_real_escape_string($user_id);
$password_escaped = mysql_real_escape_string($password);
$str = date("l F j Y");

$qry = "SELECT * ".
"FROM customers ".
"WHERE user_id = '$user_id_escaped' ".
"and password = '$password_escaped'";


$get = mysql_query($qry);

if(mysql_num_rows($get) == 1)
{
$cust_data = mysql_fetch_assoc($get);
session_start();
$_SESSION['first_name'] = $cust_data['first_name'];
$_SESSION['last_name'] = $cust_data['last_name'];
$_SESSION['user_id'] = $cust_data['user_id'];
$_SESSION['password'] = $cust_data['password'];


print <<<DEMO

<!DOCTYPE html>

<html>
<head>
<title>My Web Page</title>
<script type="text/javascript">
var request;
request = new XMLHttpRequest();
var breeze;
breeze = new XMLHttpRequest();
var given;
given = new XMLHttpRequest();
var crystal;
crystal = new XMLHttpRequest();
var moon;
moon = new XMLHttpRequest();
</script>

<style type="text/css">
.horizontal ul
{
list-style-type: none;
margin: 0;
padding: 0;
}

body {margin: 10em;}

#form {margin: 1em 1em;}


.horizontal ul li
{
display: inline;
width: 200px;
height: 50px;
background: #ccc;
text-align: center;
padding: .1em;
font-size: .8em
}
</style>

</head>

<body>
<noscript>Please Enable Javascript</noscript>


<p>$str</p>
<p>Customer Side</p>
<p>Your Local Time:<SPAN>&nbsp&nbsp&nbsp&nbsp<SPAN id='showtimehere'></SPAN></p>

<script type="text/javascript">
<!--
function showtime()
{
var Donut = new Date();
var day = Donut.getDate(); //returns day of month (1-31)
var year = Donut.getFullYear(); //returns year (xxxx)
var hours = Donut.getHours(); //returns hours (0-23)
var dn = "AM";
if(hours>=12)
{
dn="PM"
hours = hours-12
}
if(hours==0)
{
hours=12
}
var minutes = Donut.getMinutes(); //returns minutes (0-59)
if(minutes<=9)
{
minutes = "0"+minutes
}
var time = hours+":"+minutes+" "+dn;
document.getElementById('showtimehere').innerHTML = time;
setTimeout("showtime()", 60000);
}
showtime();
</script>

<div class=horizontal>
<form >
<ul id="May120128AM_list" style="display: block;">

<li><input type="hidden" id="May120128AM_check_if_display_block_or_none_onload" name="element_id" value="May120128AM_list"></li>


<li><input type="hidden" id="May120128AM" name="apt_time" value="May120128AM"></li>

<li><input type="hidden" name="user_id" id="May120128AM_user_id" value="{$_SESSION['user_id']}"/></li>

<li><input type="hidden" name="password" id="May120128AM_password" value="{$_SESSION['password']}"/></li>

<li id="May120128AM_apt_time">8:00 - 8:45 AM</li>



<li id = 'May120128AM_Schd_Can'></li>

<li id = 'May120128AM_Nt_Avail'></li>


<li id = 'May120128AM_Avail' ></li>

</ul>
</form>
</div>

<script type="text/javascript">
var apt_time = encodeURIComponent(document.getElementById("May120128AM").value);
var userid = encodeURIComponent(document.getElementById("May120128AM_user_id").value);
//var password = encodeURIComponent(document.getElementById("May120128AM_password").value);
var parameters = "apt_time="+apt_time+"&user_id="+userid

request.open("POST", "/cgi-bin/check_apts_onload_with_just_apt_time.html", true);
request.onreadystatechange = function()
{
if(request.readyState == 4)
{
if(request.status == 200)
{
var SchdCan = document.getElementById('May120128AM_Schd_Can');
var NtAvail = document.getElementById('May120128AM_Nt_Avail');
var Avail = document.getElementById('May120128AM_Avail');

if(request.responseText == "available")
{
SchdCan.innerHTL = ''
NtAvail.innerHTML = ''
Avail.innerHTML = "Available For {$_SESSION['first_name']} <button id='May120128AM_Click_To_Sch' name='apt_time' value='May120128AM' onClick='clickToSchedule(); return false'>Click Here To Schedule</button>"
}
if(request.responseText == "you are scheduled")
{

SchdCan.innerHTML = "{$_SESSION['first_name']}, You Are Scheduled <button id='May120128AM_Click_To_Can' name='apt_time' value='May120128AM' onClick = 'clickToCancel(); return false'>Click Here To Cancel</button>"

NtAvail.innerHTML = ''
Avail.innerHTML = ''
}
if(request.responseText == "not available")
{

SchdCan.innerHTML = ''
NtAvail.innerHTML = 'not available'
Avail.innerHTML = ''



} //Closing if(responseText == "")

} //Closing if(request.status == 200)

} //Closing if(request.readyState==4)
} //Closing onreadystatechange function
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(parameters);
</script>





<script type="text/javascript">
//CSS Display Block Or None Onload- Start
var display = encodeURIComponent(document.getElementById("May120128AM_check_if_display_block_or_none_onload").value);
var parameters = "element_id="+display
breeze.open("POST", "/cgi-bin/control_panel_css_check_table_to_determine_if_status_is_display_or_hide_onload.html", false);
breeze.onreadystatechange = function()
{
if(breeze.readyState == 4)
{
if(breeze.status == 200)
{
if(breeze.responseText == "none")
{
var car = document.getElementById('May120128AM_list');
car.style.display = "none";
}
if(breeze.responseText == "block")
{
var car = document.getElementById('May120128AM_list');
car.style.display = "block";
}
//alert(breeze.responseText);
}
}
}
breeze.setRequestHeader("Content-type","application/x-www-form-urlencoded");
breeze.send(parameters);
//CSS Display Block Or None Onload- End
</script>





<script type="text/javascript">
var Bath = new Date();
var hour = Bath.getHours(); //returns hours (0-23)
var parameters = "client_hour="+hour
given.open("POST","/cgi-bin/server_time_to_adjust_client_apt_time.html", false);
given.onreadystatechange = function()
{
if(given.readyState == 4)
{
if(given.status == 200)
{
//alert(given.responseText);
if(given.responseText == "-3")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "5:00 - 5:45 AM"
}
if(given.responseText == "-2")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "6:00 - 6:45 AM"
}
if(given.responseText == "-1")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "7:00 - 7:45 AM"
}
if(given.responseText == "0")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "8:00 - 8:45 AM"
}
if(given.responseText == "+1")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "9:00 - 9:45 AM"
}
if(given.responseText == "+2")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "10:00 - 10:45 AM"
}
if(given.responseText == "+3")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "11:00 - 11:45 AM"
}
if(given.responseText == "+4")
{
var client = document.getElementById('May120128AM_apt_time');
client.innerHTML = "12:00 - 12:45 AM"
}
}
}
}
given.setRequestHeader("Content-type","application/x-www-form-urlencoded");
given.send(parameters);
</script>



<script type="text/javascript">
var peanut = new Date();
var month = peanut.getMonth();
if(month==0){month = "Jan"};
if(month==1){month = "Feb"};
if(month==2){month = "Mar"};
if(month==3){month = "Apr"};
if(month==4){month = "May"};
if(month==5){month = "Jun"};
if(month==6){month = "Jul"};
if(month==7){month = "Aug"};
if(month==8){month = "Sep"};
if(month==9){month = "Oct"};
if(month==10){month = "Nov"};
if(month==11){month = "Dec"};
var day = peanut.getDate(); //returns day of month (1-31)
var year = peanut.getFullYear(); //returns year (xxxx)
var hour = peanut.getHours(); //returns hours (0-23)
if(hour == 0){hour = '12AM'}
if(hour == 1){hour = '1AM'}
if(hour == 2){hour = '2AM'}
if(hour == 3){hour = '3AM'}
if(hour == 4){hour = '4AM'}
if(hour == 5){hour = '5AM'}
if(hour == 6){hour = '6AM'}
if(hour == 7){hour = '7AM'}
if(hour == 8){hour = '8AM'}
if(hour == 9){hour = '9AM'}
if(hour == 10){hour = '10AM'}
if(hour == 11){hour = '11AM'}
if(hour == 12){hour = '12AM'}
if(hour == 13){hour = '1PM'}
if(hour == 14){hour = '2PM'}
if(hour == 15){hour = '3PM'}
if(hour == 16){hour = '4PM'}
if(hour == 17){hour = '5PM'}
if(hour == 18){hour = '6PM'}
if(hour == 19){hour = '7PM'}
if(hour == 20){hour = '8PM'}
if(hour == 21){hour = '9PM'}
if(hour == 22){hour = '10PM'}
if(hour == 23){hour = '11PM'}
var dateTime = month+day+year+hour;
var parameters = "dateTime="+dateTime

crystal.open("POST", "/cgi-bin/check_current_dateTime_to_see_if_this_apt_time_is_now_so_display_none.html", false);
crystal.onreadystatechange = function()
{
if(crystal.readyState == 4)
{
if(crystal.status == 200)
{
}
}
}
crystal.setRequestHeader("Content-type","application/x-www-form-urlencoded");
crystal.send(parameters);
//setTimeout("aptTimeDisabled()", 60000);
//} //Close function
//Disable Current Appointment Time
//alert(hour);
</script>
</body>


</html>
DEMO;

} // Close if(mysql_num_rows($get) == 1)
} // Close if(isset($_POST['password']))
} // Close if(isset($_POST['user_id']))
?>




This file below is a for loop with the same javascript. The differences are it uses variables instead of static values, the javascript doesn't work, and parts of it have been deleted to make it small enough to post to the forum. I think part of the problem is the <input> elements that are inside the <li> elements are not sending their values to the javascript. That is only a guess. This is html and javascript placed in a heredoc, which is placed in a for loop.

This entire file is included() in the file the login form points to. That file takes care of the database connection, session start and defines session array using mysql_fetch_assoc. The ajax objects have been created and work fine. They are not shown here. Thanks for reading this. Hopefully someone can show me what I'm doing wrong.

Here it is:


<?php
if(isset(user_id))
{

$m = date("n"); //Finds todays month (From 1-12)

$days_in_month = date("t"); //The number of days in the current month

$f = date("F"); //January, February, etc

$M3 = date("M"); //Jan, Feb, etc

$Y = date("Y"); //Finds todays year(20xx)

$w = date("w",mktime(0,0,0,$m,1,$Y)); //Finds the day of the week (ie, Sunday) of the 1st day of the month.

$today = date("j"); //Finds todays date (From 1-31)

$nbsp = "";

$ecds = "";


for($empty = 1; $empty <= $w; $empty++){//Daily schedule empty days
$ecds.="<td>&nbsp;</td>";
}

for($hi = 1; $hi <= $days_in_month; $hi++)
{
print <<<DEMO
<div id="$M3$hi$Y" style="display: none;
text-align: center;
width: 33em;
height: 26em;
background: #B3ECFF;
margin-bottom: 2em;"
>

<p><a href='' onClick="hideSchedule('$M3$hi$Y','$m'); return false">Close</a></p>
<p style='font-size: .8em;'>$M3 $hi Schedule</p>

{$_SESSION["first_name"]}&nbsp{$_SESSION["last_name"]}&nbsp&nbsp&nbsp{$str}


<style type="text/css">
.horizontal ul
{
list-style-type: none;
margin: 0;
padding: 0;
}


.horizontal ul li
{
display: inline;
width: 200px;
height: 50px;
background: #ccc;
text-align: center;
padding: .1em;
font-size: .8em
}
</style>


<p>Your Local Time:<SPAN>&nbsp&nbsp&nbsp&nbsp<SPAN id="showtimehere"></SPAN></p>

<script type="text/javascript">
showtime();
</script>

<div class=horizontal>
<form >
<ul id= "{$M3}{$hi}{$Y}8AM_list" style="display: block;
text-align: left;">

<li><input type="hidden" id="{$M3}{$hi}{$Y}8AM_check_if_display_block_or_none_onload" name="element_id" value="{$M3}{$hi}{$Y}8AM_list"></li>


<li><input type="hidden" id="{$M3}{$hi}{$Y}8AM" name="apt_time" value="{$M3}{$hi}{$Y}8AM"></li>

<li><input type="hidden" name="user_id" id="{$M3}{$hi}{$Y}8AM_user_id" value="{$_SESSION['user_id']}"/></li>


<li id="{$M3}{$hi}{$Y}8AM_apt_time">8:00 - 8:45 AM</li>



<li id = "{$M3}{$hi}{$Y}8AM_Schd_Can"></li>

<li id = "{$M3}{$hi}{$Y}8AM_Nt_Avail"></li>


<li id = "{$M3}{$hi}{$Y}8AM_Avail"></li>

</ul>
</form>
</div>
THIS PART IS ONE OF THE PARTS THAT DOESNT WORK IN THE HEREDOC
<script type="text/javascript">
var apt_time = encodeURIComponent(document.getElementById("{$M3}{$hi}{$Y}8AM").value);
var userid = encodeURIComponent(document.getElementById("{$M3}{$hi}{$Y}8AM_user_id").value);
var data = "apt_time="+apt_time+"&user_id="+userid

moon.open("POST", "/cgi-bin/check_apts_onload_with_just_apt_time.html", false);
moon.onreadystatechange = function()
{
if(moon.readyState == 4)
{
if(moon.status == 200)
{
var SchdCan = document.getElementById("{$M3}{$hi}{$Y}8AM_Schd_Can");
var NtAvail = document.getElementById("{$M3}{$hi}{$Y}8AM_Nt_Avail");
var Avail = document.getElementById("{$M3}{$hi}{$Y}8AM_Avail");

if(moon.responseText == "available")
{
SchdCan.innerHTL = ''
NtAvail.innerHTML = ''
Avail.innerHTML = "Available For {$_SESSION['first_name']} <button id="{$M3}{$hi}{$Y}8AM_Click_To_Sch" name="apt_time" value="{$M3}{$hi}{$Y}8AM" onClick='clickToSchedule(); return false'>Click Here To Schedule</button>"
}
if(moon.responseText == "you are scheduled")
{

SchdCan.innerHTML = "{$_SESSION['first_name']}, You Are Scheduled <button id="{$M3}{$hi}{$Y}8AM_Click_To_Can" name="apt_time" value="{$M3}{$hi}{$Y}8AM" onClick = 'clickToCancel(); return false'>Click Here To Cancel</button>"

NtAvail.innerHTML = ''
Avail.innerHTML = ''
}
if(moon.responseText == "not available")
{

SchdCan.innerHTML = ''
NtAvail.innerHTML = 'not available'
Avail.innerHTML = ''



} //Closing if(responseText == "")

} //Closing if(moon.status == 200)

} //Closing if(moon.readyState==4)
} //Closing onreadystatechange function
moon.setRequestHeader("Content-type","application/x-www-form-urlencoded");
moon.send(data);
</script>





<script type="text/javascript">
//CSS Display Block Or None Onload- Start
var display = encodeURIComponent(document.getElementById("{$M3}{$hi}{$Y}8AM_check_if_display_block_or_none_onload").value);
var parameters = "element_id="+display
breeze.open("POST", "/cgi-bin/control_panel_css_check_table_to_determine_if_status_is_display_or_hide_onload.html", false);
breeze.onreadystatechange = function()
{
if(breeze.readyState == 4)
{
if(breeze.status == 200)
{
if(breeze.responseText == "none")
{
var car = document.getElementById("{$M3}{$hi}{$Y}8AM_list");
car.style.display = "none";
}
if(breeze.responseText == "block")
{
var car = document.getElementById("{$M3}{$hi}{$Y}8AM_list");
car.style.display = "block";
}
//alert(breeze.responseText);
}
}
}
breeze.setRequestHeader("Content-type","application/x-www-form-urlencoded");
breeze.send(parameters);
//CSS Display Block Or None Onload- End
</script>








<br />
</div>

DEMO;
}
)
?>

Fou-Lu
07-23-2012, 07:47 PM
This creates a nice disaster of output source code.
I'm no JS writer, so I don't know to what extent of leniency it provides. I would presume its very unhappy about your reuse of variable names over multiple iterations.
Write the JS properly with functions instead. There is no reason to rewrite the same handling over and over again when you can simply provide the necessary arguments to the function in question.

So if I had to guess, this is all fault of JS. If it renders the source properly, then PHP has done its job.

Keleth
07-23-2012, 07:58 PM
Yah, can you show the rendered HTML? Does the console show anything?

DrDOS
07-23-2012, 08:10 PM
I've run in to this exact problem and the solution is very simple to implement. You have to declare a javascript array, then use php to push the data from the php array into the javascript array, then you just use javascript, in any way, to access the array elements. The reason why you have to do it this way is the data may be in different types, and javascript has trouble with the different types if it's not in array form. If the data is all of one type you can write the code your way, but normally it isn't. For instance if you want a form to be reloaded with the same data as submitted, you can just loop over all the inputs with the javascript array.

milesdriven
07-23-2012, 08:34 PM
Hi DrDos, I just noticed your reply. I remember you saying that before. I don't know how to write it thought, could you give me an example?



Fou-Lu, you suggested writing functions for everything, then adding arguments to those function. That way the arguments go through the loop iterations instead of the whole function. I know this is a php thread, but I have an example to show you of what I think you are saying.

Here is that example:


function getThis(one)
{
document.getElementById(one).innerHTML = "some text";
}


How do I tell that function to execute onload? Like this?


<script type="text/javascript">
getThis($phpvariable);
</script>


The rendered html is below. Its a huge script. I copied a part of it. The important thing is all the element id's are coming out fine. They look like accurate html to me. Php is iterating through them. So its the javascript that's complaining. If everyone agrees with this, then at least I know the php syntax I'm using is fine.



<div class=horizontal>
<form >
<ul id= "Jul220128AM_list" style="display: block;
text-align: left;">

<li><input type="hidden" id="Jul220128AM_check_if_display_block_or_none_onload" name="element_id" value="Jul220128AM_list"></li>


<li><input type="hidden" id="Jul220128AM" name="apt_time" value="Jul220128AM"></li>

<li><input type="hidden" name="user_id" id="Jul220128AM_user_id" value="202020"/></li>


<li id="Jul220128AM_apt_time">8:00 - 8:45 AM</li>



<li id = "Jul220128AM_Schd_Can"></li>

<li id = "Jul220128AM_Nt_Avail"></li>


<li id = "Jul220128AM_Avail"></li>

</ul>
</form>
</div>

<script type="text/javascript">
var apt_time = encodeURIComponent(document.getElementById("Jul220128AM").value);
var userid = encodeURIComponent(document.getElementById("Jul220128AM_user_id").value);
var data = "apt_time="+apt_time+"&user_id="+userid

moon.open("POST", "/cgi-bin/check_apts_onload_with_just_apt_time.html", false);
moon.onreadystatechange = function()
{
if(moon.readyState == 4)
{
if(moon.status == 200)
{
var SchdCan = document.getElementById("Jul220128AM_Schd_Can");
var NtAvail = document.getElementById("Jul220128AM_Nt_Avail");
var Avail = document.getElementById("Jul220128AM_Avail");

if(moon.responseText == "available")
{
SchdCan.innerHTL = ''
NtAvail.innerHTML = ''
Avail.innerHTML = "Available <button id="Jul220128AM_Click_To_Sch" name="apt_time" value="Jul220128AM" onClick='clickToSchedule(); return false'>Click Here To Schedule</button>"
}
if(moon.responseText == "you are scheduled")
{

SchdCan.innerHTML = "You Are Scheduled <button id="Jul220128AM_Click_To_Can" name="apt_time" value="Jul220128AM" onClick = 'clickToCancel(); return false'>Click Here To Cancel</button>"

NtAvail.innerHTML = ''
Avail.innerHTML = ''
}
if(moon.responseText == "not available")
{

SchdCan.innerHTML = ''
NtAvail.innerHTML = 'not available'
Avail.innerHTML = ''



} //Closing if(responseText == "")

} //Closing if(moon.status == 200)

} //Closing if(moon.readyState==4)
} //Closing onreadystatechange function
moon.setRequestHeader("Content-type","application/x-www-form-urlencoded");
moon.send(data);
</script>

Keleth
07-23-2012, 08:57 PM
It does look like the JS rendered properly, so while I donno exactly what to expect, it does look OK. Again, the JS console doesn't show anything?

milesdriven
07-23-2012, 09:01 PM
Here I go again ( laughing at myself): The JS Console? Is that a part of firebug?

By the way, do you know how to use php to push data from a php array into a javascript array? Someone posted a message to this thread saying that will solve this. I'm studying that.

The browser source looks fine too me too.


Thanks very much for your help.

Keleth
07-23-2012, 09:04 PM
Well, firebug does have a JS console, that's the one I use, but a lot of browsers have built in consoles as well. If you're using Firebug, the left most tab should be console (next to HTML). In your javascript code, you can put console.log('string' + orVariable) and it'll write to the console. It will also display any errors the javascript has, show any data sent/received via AJAX (including all the headers, which is nice).

milesdriven
07-23-2012, 09:06 PM
I use firefox. Thanks again.

Keleth
07-23-2012, 09:15 PM
I use firefox. Thanks again.

Firefox's version of firebug does have the console.

As for pushing data from PHP to Javascript, you do it the same way you write any other Javascript: echo out the values so it looks like proper javascript on the text end.

Fou-Lu
07-23-2012, 09:31 PM
The problem here is that is a partial block of output. You have <script> pulled through every iteration which uses the same variables on each output, and I'd assume that makes it very unhappy. If it works, I'd expect it to only work on the last block, but I cannot say for sure as I'm not sure how the ECMA parser deals with duplicates in separate blocks (is it valid at all, and if so is it valid between its declaration and the next? That I don't know).

As for the PHP and JS. Think outside of the L7. PHP is fully parsed and returned as text before the JS is executed. This is to your advantage since PHP is capable of creating the data necessary for the JS to run before its even handled. You can build all the data you need before it even starts to run.

milesdriven
07-23-2012, 09:31 PM
Thanks very much to everyone. Thanks for steering me in a better direction.

DrDOS
07-23-2012, 10:27 PM
myarray = [];
<?php
for ( $i = 0 ; $i < count($mystyle) ; $i++ )
{
echo "myarray.push('".$mystyle[$i]."');\n";
}

?>
for ( i = 0 ; i < myarray.length ; i++ )
{
thedata[i].value = myarray[i];
}

Keleth
07-23-2012, 10:37 PM
See, again, I REALLY don't see the point in using push. You're doing extra functions on Javascript for NO reason.



var myarray = new Array(<?php for ( $i = 0 ; $i < count($mystyle) ; $i++ ) echo $mystyle[$i].', '; ?>);


Would you write 30 pushes if you were writing javascript directly? Why tell PHP to do it?

DrDOS
07-23-2012, 10:48 PM
See, again, I REALLY don't see the point in using push. You're doing extra functions on Javascript for NO reason.



var myarray = new Array(<?php for ( $i = 0 ; $i < count($mystyle) ; $i++ ) echo $mystyle[$i].', '; ?>);


Would you write 30 pushes if you were writing javascript directly? Why tell PHP to do it?Yes, I would do that because javascript has difficulty with mixed data types when you use other methods, this way mixed data types work fine.

Keleth
07-23-2012, 10:59 PM
That's because an array isn't meant to have mixed datatypes. When you push mixed datatypes, if I'm not mistaken, it actually converts it to an object.

You can use a JSON object that behaves nearly identically to an array for that... you can assign and retrieve elements the same way as an array with a anonymous JSON object, and its meant to hold different datatypes. That's not an issue with Javascript, but rather your use.

DrDOS
07-23-2012, 11:17 PM
That's because an array isn't meant to have mixed datatypes. When you push mixed datatypes, if I'm not mistaken, it actually converts it to an object.
An array is an object by definition, it doesn't have to be converted to one in javascript, it is one. The only real difference between the way JS and php handle arrays is JS doesn't have 'native' associative arrays, but you can construct objects which are associative arrays. They all use the 'key => value pair' concept. You can have mixed data types as the values in the normal JS array, I do it all the time. If you Google javascript array you will get javascript array object.

Keleth
07-23-2012, 11:23 PM
You're right; there is just an Array object. When I said converted to an object, I meant converted to a JSON. However, the Array object was not designed to handle multiple datatypes; it was made to replicate the functionality of arrays as known in other programming languages.

You CAN put multiple datatypes within a single array, because Javascript doesn't have strict datatypes. But because it wasn't made to handle it, you can have issues. You can also put a string into a variable, then overwrite it with an integer, then a bool, then a float, then back to a string, and Javascript doesn't care... but it could screw up your code.

An Array is an object by definition, but so is a Date, and don't tell me somehow its related. An array is an object, but its an object that has methods and properties designed to make it work a certain way. Saying its an object is a non-sequitor. If you want the same datatypes, use an Array. If you want multiple datatypes, use a JSON.

I cannot think of any circumstance where I see a function repeated multiple times as a good thing when there are other acceptable, and better, options. Javascript can already be so slow as it is, instilling the notion that multiple pushes to create an array is acceptable just feels wrong.

milesdriven
07-23-2012, 11:30 PM
I'm still absorbing everything you two are talking about. For now, my thinking is the first think I'm going to try is taking all the functions and onload stuff out of the php loop. I'll convert the onload javascript to functions and add arguments to it.

Instead of this:


<script type="text/javascript">
document.getElementById($variable).innerHTML = '<button>message'</button>
</script>


I'll change it to this and take it out of the loop:


<script type="text/javascript">
function getSomethingDone(jsvariable)
{
document.getElementById(jsvariable).innerHTML = '<button>message'</button>
}
</script>


I'll put this in the loop so it still runs on page load:


for($k = 1; $k <= $days_in_month; $k++)
{
print <<<DEMO
<script type="text/javascript">
getSomethingDone($phpvariable);
</script>
DEMO;
}


I'll see if this works first. If not, I'll try the push. I'm printing this thread for future reference. Lots of good information in it. One thing I have definitely learned in all my time coding is I don't know if it'll work until I try it.

Thanks to both of you for taking an interest in helping.

DrDOS
07-23-2012, 11:45 PM
http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/

A JavaScript array is a collection of variables ("elements") referenced by the array name and the zero-based index of their position: "MyArray[0]" points to the first array element of MyArray.

Each array element is an independent variable, which can be of a different data type than other elements in the same array. Below, we declare a JavaScript array containing four elements: each is of a different data type.
var arlene = new Array("a string", 12, 47.845, true);

This perfectly valid JavaScript array contains as elements a string, an integer, a floating point number, and a boolean (a special JavaScript object).


My last word on the subject. Except maybe to say that the non-strict data typing may from time to time cause trouble anywhere in javascript.

Fou-Lu
07-23-2012, 11:51 PM
Needless to say, neither JS nor PHP have real arrays.
I'm quite sure that JS supports associative "arrays", so that would make it equivalent to PHP's use of hashtables, and hashtables are of course nothing like arrays.

PHP does have an object that is almost arrayish. The FixedArray class has the behaviour closest to the array, but PHP is incapable of handling true arrays due to the properties allowed within the zval struct. The only thing that actually comes close is the char* used for strings.

milesdriven
07-24-2012, 12:19 AM
The solution to this probably has several different parts to it. One of them is to take the element id's, such as:


id = 'May120128AM_list'


...which has several data types in it, and convert it to one piece of data, whether that needs to be a variable or array, clearly understood by both php and javascript.

Then put that one variable or array[] in here:


id ='$variable or array'


...and here:


document.getElementById($variable or array[]);


Combine this strategy with the strategy of taking all javascript out of the loop. Putting only the function calls ( myFunction(argument1, argument2); ) in the loop, with only their arguments (probably arrays) being the next iteration of the loop. My coding style seems to like combining different data types into one id.

DrDOS
07-24-2012, 01:20 AM
This may be slightly off the original topic, but we all need to remember that all PLs are completely artificial languages, there's no such thing as a 'natural' PL. So everything is exactly how someone 'perhaps arbitrarily' defined it to be. And they can use whatever words they want in defining things, but we have to go along or the codes don't run.

milesdriven
07-24-2012, 02:05 AM
Hi DrDOS,

I'm studying the example you showed me of how to push php array data into a javascript array. The example shows javascript above the upper php delimiter and below the lower one.

I assume from that it is permissible to literally nest php code within javascript, like this:



<script type="text/javascript">
javascript code line 1
javascript code line 2

<?php
php code line 1
php code line 2
echo "some javascript code created from the javascript written above and below me";
?>

javascript code line 3
javascript code line 4
</script>


Is it true that both php and javascript will run nested like this as long as both languages are written well?

DrDOS
07-24-2012, 02:28 AM
Hi DrDOS,

I'm studying the example you showed me of how to push php array data into a javascript array. The example shows javascript above the upper php delimiter and below the lower one.

I assume from that it is permissible to literally nest php code within javascript, like this:



<script type="text/javascript">
javascript code line 1
javascript code line 2

<?php
php code line 1
php code line 2
echo "some javascript code created from the javascript written above and below me";
?>

javascript code line 3
javascript code line 4
</script>


Is it true that both php and javascript will run nested like this as long as both languages are written well?

Yes, it will.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum