Jump to content
Larry Ullman's Book Forums
Bennie8

Looping Through An Array One Element At A Time

Recommended Posts

Dear Larry,

 

This new site of yours looks real nice.

 

I've been unable to loop through an "array" one element at a time using the following code, which is based upon "Script 12.3" in Chapter 12 of PHP 6 and MySQL 5:

 

<html>

<body>

 

<?php

 

$i = null;

$test = array();

 

$test[] = 'one';

$test[] = 'two';

$test[] = 'three';

 

if (isset($_POST['submitted'])){

$i++;

}

 

?>

 

<form action="test-array.php" method="post">

<textarea><?php echo $test[0 + $i]; ?></textarea>

<input type="submit" name="submit" value="Next" />

<input type="hidden" name="submitted" value="TRUE" />

</form>

 

</body>

</html>

 

I must have tried every combination of code under the sun to get through the "$test" array, but the page stops at the printed word "two" as I click on the "Next" button, and will go no further.

 

Thank you for any insights as to a solution,

 

Bennie8

Share this post


Link to post
Share on other sites

I think the main problem is that you never use a loop in your code. You increment $i, but only once, if the form is submitted (you also increment an $i that was set to null, which is probably a bad idea). It's not obvious what the intent is from looking at your code (whether you want one form with a bunch of textareas, or multiple forms with one textarea each.

 

For looping over an array, there are several options. I would probably use the foreach construct that loops over each element in the array. Code would be something like...

if (isset($_POST["submitted"])) {
foreach($test AS $testItem) {
   	<form action="test-array.php" method="post">
   	<textarea><?php echo $testItem; ?></textarea>
   	<input type="submit" name="submit" value="Next" /> 
   	<input type="hidden" name="submitted" value="TRUE" />
   	</form>
}
}

or...

if (isset($_POST["submitted"])) {
<form action="test-array.php" method="post">
foreach($test AS $testItem) {
   	<textarea><?php echo $testItem; ?></textarea>
}

<input type="submit" name="submit" value="Next" /> 
	<input type="hidden" name="submitted" value="TRUE" />
	</form>
}

 

Depending upon what your goal for the code is. You could also use a for loop instead of a foreach, with the same effect. It would be something like

for ($i = 0; $i < sizeof($test); $i++) {
// do something with $test[$i]
}

 

Anyway, hope that helps. If you expect code to be looping in some way, then make sure there's a for or do/while in your code somewhere.

 

-matthaus

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear Matthaus,

 

Thank you for your help.

 

I have no idea where to put your code in my script. I tried the following and it didn't do anything:

 

<html>

<body>

 

<?php

 

$test = array();

 

$test[] = 'one';

$test[] = 'two';

$test[] = 'three';

 

?>

 

if (isset($_POST["submitted"])) {

 

<form action="test-array.php" method="post">

foreach($test AS $testItem) {

<textarea><?php echo $testItem; ?></textarea>

}

 

<input type="submit" name="submit" value="Next" />

<input type="hidden" name="submitted" value="TRUE" />

</form>

}

 

 

</body>

</html>

 

Could you please put one of your first two examples into a complete script, in the same manner that my initial example is formatted? If I put either of your first two examples within PHP tags, there are tags within tags.

 

This is all kind of daunting for me, so thank you for your patience.

 

What I am using a form "textarea" box for is in conjunction with my first-ever jQuery "plugin" that I have just put together, after reading up on jQuery. I noticed by accident, while looking up "sticky forms" and "strip_tags" in Larry's book, that a "textarea" box would be perfect for what I have in mind for a web page demonstration of my rudimentary jQuery plugin.

 

Since writing my first post a couple of hours ago, I have found the same problem with going from one "text example" to the next, by clicking on a button, when I use "jQuery" in place of PhP. I get stuck on the first "switch" statement "case."

 

Here is the code:

 

<html>

<head>

 

<script src="http://code.jquery.com/jquery-1.5.js" type="text/javascript" charset="utf-8"></script>

 

<script type="text/javascript">

 

// <![CDATA[

 

var typo;

 

var j = 0;

 

$(document).ready(function() {

 

switch (j) {

case 0 :

typo= '<p>This is a sentence.</p>';

break;

case 1 :

typo= '<p>This is another sentence.</p>';

break;

}

 

j++;

 

$('#button').click(function(){

$('#test').html(typo);

});

 

}); // end of $(document).ready

 

// ]]>

 

</script>

 

</head>

<body>

 

<?php

 

if (isset($_POST['submitted'])) { // start of 'if' conditional

 

echo stripslashes(strip_tags($_POST['data'], "<p> <span> <br>"));

 

} // end of 'if' conditional

 

?>

 

<form action="test-array4.php" method="post">

 

<textarea id="test" name="data" rows="8" cols="45"><?php if (isset($_POST['data'])) echo stripslashes($_POST['data']); ?></textarea>

 

<input type="submit" name="submit" value="Adjust" />

 

<input type="hidden" name="submitted" value="TRUE" />

 

</form>

 

<button id="button">Next Sentence</button>

 

</body>

 

</html>

 

If you open this code up in your browser, and then click the "Next Sentence" button, you will see the first "switch" statement case's text. If you then click on the "Adjust" button, you will see that this same text, that will now appear above the "textarea" box, can be manipulated via changes made to the text down in the "textarea" box, when you click the "Adjust" button again.

 

It is at this point, once the appropriate changes have been made to the "textarea" box text--that my jQuery plugin has interacted with--that the viewer will then be able to move on to another "text example" that will display in the "textarea" box...by clicking the "Next Sentence" button.

 

This is where I have not been able to move through my PhP array or Javascript "switch" statement. There has to be a way to increment that I am overlooking.

 

Thanks again,

 

Bennie8

Share this post


Link to post
Share on other sites

Bennie8, sorry for sounding rude, but looking at the code in both your first and second posts, it seems like you do not understand how to use a loop at all.

 

As Matthaus stated, you should use either a foreach loop or a for loop to go through each element in an array.

 

Although, from what I can gather, you don't need to use PHP at all, unless you're using Ajax for some sort of database manipulation. Basically, you need to first capture all the "test" sentences/words, and store them in an array using jQuery/JavaScript. After that, you'll need to attach an onclick event to the "Next Sentence" button, so that a counter variable (e.g., i) is incremented by one each time the button is clicked, and then use that increment variable (i) to reference the correct element in the array.

 

Anyway, without knowing exactly what you want to do with your code, it's hard to provide any more specific information.

 

If I may be somewhat presumptuous though, what you're attempting to do seems a bit over your head. I mean, knowing how to loop through an array is a fairly basic principle, and if you're having trouble with that, I would recommend taking a step back, and practicing more with Larry's book before attempting what you want to.

 

Lucky for you though, Larry's book is awesome, so you are in good hands if you follow along closely.

  • Upvote 1

Share this post


Link to post
Share on other sites

<html>
<body>

<?php
$test = array();

$test[] = 'one';
$test[] = 'two';
$test[] = 'three';

echo '<form action="test-array.php" method="post">';

if (isset($_POST['submitted'])){ 

foreach ($test AS $testItem) {
   	printf('<textarea>%s</textarea>', $testItem);
}

}

printf('<input type="submit" name="submit" value="Next" />
<input type="hidden" name="submitted" value="TRUE" />
</form>');


?>

</body>
</html>

 

I did make a mistake in my previous post. I was mixing html and php too liberally. The above script should work. But I think hartleysan brought up a couple of good points. First, if you don't know how a loop structure works, then you may need to do a bit more learning or reading before taking on a script that requires loops. Second, depending upon the design of the script, it may be better to have the logic in the javascript instead of php.

 

-matthaus

Share this post


Link to post
Share on other sites

By the way, Bennie8, I didn't mean to come down hard on you or discourage you. It just seemed like you were mixing things up. Taking things one step at a time, and mastering the basics first seems like a more logical progression to me. That's all.

 

If you'd like to explain in more detail exactly what you want to do, I think myself along with everyone else here could help you out.

 

Thanks.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear matthaus and hartleysan,

 

I appreciate your help.

 

I would like to show you two scripts. The first script uses "JavaScript" to loop through a "test" array. The loop works fine until the "Adjust" button is clicked on the script's Form, at which point the array gets reset to zero, defeating the purpose of a planned Demonstration page.

 

<html>

<head>

 

<script type="text/javascript">

 

var j=0;

 

function loop_it(){

 

var test = new Array(3)

 

test[0] = "one";

test[1] = "two";

test[2] = "three";

 

document.getElementById("test").innerHTML=test[j];

document.getElementById("upper-text").innerHTML="";

 

if (j<2) {

 

j = j + 1;

 

} else {

 

j = 0;

 

} // end of 'if (j<2)' incrementer

 

} // end of 'function loop_it(){'

 

</script>

 

</head>

<body>

 

<div id="upper-text">

 

<?php

 

if (isset($_POST['submitted'])) { // start of 'if' conditional

 

echo stripslashes(strip_tags($_POST['data'], "<p> <span> <br>"));

 

} // end of 'if' conditional

 

?>

 

</div><!-- end of 'id="upper-text"' div -->

 

<form action="javascript-array.php" method="post">

 

<textarea id="test" name="data" rows="8" cols="45"><?php if (isset($_POST['data'])) echo stripslashes($_POST['data']); ?></textarea>

 

<input type="submit" name="submit" value="Adjust" value="FALSE" />

 

<input type="hidden" name="submitted" value="TRUE" />

 

</form>

 

<p><a href="#" onclick="loop_it();">Loop it!</a></p>

 

</body>

</html>

 

This second script will increment correctly even after the "Adjust" button has been clicked, thanks to a second "Form" being added to the script. The problem is, the PhP array only advances one time!

 

<html>

<head>

 

<style type="text/css">

 

#upper-text-container {

width: 400px;

height: 200px;

border: 1px solid #000;

}

 

#textarea-container {

width: 400px;

height: 200px;

border: 1px solid #000;

}

 

</style>

 

</head>

<body>

 

<div id="upper-text-container"><!-- start of 'id="upper-text-container"' div -->

 

<?php

 

if (isset($_POST['submitted'])) { // start of 'if' conditional

 

echo stripslashes(strip_tags($_POST['data'], "<p> <span> <br>"));

 

} // end of 'if' conditional

 

?>

 

</div><!-- end of 'id="upper-text-container"' div -->

 

<?php

 

$i = null;

 

$typos[0] = '<p>Example One</p>

<p>This is a sentence. This is another sentence.</p>

<p>This is a sentence. This is another sentence.</p>';

 

$typos[1] = '<p>Example Two</p>

<p>This is a sentence. This is another sentence.</p>

<p>This is a sentence. This is another sentence.</p>';

 

$typos[2] = '<p>Example Three</p>

<p>This is a sentence. This is another sentence.</p>

<p>This is a sentence. This is another sentence.</p>';

 

if (isset($_POST['submitted2'])) { // start of 'if' conditional

 

$i = $i + 1;

 

} // end of 'if' conditional

 

?>

 

<div id="textarea-container"><!-- start of 'id="textarea-container"' div -->

 

<form action="php-array.php" method="post">

 

<fieldset>

 

<legend>Adjust text area</legend>

 

<textarea name="data" rows="8" cols="45"><?php echo (isset($_POST['data'])) ? stripslashes($_POST['data']) : $typos[0 + $i]; ?></textarea>

 

<input type="submit" name="submit" value="Adjust" />

 

<input type="hidden" name="submitted" value="TRUE" />

 

</fieldset>

 

<br /><br />

 

</form>

 

<form action="php-array.php" method="post">

 

<input type="submit" name="submitted2" value="Next" />

 

<input type="hidden" name="submitted2" value="TRUE" />

 

</form>

 

</div><!-- end of 'id="textarea-container"' div -->

 

</body>

</html>

 

It looks like the solution is a different way of writing the incrementing code. I'm going to try some kind of "ajax request" to see if that works, too...as soon as I can read up on it.

 

Regards,

 

Bennie8

Share this post


Link to post
Share on other sites

The first thing I noticed is that you have two "value" values for the first input in the first script. That's not gonna work.

 

Also, I am still a bit confused by what you want to do. Basically, you want to grab a bunch of sentences from a database, throw one of them into a DIV, and if the user presses the "Adjust" button, you want to be able to edit the sentence in the box above the DIV, and if the user presses the "Next Sentence" button, then you want to be able to get the next sentence and display it, right?

 

Please let us know if that's what you want to do or not, and then we can point you in the right direction.

 

Also, I would recommend getting this to work with just PHP first, and once that's working, you can add the Ajax layer at a later time. Using just PHP will force you to reload the page with each button click, but there's nothing wrong with that.

 

Edit: As an afterthought, if what I mentioned above is what you want to do, it'd probably be more user-friendly to display all the editable sentences at once, place "Edit" buttons next to all of them, so that the user can easily see everything and choose what they want to edit.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear HartleySan,

 

You are right. I would like the viewer to see a new sentence when they click the "Next Sentence" button.

 

As the Demonstration page planned will feature a 'game' of sorts where the viewer will advance through 15 or 20 sentence examples, and then click a "Stop" button to see how many seconds it has taken them to complete the series, a single "Next Sentence" button would be the best option.

 

For the heck of it, I tried an "ajax request" to see what would happen, adapting a script I practiced on a couple of years ago while doing an online PhP tutorial...and the exact same thing happened: only one array element would display upon clicking the "Next Sentence" button.

 

I noticed that on page 498 of Larry's book PhP 5 Advanced it says, "As for variable scope, you can reference ajax in this function because in JavaScript, variables declared outside of any function are automatically available within them. This differs from PhP."

 

Maybe that's why the code for looping through a "JavaScript" array won't work with a PhP array.

 

I bought that book over 6 months ago, but haven't read it yet, as I've been side-tracked by jQuery, after winning a jQuery book in an online contest halfway through Chapter 1!

 

Could you direct me to something specific on the web that would address this problem, as incrementing a PhP array is the only PhP information I that need at this time. The rest of my Demonstration page uses other coding.

 

Thanks,

 

Bennie8

 

Here is the "ajax request" code that doesn't work properly:

 

 

 

<html>

<body>

<head>

 

<script type="text/javascript" src="js/forum-array-ajax.js"></script>

 

</head>

 

<form action="#">

 

<label for="txt1">For Next Sentence: </label>

 

<input type="button" value="Click" onclick="showHint(1);" />

 

<p><span id="ajax-request-here">ajax-request will go here</span></p>

 

</form>

 

</body>

</html>

 

 

 

 

/* filename: forum-array-ajax.js > linked to 'forum-array-index.php' */

 

var xmlhttp;

 

function showHint(str) { // start 'function showHint(str)'

 

xmlhttp=GetXmlHttpObject();

 

if(xmlhttp==null) { // start 'if(xmlhttp==null)'

 

alert("Your browser does not support XMLHTTP!");

 

return;

 

} // end 'if(xmlhttp==null)'

 

var url="includes/forum-array-ajax.php";

url=url+"?q="+str;

url=url+"&sid="+Math.random();

xmlhttp.onreadystatechange=stateChanged;

xmlhttp.open("GET",url,true);

xmlhttp.send(null);

 

} // end 'function showHint(str)'

 

function stateChanged() { // start 'function stateChanged()

 

if(xmlhttp.readyState==4) { // start 'if(xmlhttp.readyState==4)'

 

document.getElementById("ajax-request-here").innerHTML=xmlhttp.responseText;

 

} // end 'if(xmlhttp.readyState==4)'

 

} // end 'function stateChanged()'

 

function GetXmlHttpObject() { // start 'function GetXmlHttpObject()'

 

if(window.XMLHttpRequest) { // start 'if(window.XMLHttpRequest)'

 

// code for +IE7, Firefox, Chrome, Opera, Safari

 

return new XMLHttpRequest();

 

} // end 'if(window.XMLHttpRequest)'

 

if(window.ActiveXObject) { // start 'if(window.ActiveXObject)'

 

// code for IE6, IE5

 

return new ActiveXObject("Microsoft.XMLHTTP");

 

} // end 'if(window.ActiveXObject)'

 

return null;

 

} // end 'function GetXmlHttpObject()'

 

 

 

 

<?php

 

/* filename: forum-array-ajax.php > linked to 'forum-array-ajax.js' > linked to 'forum-array-index.php' */

 

// declare the variable even though php doesn't require it

 

$i = 0;

$j = 0;

 

$typos[]="";

 

// fill up array with names

 

$typos[]="element 0";

$typos[]="element 1";

$typos[]="element 2";

 

// get the q parameter from URL

 

$q=$_REQUEST["q"];

 

if($q) { // start of 'if($q)'

 

$i = $q;

 

$i = $i + $j;

 

$hint=$typos[$i];

 

$j = $j + 1;

 

} // end of 'if($q)'

 

$response= $hint;

 

// output the response

 

echo $response;

 

?>

Share this post


Link to post
Share on other sites

Well, the answer is pretty obvious. You're sending 1 to the JS script, and subsequently to the PHP script, every time. That's gonna get you the "1" value (the second element in the array) every time.

 

The simple solution is to make a global i counter variable in the JS script, start it at zero, and increment it by 1 every time the button is clicked. Also, be sure you send that i counter variable, and not 1, to the onclick function. That should solve your problem.

 

One thing you need to be aware of though is the scope of variables. I noticed that you're using all kinds of variables that don't need to be used, and have no effect on anything, like the $j in the PHP script.

 

My point is, while sending the global i counter variable to the onclick function should solve your problem for now, I would encourage you to continue to read Larry's book carefully, so that you can better understand how PHP (and other programming languages for that matter) work. (Kinda that whole "teach a man how to fish" thing.)

 

Anyway, good luck.

 

Edit: Also, your HTML is invalid. When you have the time, take a step back and learn things from the start again. It'll make your life so much easier.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear HartleySan,

 

Sorry about the misplaced "<body>" tag. I was stripping out all of the code that wasn't important to the example and the "<body>" tag ended up above the "head" section instead of below it.

 

I tried that incrementing jazz you suggested at different points in the 'forum-array-ajax.js' file, but the script didn't respond. I guess I'll have to keep searching for the answer.

 

What I've been looking for on the Internet is a way to set a 'condition' inside of one of those loop-types you first mentioned that would stop the loop after each element, and then pick up from there the next time the loop gets activated.

 

Later,

 

Bennie8

 

P.S. I added the "1" to the "showHint(1)" function just to get the script to work, as it was originally this script: [http://www.w3schools.com/php/php_ajax_php.asp]. I was trying to then create a variable indigenous to the 'forum-array-ajax.js' file that would increment independent of the form on the index page.

 

What I usually do in situations like this is throw all kinds of code at the wall and see if anything sticks. Sometimes it does!

Share this post


Link to post
Share on other sites

All right. I'm gonna try and help you out a bit more here. I'm gonna write some code that "shuold" work (although I'm not able to test it now).

 

HTML file

 

<html>

 <head>

   <script type="text/javascript">

     var i = 0; // This is your global counter variable, which you will increment each time.
                // If you decide to put your JS in an external file, make sure the scope of your variables is okay.

     var typos = ['element1','element2','element3']; // I am honestly still confused, as you don't seem to need PHP or Ajax.
                                                     // If you are grabbing the info from a database, then please give
                                                     // us some more info about that. Otherwise, we can't help.
                                                     // I am just declaring typos globally here to show off the "loop" mechanics.
                                                     // Note that you're not really looping though.

     window.onload = function() {

       document.getElementById('txt1').onclick = showHint(i);

     };

     function showHint(i) {

       document.getElementById('data-here').innerHTML = typos[i];

       i++;

     }

   </script>

 </head>

 <body>

   <p>For Next Sentence: <button id="txt1">Click</button></p>

   <div id="data-here"></div>

 </body>

</html>

 

Please note the small amount of code necessary to do what you wanted. Please let me reiterate this point: You do not need to use PHP or Ajax unless a database is involved, in which case, please tell us. Otherwise, very simple JS and HTML (without a form) will suffice.

 

Again, please let us know if there's something you don't understand.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear Hartleysan,

 

Thank you for that script.

 

It gave me an idea for the following script. Unfortunately, the same problem as before arises: namely, the javascript incrementer zeros out whenever the form's "Adjust" button is clicked!

 

<html>

<head>

 

<script type="text/javascript" src="js/forum-array-ajax.js"></script>

 

<script type="text/javascript">

 

var i = 2;

 

function upValue() {

 

document.getElementById("loop_input").value= i;

 

if(i<3){

i = i + 1;

} else {

i= 1;

}

 

}

 

</script>

 

<style type="text/css">

 

#upper-text-container {

width: 525px;

height: 200px;

padding-right: 5px;

padding-left: 5px;

border: 1px solid #000;

}

 

</style>

 

</head>

<body>

 

<div id="upper-text-container"><!-- start of 'id="upper-text-container"' div -->

 

<?php

 

if (isset($_POST['submitted'])) { // start of 'if' conditional

 

echo stripslashes(strip_tags($_POST['data'], "<p> <span> <br>"));

 

} // end of 'if' conditional

 

?>

 

</div><!-- end of 'id="upper-text-container"' div -->

 

<form action="#" method="post">

 

<textarea id="ajax-request-here" name="data" rows="8" cols="65"><?php if (isset($_POST['data'])) echo stripslashes($_POST['data']); ?></textarea>

 

<label for="txt1">For Next Sentence: </label>

 

<input type="button" id="loop_input" name="0" value="1" onclick="showHint(this.value); upValue();" />

 

<input type="submit" name="submit" value="Adjust" />

 

<input type="hidden" name="submitted" value="TRUE" />

 

</form>

 

</body>

</html>

 

Here is a link to the idea that I'm working on:

 

http://whowillbethenextonline.com/forum/forum-array-question1.php,

 

that uses a couple of sections from the jQuery "plugin" that I'm still revising.

 

When you fix a spelling or punctuation error in the "textarea examples" you'll see, and then click the "Adjust" button, the "highlighting" of the incorrect sentence(s) disappears...at which point you can click the "Next" button and start on a new "textarea example." The nature of the game is to see how fast a player can correct 15 or 20 textarea examples.

 

Unfortunately, this fun now ends at Example Two!

 

Bennie8

Share this post


Link to post
Share on other sites

Well, I'll be. I threw the code into IE6 at work, and it doesn't work, just like you said. I apologize (for whatever mistake there is). I'll look into it when I get home. Sorry.

Share this post


Link to post
Share on other sites

When having trouble with javascript, I would highly recommend using a javascript debugger like firebug (http://getfirebug.com/). It lets you step through the javascript as it executes (statement by statement), monitor variables, and has a console where errors will be printed.

 

I can't imagine debugging javascript without it.

 

-matthaus

  • Upvote 1

Share this post


Link to post
Share on other sites

Yeah, I usually use the JS debugger in Chrome. (Chrome rocks!)

 

But I was at work when I wrote that code, and aside from being busy and not having a decent JS resource handy, I am stuck in IE6 in XP at work. (Oh, it sucks!)

 

Anyway, I checked my big ol' JS resource when I got home, and instantly saw the problem with my code.

 

The revised code is below, and I have confirmed that it does work. Note that I added some other tags that are good to have in any HTML document.

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">

 <head>

   <meta http-equiv="content-type" content="text/html; charset=UTF-8">

   <title>Testing</title>

   <script type="text/javascript">

     var i = 0;

     var typos = ['element1','element2','element3'];

     window.onload = function() {

       document.getElementById('txt1').onclick = showHint;

     };

     function showHint() {

       document.getElementById('data-here').innerHTML = typos[i];

       i++;

     }

   </script>

 </head>

 <body>

   <p>For Next Sentence: <button id="txt1">Click</button></p>

   <div id="data-here"></div>

 </body>

</html>

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear Matthaus and Hartleysan,

 

I'll be busy for a while studying your script ideas and checking out your suggested links!

 

Thank you for taking time from your busy schedules to help me figure out my array dilemma.

 

I gutted an old php-ajax script that I worked on years ago, that I got from here,

 

http://www.w3schools.com/php/php_ajax_poll.asp,

 

and came up with an incrementing system that works! Unfortunately, the "newline" formatting was lost in the process, I think it's called, in the textarea. Now, the "<p>" and "<span><br />" tags are in one long string, as opposed to before, when they were one under the other--making them difficult for the viewer to discern.

 

Here is a link to the new page:

 

http://whowillbethenextonline.com/forum/forum-array-question2.php .

 

I tried the PhP 'nl2br()' function after adding 'newline' characters '\n' to my array strings, but that didn't help.

 

Bennie8

 

P.S. Here are the main page (forum-question-solution.php), the JavaScript file (forum-question-solution.js), and the PhP file (forum-question-solution-increment.php) if you are interested. [You might see some extra coding here and there that I plan on using later.]

 

forum-question-solution.php

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<meta name="generator" content="NoteTab Light" />

<title>PhP 6 and MySQL 5 Forum Array Question</title>

 

<!-- based upon Script # 12.3 in PHP 6 and MySQL 5 -->

 

<script src="http://code.jquery.com/jquery-1.5.js" type="text/javascript" charset="utf-8"></script>

 

<!-- see http://examplet.buss.hk/jquery/selector.regex.php for explanation of the 'jQuery' regex() plugin - This regex() plugin is needed for the 'php-array-demo.js' file to work -->

 

<script type="text/javascript" src="js/jquery.regex.js"></script>

 

<script type="text/javascript" src="js/php-array-demo.js"></script>

 

<script type="text/javascript" src="js/forum-question-solution.js"></script>

 

<style type="text/css">

 

body {

color: #29405B;

background-color: #FAFBFC;

}

 

h5 {

margin: 0px 0px 5px 0px;

}

 

#upper-text-container {

width: 525px;

height: 200px;

padding-right: 5px;

padding-left: 5px;

border: 1px solid #000;

}

 

#textarea-container {

width: 535px;

height: 200px;

border: 1px solid #000;

}

 

textarea {

overflow: hidden;

}

 

</style>

 

</head>

 

<body>

 

<h5>It's TypoFinder! For Web Page Coders!</h5>

 

<div id="upper-text-container"><!-- start of 'id="upper-text-container"' div -->

<?php

 

if (isset($_POST['submitted'])) { // start of 'if' conditional

 

echo stripslashes(strip_tags($_POST['data'], "<p> <span> <br>"));

 

} // end of 'if' conditional

 

?>

 

</div><!-- end of 'id="upper-text-container"' div -->

 

<div id="textarea-container"><!-- start of 'id="textarea-container"' div -->

 

<form action="#" method="post">

 

<fieldset>

 

<legend>Adjust text area</legend>

 

<textarea id="poll-2" name="data" rows="8" cols="65"><?php if (isset($_POST['data'])) echo stripslashes($_POST['data']); ?></textarea>

 

<input type="submit" name="submit" value="Adjust" />

 

<input type="hidden" name="submitted" value="TRUE" />

 

</fieldset>

 

</form>

 

<div><br /><br /></div>

 

<form action="#" method="post">

 

<fieldset>

 

<legend>Advance to Next Example</legend>

 

<label for="vote-yes">Click radio button for next example</label>

 

<input type="radio" name="vote" id="vote-yes" value="0" onclick="getVote(this.value); this.form.reset();" />

 

</fieldset>

 

</form>

 

</div><!-- end of 'id="textarea-container"' div -->

 

</body>

 

</html>

 

forum-question-solution.js

 

/* External 'forum-question-solution.js' file for 'forum-question-solution.php,' 'forum-question-solution-increment.php,' and 'forum-question-solution-value.txt.' */

 

var xmlhttp;

 

function getVote(int) { // start 'getVote(int)' function

 

xmlhttp=GetXmlHttpObject();

 

if (xmlhttp==null) {

 

alert ("Your browser does not support HTTP Requests");

 

return;

 

}

 

if (int==0) {

 

var url="includes/forum-question-solution-increment.php";

 

}

 

url=url+"?vote="+int;

url=url+"&sid="+Math.random();

xmlhttp.onreadystatechange=stateChanged;

xmlhttp.open("GET",url,true);

xmlhttp.send(null);

 

if (int==0) {

 

document.getElementById("poll-2").style.backgroundColor="#F0FFFF";

 

document.getElementById("upper-text-container").innerHTML="";

 

}

 

} // end 'getVote(int)' function

 

function stateChanged() { // start 'stateChanged()' function

 

if (xmlhttp.readyState==4) {

 

document.getElementById("poll-2").innerHTML=xmlhttp.responseText;

 

}

 

} // end 'stateChanged()' function

 

function GetXmlHttpObject() { // start 'GetXmlHttpObject()' function

 

var objXMLHttp=null;

 

if (window.XMLHttpRequest) {

 

objXMLHttp=new XMLHttpRequest();

 

} else if (window.ActiveXObject) {

 

objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");

 

}

 

return objXMLHttp;

 

} // end 'GetXmlHttpObject()' function

 

forum-question-solution-increment.php

 

<?php

 

/* External 'forum-question-solution-increment.php' file for 'forum-question-solution.php.' Connected to 'forum-question-solution-value.txt' */

 

$vote = $_REQUEST['vote'];

 

// get content of textfile

 

$filename = "forum-question-solution-value.txt";

 

$content = file($filename);

 

// put content in array

 

$array = explode("||",$content[0]);

$yes = $array[0];

$no = $array[1];

 

if ($vote == 0) {

 

$yes = $yes + 1;

 

}

 

if ($vote == 1) {

 

$no = $no + 1;

 

}

 

// added $number variable for counter below

 

$number = $yes + $no;

 

if ($yes==4){

$yes = 1;

}

 

// insert votes to txt file

 

$insertvote = $yes . "||" . $no;

 

$fp = fopen($filename, "w");

 

/* I added the following 'flock()' function after reading page 311 of Larry Ullman's 'PHP Third Edition,' and then a 'w3schools' page (http://www.w3schools.com/php/func_filesystem_flock.asp) that shows how to use an 'if' conditional to insert the 'flock()' function into a script. */

 

if(flock($fp,LOCK_EX)) {

 

fputs($fp,$insertvote);

 

// release lock

 

flock($fp,LOCK_UN);

 

// echo "flock() works";

 

} else {

 

fputs($fp,$insertvote);

 

// echo "flock() doesn't work";

 

}

 

fclose($fp);

 

$typos[1] = '<p>Example One.</p>

<p>This is a sentence.This is another sentence.</p>

<p>This is a sentence. This is another sentence.</p>

<span>This is a sentence.This is another sentence.</span>

<span>This is a sentence. This is another sentence.</span>';

 

$typos[2] = '<p>Example Two</p>

<p><script type="text/javascript">

alert(\'<p>Can you find : the punctuation error?</p>\');

</script></p>';

 

$typos[3] = '<p>Example Three</p>

<p>Finally!This is a third sentence.</p>

<p>Finally! This is a third sentence.</p>';

 

if($yes<4) {

echo $typos[$yes];

}

 

?>

Share this post


Link to post
Share on other sites

Bennie8, please do me a favor and stop posting long blocks of code. It's not helping any. For starters, I'm not going to write your code for you. We're all here to help and give you pointers, not to do everything for you.

 

With that said, I have looked at your code, and while your effort is admirable, and I'm happy that you're trying so hard, I can't help but feel like you're just randomly throwing pieces of code together you have gotten from other places, and now you can't figure out why the code is not working. Really, I cannot stress this enough: You really need to take a step (or two) back, and rethink things.

 

For starters, I still don't completely understand what you're trying to accomplish. I mean, it seems like your trying to display different parts of an HTML page, upon which you want to edit the content for any spelling/grammar mistakes, and then reinsert the corrected sentences somewhere. That's about the extent of what I can imagine.

 

So from here on out, instead of posting huge blocks of code, let's take this one step at a time, taking baby steps along the way, and make sure you understand what you're doing while you're doing it and slowing building your site, okay? Fair enough?

 

Now, before we go any further, could you please explain to me in detail exactly what you want to make? I need all the details about what you want, where your data is coming from (e.g., a text file, a database), who your audience is going to be, what functionality you think the site should have, etc. After everyone that's here trying to help you is on the same page, we can proceed, okay? Cool.

 

And again, please don't rush things. Perhaps you have a deadline you have to meet, but rushing's not going to help, and it makes everyone on this board less likely to help you.

 

We anxiously await your reply. Thank you.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear Hartleysan,

 

The code is already written. It's all there in the detail that you've asked for over and over.

 

There is no database; there is just the text in the PhP array in the script.

 

I originally wrote here to find out if anyone knew how to cycle through a PhP array one value at a time by clicking on a button.

 

But, no one seems to know how to do that. And, I can't find out that information anywhere on the web, either.

 

Luckily, I figured out a way to cycle through a PhP array, using an "ajax request"--but, at the cost of losing the "formatting" in the textarea that I had had before.

 

It seems that what writes correctly to a "<div>" or "<p>" on the main page through an "ajax request" will display differently when written into a form’s "textarea."

 

I thought that someone might know what could be added to a string, such as adding a "newline" character ('\n'), to bring back this formatting to the text in the textarea; but it seems that no one knows how to do that, either. Nor, can I find that information anywhere on the web. Apparently, this combination of code that works perfectly for my Demonstration page is not commonly used.

 

When I find out more about how to cycle through a PhP array one click at a time, or how to format text in a “textarea,” I'll let it be known on this thread, so that others can learn about it, too. If the answers are in one of the chapter in any of the three Larry Ullman PhP books that I have sitting here, please tell me the chapter. I haven’t found them.

 

As far as my placing the entire script in my message: it's for the benefit of someone who is interested in learning the same type of coding procedures that I am. That's why someone would click on a link with the Subject line titled "Looping Through An Array One Element At A Time." My explanations aren't directed towards crusty veterans such as yourself, who already know this stuff like the back of your hand. I'm relaying information about what I've found out through trial-and-error on this topic. You've been telling me about “JavaScript loops,” that I explained near the beginning of this thread don't work in this instance.

 

Most answers to people's questions on just about any website you can think of are so cryptically written that it's very hard to understand the answers. And, the coding solutions are usually presented in little snippets that a beginner at coding would not be completely sure how to adapt to their scripts.

 

That might explain why there are thousands of questions relating to the same topics year after year all over the Internet: because it's hard to find clear, complete answers written at the level of the beginners who asked them.

 

That might also explain why there are so many computer books written on the same subject. Either there are a slew of errors of one kind or another in a book that are so confusing to a beginner that they give up and never complete the book; or, a book touted for "absolute beginners" takes off like a rocket by the second chapter, and the beginner is left behind on the launching pad.

 

Just read the comments on places like Amazon.com about computer books and you will see what I mean.

 

When I was looking for a book on PhP, I started reading one glowing comment after another about this "Larry Ullman" guy who really cares about getting it right in his books, and who makes it a point to go into the kind of detail in his books that other authors choose not to. “He even answers people's E-mails,” the comments boast, and he prominently lists any errors in his books on his website, that his readers send to him.

 

That's why I came to this Forum looking for an answer to a PhP question. Where better to go?

 

And one thing I'll say about the "text editor" on this Forum: it's like going on a ride at Disneyland! It's got all the bells and whistles that you could ever ask for.

 

Bennie8

Share this post


Link to post
Share on other sites

Dear Hartleysan,

 

The code is already written. It's all there in the detail that you've asked for over and over.

 

Just to be clear, HartleySan really is trying to help and I, for one, appreciate that.

 

I originally wrote here to find out if anyone knew how to cycle through a PhP array one value at a time by clicking on a button.

 

But, no one seems to know how to do that. And, I can't find out that information anywhere on the web, either.

 

Simple: use PHP to write the PHP array out as a JavaScript array. Create a JavaScript variable that's a counter. For each click of the button, increment the counter, which allows you to get the next item in the array.

 

Or, the more complex method would be to use the JavaScript counter, but send it to the PHP script, which uses the counter to return the current element. This is more complicated and would only be necessary if the array was very large.

 

If the answers are in one of the chapter in any of the three Larry Ullman PhP books that I have sitting here, please tell me the chapter. I haven’t found them.

 

Thanks for the purchases of my books! I haven't written about this specific of a thing in any of my current books.

 

Most answers to people's questions on just about any website you can think of are so cryptically written that it's very hard to understand the answers. And, the coding solutions are usually presented in little snippets that a beginner at coding would not be completely sure how to adapt to their scripts.

 

I don't think I agree with you here. I tend to provide cryptic answers because I'm extremely busy. If I took the time to provide exhaustive answers to everyone's questions, I'd never be able to do my own paying work. To me, the purpose of a reply is to get the original poster to understand the answer, not to provide an answer that anyone can understand. If the answer is too cryptic for the original poster, it can be expanded. If other people come along and don't understand the answer, or how it all works together, they can ask a question and that question can be answered. But I very much feel that being cryptic is the same as being efficient.

 

I'm also hesitant to complain about free help, but maybe that's just me.

 

That might also explain why there are so many computer books written on the same subject. Either there are a slew of errors of one kind or another in a book that are so confusing to a beginner that they give up and never complete the book; or, a book touted for "absolute beginners" takes off like a rocket by the second chapter, and the beginner is left behind on the launching pad.

 

Just read the comments on places like Amazon.com about computer books and you will see what I mean.

 

Again, I'm going to have to disagree with your theory here. I don't think it's reasonable to suggest that the poor quality of books is why there are so many on a subject. That's just illogical. As a writer, I know for a fact that there are lots of books on subject X (instead of Y) because the publisher thinks there's a market for it. I don't disagree that there are plenty of books out there that aren't great, but every publisher and every writer is trying to create a good book that the reader likes.

 

When I was looking for a book on PhP, I started reading one glowing comment after another about this "Larry Ullman" guy who really cares about getting it right in his books, and who makes it a point to go into the kind of detail in his books that other authors choose not to. “He even answers people's E-mails,” the comments boast, and he prominently lists any errors in his books on his website, that his readers send to him.

 

Now I'm intrigued about this "Larry Ullman" guy! Thanks for the nice words. I very much do care about getting it right, although I would like to think that all writers do. I've always felt, though, that my books work in part because I don't go into a lot of detail, instead focusing on what really matters (whereas I feel like many technical books have too much of the writer trying to show how much they know). I suspect it's fair to say that I support my books more than most writers. In part that's because this is my job, in part because I learn a lot by supporting the books (i.e., it makes me a better writer), and in part because there is a marketing aspect there.

 

That's why I came to this Forum looking for an answer to a PhP question. Where better to go?

 

Absolutely what the forum is for!

 

And one thing I'll say about the "text editor" on this Forum: it's like going on a ride at Disneyland! It's got all the bells and whistles that you could ever ask for.

 

 

Indeed. And thanks for being judicious in not using them all! One of the things I meant to do was cut down on the bells and whistles, but I haven't gotten to it yet.

Share this post


Link to post
Share on other sites

Bennie8,

 

The reason you can't find a way to traverse an array by mouse click with PHP coding is because there isn't one. PHP runs on the server only, and knows nothing about what is happening on the client (i.e., browser) side. A PHP script executes in its entirety, and sends the final results to the browser. Javascript, on the other hand, executes on the client, and that's why your AJAX solution is the correct approach. And AJAX utilizes Javascript (AJAX = Asynchronous Javascript And XML), so the suggestion by HartleySan was spot on.

 

As for your issue with the <textarea>, PHP doesn't automatically convert newlines to <br>, but there is a function called nl2br() that is commonly used to make that conversion for displaying as regular HTML text, and you must be using it. If you want to re-display text from a <textarea> into a <textarea> field, don't use that function, just display the unconverted text. You could also do a string replace of converted text with str_replace('<br>', '\n', $yourTextareaString). When echoing the replacement string, you'll want to enclose it with double-quotes rather than single-quotes since single-quoted strings are printed exactly as-is and you'll just see \n instead of a newline.

 

When entering blocks of code, please consider using the code tags (in the editor toolbar it's the <> button), which makes the code much easier to read and preserves indention. I personally don't have a problem with lengthy blocks, but I probably won't read all of it.

 

Hang in there. You'll make a lot of mistakes in the beginning, but you'll learn more from those mistakes than by doing it right the first time.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear Larry,

 

Thank you for clearing the air!

 

Bennie8

 

Dear Paul,

 

Welcome aboard!

 

JavaScript, when used as part of an "Ajax request" works just fine in getting information to and from PhP, where a number can be stored in a text file as part of an ad hoc array incrementer. But, when JavaScript is used for the incrementing on the main page, there is a downside: namely, the JavaScript counter "zeros out" whenever a "Submit" button on the page's "form" is clicked, thus preventing the incrementing from working in conjunction with the adjusting of text, through the use of the form's "Adjust" button (a "Submit" button), to display items seamlessly from the JavaScript array.

 

This page shows what I mean: http://whowillbethenextonline.com/forum/javascript-array.php

 

If you click the "Loop it!" link that you'll see on the page twice, displaying the word "two," and then click the form's "Adjust" button, and then click the "Loop it" button again, you will see that the array has returned to the first JavaScript array element's value: "one."

 

So, using that method won't work for the Demonstration page that I had in mind for my jQuery plugin.

 

Naturally, I was surprised when the "Ajax" method worked in looping through a PhP array! But, I then noticed that the formatting gets lost when a PhP array’s "ajax request" text is what is being displayed in the textarea. I tried the 'nl2br()' and 'str_replace()' functions that you mentioned, but I couldn't get them to affect the text in the textarea. Those functions will work on text displayed on the main page, that sits inside of a "<div>" tag, for instance, but then the text inside that "<div>" tag can't be worked-with as the "textarea" text can, as far as my Demonstration page is concerned.

 

On the other hand, if a call is made directly to a PhP array that's on the main page, from a form that's on the main page, the text displayed in the textarea looks exactly as it should, as in this example:

 

http://whowillbethenextonline.com/forum/forum-array-question.php

 

But, the "incrementing" code that I've been using doesn't seem to work on this page to cycle throught the PhP array. It must have something to do with the PhP being on the server, as you said, or, maybe there's a way to write the incrementing code that will work that I haven't tried yet.

 

So, either I can find a way to increment a PhP array that is called from a form on the main page, displaying easy-to-read code...or I'll have to scrap my Demostration page idea!

 

That last page I linked to can still be used to "copy-and-paste" code into, to check for various grammatical and punctuation problems in web page coding, when I connect my finished jQuery plugin to it.

 

Well, back to the drawing board.

 

Thank you all,

 

Bennie8

Share this post


Link to post
Share on other sites

Bennie, you're killing me, man. First off, I'm no veteran. I have asked enough of my own questions on this forum to make Larry's head spin. I apologize if I came off as insulting, but frankly, you're not listening.

 

First off, Larry's book talks in plenty of detail about how to cycle through an array. Matthaus also clearly outlined it in his first reply to your question. Again, I can only reiterate this so many times: You do NOT need PHP for what you are doing. If you are simply reading sentences from an array in the code itself, JavaScript is perfectly fine. Also, the code I gave you is a perfect starting point.

 

However, your code is way, waaaay over the top and out of control. If you want to help people like yourself that want to do these sorts of things, please listen to the people that know what they're talking about and try to learn a thing or too. It's fine to ask questions if you don't know the answer, but please don't come in here with that attitude.

 

I really do understand your frustration though with scouring the Web, and never being able to find a straight answer from the "pros". I still experience that all the time. The fact of the matter though, is that many people who are good at coding are horrible at explaining things. That's why Larry is such a savior.

 

Anyway, back to your code. The code I gave you practically does everything you want. With a few extra lines of some code and some CSS styles, you will have exactly what you're looking for. If there is some part of my code you don't understand, please ask. But you have to recognize the value in having a script that is one JS function, one event assignment and two lines of code in the body to get the job done, as opposed to the three scripts you have interacting for no reason whatsoever. You also have so many unnecessary variable assignments that I don't know where to begin.

 

Look, I'm trying to be nice and helpful, but you gotta listen a bit more, or I'm gonna stop trying. And while I'm the main one replying to your threads, I seriously doubt that anyone else on this forum could read your posts and clearly understand what you're trying to do.

 

So I'll ask one more time: What do you want to do? You want to take sentences defined in an array in the code, place them in a text area one at a time (tags included), edit them, and then hit the next button to load the next sentence and store the revised one back into the array, right? If that's the case, please say so, and I'll revise my code above to help you out.

  • Upvote 1

Share this post


Link to post
Share on other sites

Dear Hartleysan,

 

Ok. Now I think I know where the "failure to communicate" emanated from. I think I may have given you the impression that I wanted a viewer to be able to "save" the editing that they had done to "example text" in the textarea box to a database or file, at which point they could then move on to the next text example. Is that close?

 

The purpose of the "editing" of the textarea box text is only to make the "highlighting" disappear, so that the viewer can then move on to the next text example. "Saving" the edited text to a database or file would be a whole different ball of wax, that's for sure.

 

Anyway, I came back from a walk a little while ago and had an epiphany.

 

After reading Paul’s suggestions about the PhP ‘nl2br()’ and ‘str_replace()’ functions earlier, I went to my ‘forum-question-solution.js’ file (now ‘forum-question-solution3.js’) and found that I was successfully able to alter the “ajax requested” text heading for the main page’s textarea box by adding JavaScript methods like these to the “xmlhttp.responseText” thinger:

 

document.getElementById("poll-2").innerHTML= xmlhttp.responseText.toUpperCase();

/* above works */

 

document.getElementById("poll-2").innerHTML= xmlhttp.responseText.replace('\n','<br>');

/* this works, but does not affect formatting */

 

but, I was still unable to change the placement of the “<p>,” “<span>” or “<br />” tags when they arrived at the textarea box.

 

But, after taking a walk, and before you know it, I had a solution!

 

And, here is a web page with the new script:

 

[i have taken down the web page that was linked-to here. It doesn't work right.]

 

Thank you for sharing your comments,

 

Bennie8

  • Upvote 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×