eburlea 23 Junior Poster

After hours of googling, I have found the answer on http://www.satya-weblog.com/2007/05/php-and-javascript-cookie.html

in View

<script type="text/javascript">
    var timezone = jstz.determine();
    document.cookie = 'user_timezone=' + timezone.name();
</script>

in Controller

$request = new Zend_Controller_Request_Http();
$user_timezone = $request->getCookie('user_timezone');
if(isset($user_timezone)){
    echo 'User Timezone is ' . $user_timezone . '.';
} else {
    echo 'The cookie has not been set yet.';
}
eburlea 23 Junior Poster

Hello!

I have the same problem and I have solved just half of it.

I have downloaded a javascript plugin 'jsTimezoneDetect' (https://bitbucket.org/pellepim/jstimezonedetect/downloads) and linked it in the header. Then I wrote the following code that is returning the timezone:

<script type="text/javascript">
    var timezone = jstz.determine();
    var user_timezone = timezone.name();
</script>

How can I pass the value of the variable user_timezone to PHP in the same page? I do not want to use method $_GET. I have tried with Ajax, but without success.

I am using Zend Framework and I need to pass the value from View to Controller.

Thanks.

eburlea 23 Junior Poster

You can use jQuery User Interface Dialog: http://jqueryui.com/dialog/#modal-form

eburlea 23 Junior Poster

I use XAMPP on Windows OS. It includes apache server, mysql database, php, and other. If you want to use it, first you need to download and install Microsoft Visual C++ 2008 SP1 Redistributable Package (x86) from http://www.microsoft.com/en-us/download/details.aspx?id=5582 , then download and install XAMPP from http://www.apachefriends.org/en/xampp-windows.html#641 . And you are ready to go!

eburlea 23 Junior Poster

I have found out the problem.

The mistake was that I added the code for database configuration in 'application.ini' file in the wrong place, it needs to be under [production].

BEFORE:

    [production]
    phpSettings.display_startup_errors = 0
    phpSettings.display_errors = 0
    includePaths.library = APPLICATION_PATH "/../library"
    bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
    bootstrap.class = "Bootstrap"
    appnamespace = "Application"
    resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
    resources.frontController.params.displayExceptions = 0

    [staging : production]

    [testing : production]
    phpSettings.display_startup_errors = 1
    phpSettings.display_errors = 1

    [development : production]
    phpSettings.display_startup_errors = 1
    phpSettings.display_errors = 1
    resources.frontController.params.displayExceptions = 1

    resources.db.adapter = PDO_MYSQL
    resources.db.params.host = localhost
    resources.db.params.username = mydbusername
    resources.db.params.password = mydbpassword
    resources.db.params.dbname = mydbname
    resources.db.params.charset  = UTF8
    resources.db.isDefaultTableAdapter = true

AFTER:

[production]
    phpSettings.display_startup_errors = 0
    phpSettings.display_errors = 0
    includePaths.library = APPLICATION_PATH "/../library"
    bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
    bootstrap.class = "Bootstrap"
    appnamespace = "Application"
    resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
    resources.frontController.params.displayExceptions = 0

    resources.db.adapter = PDO_MYSQL
    resources.db.params.host = localhost
    resources.db.params.username = mydbusername
    resources.db.params.password = mydbpassword
    resources.db.params.dbname = mydbname
    resources.db.params.charset  = UTF8
    resources.db.isDefaultTableAdapter = true

    [staging : production]

    [testing : production]
    phpSettings.display_startup_errors = 1
    phpSettings.display_errors = 1

    [development : production]
    phpSettings.display_startup_errors = 1
    phpSettings.display_errors = 1
    resources.frontController.params.displayExceptions = 1
eburlea 23 Junior Poster
eburlea 23 Junior Poster

PHP Version 5.4.6

I have just created a new project, added Zend library, added the code

resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = myusername
resources.db.params.password = mypassword
resources.db.params.dbname = mydatabase
resources.db.params.charset  = UTF8
resources.db.isDefaultTableAdapter = true

into 'application.ini', created a subfolder 'DbTable' in 'models' and there created a file 'Mysqltablename.php' with the code

<?php

class Application_Model_DbTable_Mysqltablename extends Zend_Db_Table_Abstract
{
    protected $_name = 'mysqltablename';
}   

and the file 'IndexController.php' has the code

<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
        $myModel = new Application_Model_DbTable_Mysqltablename();
    }

The file 'ErrorController.php' was automatically created and has the following code

<?php

class ErrorController extends Zend_Controller_Action
{

    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        if (!$errors || !$errors instanceof ArrayObject) {
            $this->view->message = 'You have reached the error page';
            return;
        }

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $priority = Zend_Log::CRIT;
                $this->view->message = 'Application error';
                break;
        }

        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->log($this->view->message, $priority, $errors->exception);
            $log->log('Request Parameters', $priority, $errors->request->getParams());
        }

        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }

        $this->view->request   = $errors->request;
    }

    public function getLog()
    {
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasResource('Log')) {
            return false;
        }
        $log = $bootstrap->getResource('Log');
        return $log;
    }


}
eburlea 23 Junior Poster

Hello. I have created a new Zend project, created a new model class to get some data from the database. If the environment is set to 'development', the data from the database are displayed properly in the browser, but after setting the environment to 'production', the following error appears:

An error occurred

Application error

Can anybody please help to find out the problem?

eburlea 23 Junior Poster

Thank you, LastMitch. It is a CSS issue and has been solved accordingly.

eburlea 23 Junior Poster

Hi all. I need to fix a bug in a code, it is not displaying properly (it appears in the upper-left corner and when I try to click on it, the page reloads). I cannot figure it out myself. Please help.

<div class="btn_center" style="padding: 0 0 10px;">
    <fieldset>
        <div class="edit_entry btn_sm_sp" onclick="$j('#table-list').editGridRow( 'new', {'width':500, 'url': '<?=$this->baseUrl."/admin/product/category-create"?>'} );">
            <span><span><span><?php echo $this->translate->_('add_product');?></span></span></span>
        </div>
    </fieldset>
</div>
eburlea 23 Junior Poster

I have found another solution using a class.

class CreateFunction
{
    function __construct()
    {
        $function_name = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

        for($i=0,$n=count($function_name); $i<$n; $i++)
        {
            $this->$function_name[$i] = create_function('', 'echo "The name of the function is ' . $function_name[$i] . '.<br />";');
        }
    }

    public function __call($method, $args)
    {
        if(property_exists($this, $method)) {
            if(is_callable($this->$method)) {
                return call_user_func_array($this->$method, $args);
            }
        }
    }
}

$object = new CreateFunction();
$function_names = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

for($i=0,$n=count($function_names); $i<$n; $i++)
{
    $object->$function_names[$i]();
}
cereal commented: thanks for sharing! +11
eburlea 23 Junior Poster

Thank you so much all for helping me and providing many variants. The last example is exactly what I am looking for.

eburlea 23 Junior Poster

@minitauros

Thank you for your answers anyway, even if they cannot be implemented in this particular situation, I will keep them in mind and use when the case will come.

I am still googling the web for the answer, have tried many codes, but no luck.

eburlea 23 Junior Poster

No, this is not what I am looking for.

Let me explain in other words...

I have a database with 20 categories. I need to be created 20 functions which names should coincide with the category names. Also I need to use each function name inside the corresponding function as parameter. This code need to be written one time and when I add a new category into the database, I will have now 21 functions, without changing the code.

eburlea 23 Junior Poster

I could get the result with create_function() in this way:

$myarray = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

$func = create_function('$functionname', 'echo "The name of the function is $functionname.";');

for($i=0, $n=count($myarray); $i<$n; $i++)
{
    $func($myarray[$i]);
    echo '<br />';
}

Actually I need to use these dynamically created functions in a multithreading script which extracts from the database a certain number of categories that need to correspond to the name of a function. I know how to run all functions simultaneously, but I do not know how to get the category name as name of the function and as parameter in the same time. And I am not sure if I can use here '$func($myarray[$i])' as parameter to an object instead of a simple function name as below:

function first ()
{
    for($i=1; $i<=10; $i++)
    {
        mkdir('first ' . $i);
        sleep(5);
    }
}

function second()
{
    for($i=1; $i<=10; $i++)
    {
        mkdir('second ' . $i);
        sleep(5);
    }
}

function third()
{
    for($i=1; $i<=10; $i++)
    {
        mkdir('third ' . $i);
        sleep(5);
    }
}

// create 3 thread objects
$t1 = new Application_Plugin_Thread( 'first' );
$t2 = new Application_Plugin_Thread( 'second' );
$t3 = new Application_Plugin_Thread( 'third' );

// start them simultaneously
$t1->start( 1, 't1' );
$t2->start( 1, 't2' );
$t3->start( 1, 't3' );

// keep the program running until the threads finish
while( $t1->isAlive() && $t2->isAlive()  && $t3->isAlive() ) {

}
eburlea 23 Junior Poster

Hello. I am curious if it is possible to create functions dynamically in such a way, that (1) the names of the functions to be retrieved from an array and (2) these names could be used also inside the functions. I have a code that is solving the first problem, any ideas how to solve problem 2? Thanks.

<?php

$myarray = ['myvalueone','myvaluetwo','myvaluethree','myvaluefour','myvaluefive'];

for($i=0, $n=count($myarray); $i<$n; $i++)
{
    $functionname = $myarray[$i];
    $$functionname = function(){
        echo 'The name of the function is ... .';
    };
}

$myvaluetwo(); // The result need to be: The name of the function is myvaluetwo.

?>
eburlea 23 Junior Poster

Thank you for the answer.

Your first line provides exactly what I was looking for:

$page_content = file_get_contents($url);

Now all characters are as I need them to be.

Thanks again!

eburlea 23 Junior Poster

Hi. I use a fuction to retrieve some information from a remote site:

$dom = new DOMDocument;
@$dom->loadHTMLFile($url);
$page_content = $dom->saveHTML();

When I echo the content, some characters appear like 'á'. I have tried many things from the internet, but nothing helped.

Is there a solution?

eburlea 23 Junior Poster

I have a Motorola tablet, sometimes when I fill out a form, when I select a text-field by touching the screen, actually it selects an upper text-filed. Do you know what could be the problem?

eburlea 23 Junior Poster

The code:

alert(navigator.userAgent);

returns 'Mozilla/5.0 (X11;Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24'.

What substring should I take from this string to show that the device is Android?

eburlea 23 Junior Poster

I need to Specify that when the page is accessed from its default browser, it is not detected, but when accessing the page from Chrome, it is working.

Actually I need to implement a code into a site to re-direct users if they are connected from mobile devices. When we test the script, with most of the phones it is ok, and with Samsung S3 it is ok if accessing the page with Chrome.

eburlea 23 Junior Poster

Hi all.

I have got a code that detects the most mobile devices except Samsung Galaxy S3 (there may be other exceptions as well). Please advice how is it possible to detect the device Samsung Galaxy S3.

My code is:

<script type="text/javascript">            
    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if(isMobile.any()){
        alert("The device is mobile!");
    }
 </script>

Thank you.

eburlea 23 Junior Poster

You are right, diafol. The change event applies only to the first select. So, I thought to use a function for creating other elements to which the change events can be applied. The following code is working:

<select id="1" name="1">
    <option value="Value 1">Text 1</option>
    <option value="Value 2">Text 2</option>
    <option value="Value 3">Text 3</option>
    <option value="Value 4">Text 4</option>
    <option value="Value 5">Text 5</option>
</select>

<div id="newselect">&nbsp;</div>

<script type="text/javascript">
$(document).ready(function(){
    var totalElements = 1;

    function createElement(elementId) {        
        var s = $('<select id="' + elementId + '" name="' + elementId + '" />');
        $("<option />", {'value':'Value 1', 'text':'Text 1'}).appendTo(s);
        $("<option />", {'value':'Value 2', 'text':'Text 2'}).appendTo(s);
        $("<option />", {'value':'Value 3', 'text':'Text 3'}).appendTo(s);
        $("<option />", {'value':'Value 4', 'text':'Text 4'}).appendTo(s);
        $("<option />", {'value':'Value 5', 'text':'Text 5'}).appendTo(s);
        s.appendTo("#newselect");

        $('#' + elementId).change(function(){
            for(var n=elementId+1;n<=totalElements;n++) {
                $('#' + n).remove();
            }
            createElement(elementId + 1);
            totalElements = elementId + 1;
       });
    };

    $('#1').change(function(){
        for(var n=2; n<=totalElements; n++) {
            $('#' + n).remove();
        }
        createElement(2);
        totalElements++;
    });

})
</script>
eburlea 23 Junior Poster

Hi. I have a select box with the id=1. I need a solution for: when changing the select box with the id=1 to appear another select box with the id=2 and when changing the select box with the id=2 to appear another with the id=3, and so on.
I have writen a code, and I do not understand why it does not work the way I need. It works only when I change the first select box. Can somebody advise, please.

<select id="1" name="1">
    <option value="Value 1">Text 1</option>
    <option value="Value 2">Text 2</option>
    <option value="Value 3">Text 3</option>
    <option value="Value 4">Text 4</option>
    <option value="Value 5">Text 5</option>
</select>

<div id="newselect">&nbsp;</div>

<script type="text/javascript">
$(document).ready(function(){
    var i = 1;

    $('#' + i).change(function(){
        i++;
        alert(i);
        var s = $('<select id="' + i + '" name="' + i + '" />');
        $("<option />", {'value':'Value 1', 'text':'Text 1'}).appendTo(s);
        $("<option />", {'value':'Value 2', 'text':'Text 2'}).appendTo(s);
        $("<option />", {'value':'Value 3', 'text':'Text 3'}).appendTo(s);
        $("<option />", {'value':'Value 4', 'text':'Text 4'}).appendTo(s);
        $("<option />", {'value':'Value 5', 'text':'Text 5'}).appendTo(s);
        s.appendTo("#newselect");
    });

})
</script> 
eburlea 23 Junior Poster

One friend helped me to find out the solution:

$captcha = new Zend_Captcha_Figlet(array(
                'name' => 'foo',
                'wordLen' => 6,
                'timeout' => 300,
            ));

        if(!isset($_POST['my_text'])) {

            $captcha_code = $captcha->generate();
            $captcha_image = $captcha->render();

            echo '<form method="post" action="">';
            echo $captcha_image;
            echo '<input type="text" name="my_text" />';
            echo '<input type="hidden" name="captcha_code" value="'.$captcha_code.'" />';
            echo '<input type="submit" value="Submit" />';
            echo '</form>';

        } else {

            echo $_POST['my_text'].'<br />';
            echo $_POST['captcha_code'].'<br />';

            if ($captcha->isValid(array('id' => $_POST['captcha_code'],'input' => $_POST['my_text']))) {
                echo 'Validated!';
            } else {
                echo 'Not validated!';
            }

        }
eburlea 23 Junior Poster

Thank you for reply. I inserted your code in my file:

if(!isset($_POST['my_text'])) {

            //$view = new Zend_View();

            $captcha = new Zend_Captcha_Figlet(array(
                'name' => 'foo',
                'wordLen' => 6,
                'timeout' => 300,
            ));

            $captcha_code = $captcha->generate();
            //$captcha_image = $captcha->render($view);
            $captcha_image = $captcha->render();

            echo '<form method="post" action="">';
            echo $captcha_image;
            echo '<input type="text" name="my_text" />';
            echo '<input type="hidden" name="captcha_code" value="'.$captcha_code.'" />';
            echo '<input type="submit" value="Submit" />';
            echo '</form>';

        } else {

            echo $_POST['my_text'].'<br />';
            echo $_POST['captcha_code'].'<br />';

            if ($captcha->isValid($_POST['my_text'], $_POST)) {
                // Validated!
            }

        }

...and I've got the following result:

VEKOVI
812084cdd6af6fe2efa592c071923b60

Notice: Undefined variable: captcha in /var/www/soccerstatistics/application/controllers/SoccerController.php on line 328

Fatal error: Call to a member function isValid() on a non-object in /var/www/soccerstatistics/application/controllers/SoccerController.php on line 328

I have tried other changes also, but nothing. I need to know the exact mechanism of how it works, that is why I posted here. I cannot figure it out... :((

eburlea 23 Junior Poster

I've tried many of the methods from this page and nothing.

eburlea 23 Junior Poster

Hi all.

For 3 days I have searched the web to find out how it works, unfortunatelly with no success.

I need to compare the encrypted haptcha code with my text, both of them sent by a form.

if(!isset($_POST['my_text'])) {

            $view = new Zend_View();

            $captcha = new Zend_Captcha_Figlet(array(
                'name' => 'foo',
                'wordLen' => 6,
                'timeout' => 300,
            ));

            $captcha_code = $captcha->generate();
            $captcha_image = $captcha->render($view);

            echo '<form method="post" action="">';
            echo $captcha_image;
            echo '<input type="text" name="my_text" />';
            echo '<input type="hidden" name="captcha_code" value="'.$captcha_code.'" />';
            echo '<input type="submit" value="Submit" />';
            echo '</form>';

        } else {

            echo $_POST['my_text'].'<br />';            
            echo $_POST['captcha_code'].'<br />';

        }

Please help how can I compare $_POST['my_text'] and $_POST['captcha_code'].

Thank you.

eburlea 23 Junior Poster

The main problem is that it is not possible to send values by POST method directly to another domain (it would be possible through a php file).

In case the domain would be the same, it would be necessary to add "return false;" as last statement in the submit function - as stated by pritaeas in the post above, and also ".value();" from line 13 need to change to ".val();".

eburlea 23 Junior Poster

NOTE!

It is working if I replace:

<form id="myform" action="#">

with:

<form id="myform" action="http://semaffiliate.local/public/api/getemployees" method="post">

The problem is that the result I get on the other page, but I need it in the same page as the form.

eburlea 23 Junior Poster

Hi all.

I have 2 pages:

  1. that provides data from mysql in json encoding if a correct "key" is provided, in my case the "key" sent by method post should be "1".
    Link: http://semaffiliate.local/public/api/getemployees
    Code in Zend:

    public function getemployeesAction()
    {
        $key = $this->getRequest()->getPost('key');
        if (isset($key)) {
            if ($key == 1) {
                $employeeModel = new Application_Model_DbTable_Employee();
                $employees = $employeeModel->fetchAll()->toArray();
                $res = array('status' => 'Success', 'settings' => $employees);
            } else {
                $res = array('status' => 'Error', 'message' => 'Access denied, invalid key supplied.');
            }
        } else {
            $res = array('status' => 'Error', 'message' => 'Access denied, you must supply a key.');
        }
            $json = Zend_Json_Encoder::encode($res);
            header('Content-Type: application/json; charset=utf-8');
            print Zend_Json::prettyPrint($json);
    }
    
  2. that has a form, a div where the result should come and an ajax request.
    Link: http://soccerstatistics.local/public/api/index2
    Code:

       <form id="myform" action="#">
        <input id="mytext" type="text" name="key" size="10" placeholder="Type the key here..." />
        <input id="mysubmit" type="submit" value="OK" />
        </form>
    
    
    
    <div id="mydata"></div>
    
    <script type="text/javascript">
    $(document).ready(function(){
        $('#myform').submit(function(){
            var postData = "key=" + $('#mytext').value();
            $.ajax({
                type: "POST",
                url: "http://semaffiliate.local/public/api/getemployees",
                data: postData,
                success: function(data) {
                    $('#mydata').html(data);
                },
                error: function() {
                    alert('Error');
                }
            });
        });
    })
    </script>
    

After I submit the form, the link becomes: http://soccerstatistics.local/public/api/index2?key=1# and nothing is returned.

Please advise what can be the problem. Thanks.

eburlea 23 Junior Poster

Thank you.
I would like to add here also a link with good Zend documentation I have found: http://framework.zend.com/learn .

eburlea 23 Junior Poster

Hi all. I am a beginner in Zend and I am wondering if there is any good book or tutorial for developing applications with Zend Framework, using json for data encoding and decoding and how to use jquery with Zend. Thanks.

eburlea 23 Junior Poster

Hello.

I have a larger database that I want to import and I cannot do that using phpmyadmin. I tried to do this in many possible ways by command line, but I get message 'wrong syntax'.

I have Windows Vista, MySQl version 5.5.24, wamp server. The path to mysql.exe is: C:\wamp\bin\mysql\mysql5.5.24\bin\mysql.exe. The myfile.sql I located in the same folder with mysql.exe.

Using cmd I managed to go to mysql.exe:
mysql>

I have created a new database in MySql: mydatabase.

I wrote the following instructions after mysql> that gave the same error message:

mysql -u root -p mydatabase < myfile.sql
mysql -u [root] -p [mydatabase] < [myfile.sql]
mysql -u {root} -p {mydatabase} < {myfile.sql}
-u root -p mydatabase < myfile.sql
-u [root] -p [mydatabase] < [myfile.sql]
-u {root} -p {mydatabase} < {myfile.sql}

Please advise, where I am wrong. Thanks a lot.

eburlea 23 Junior Poster

@pritaeas
You are right. I'm using PHP Version 4.3.6. I will update it. Thank you.

eburlea 23 Junior Poster

Thank you for reply. I tried your code and also it does not work. The problem is that the code does not work when I use the declarations: public, protected, private. When I remove them, it works, as in the example below.

class Login {
  var $good_username;
  var $good_password;
  function Authentification () {
    $this->good_username = "myusername";
    $this->good_password = "mypassword";    
  }
}
eburlea 23 Junior Poster

Hello.

The code below returns an error. Please advise what is wrong with it. Thank you.

class Login {
  private var $good_username;
  private var $good_password;
  public function Authentification () {
    private $this->good_username = "myusername";
    private $this->good_password = "mypassword";    
  }
}
eburlea 23 Junior Poster

Jimnto
Also please notice that "innerText" works in Internet Explorer, Chrome and Opera. In Firefox replace it with "textContent".

eburlea 23 Junior Poster

@Jimnto
1. First you need to place the JavaScript code before the closing tag </body>, because the whole page needs to load for the code to act.
2. If you need to get the information between tags, you can use "getElementsByTagName" method. Because it returns an Array, you need to use a loop type "for".
3. Instead using "alert" I think in this situation it is better to use "document.write".
In this way we have the code:

<HTML>
<HEAD>
<TITLE>This is a test document for stripping text</TITLE>
</HEAD>

<body>
<h1 id="header1" onclick="getValue()">Click me!</h1>
<h3 id="home"><span class='yellowcard'>Tottenham</span></h3>
This is a text document
<h3 id="home"><span class='yellowcard'>Jim Nielsen</span></h3>
This is a text document
<h3 id="home"><span class='yellowcard'>Hello</span></h3>
This is a text document
<h3 id="home"><span class='yellowcard'>This is what</span></h3>
This is a text document
<h3 id="home"><span class='yellowcard'>I wuld like to strip out</span></h3>
This is a text document

<script type="text/javascript">
function getValue(){
  var x = document.getElementsByTagName("h3");
  document.write("<br /><br />The info below is provided by JavaScript code:<br />");
  for (var i=0; i<x.length; i++){
    document.write(x[i].innerText + "<br />");
  } 
}
getValue();
</script>
</body>
</HTML>

Hope this helps.

eburlea 23 Junior Poster

And from other html code above we need to get the text from a <td> tag that belongs to a certain class:

<td class="home uc winteam"> <span class='yellowcard'></span> Tottenham</td>

With jQuery we can get it in the following way:

var homeTeam = $('td[class^=home]').text();
alert(homeTeam);

This means: get the text from the <td> tag which classname begins with "home".

eburlea 23 Junior Poster

Because there are many differences in interpreting the JavaScript codes by browsers, it is better to use jQuery in such situations.

eburlea 23 Junior Poster

This works in Firefox:

<body>

<table>
  <tr>
    <td id="home"><span class='yellowcard'></span>Tottenham</td>
    <td id="away">Chelsea</td>
  </tr>
</table>

<script type="text/javascript">
var homeTeam = document.getElementById('home');
alert(homeTeam.textContent);
</script>

</body>
eburlea 23 Junior Poster

This works in Internet Explorer, Chrome and Opera:

<body>

<table>
  <tr>
    <td id="home"><span class='yellowcard'></span>Tottenham</td>
    <td id="away">Chelsea</td>
  </tr>
</table>

<script type="text/javascript">
var homeTeam = document.getElementById('home');
alert(homeTeam.innerText);
</script>

</body>
eburlea 23 Junior Poster

You guys are amazing, finding solutions so fast! Thank you so much, JorgeM. Now I know what should be changed. Thanks again.

eburlea 23 Junior Poster

Hi.

In March current year I started learning html, css, php, mysql, and a month ago started with Javascript. I have a webpage that I am working on to have practical tasks for finding solutions to them.

I have created a Javascript code that colores the rows of a table when the mouse is over them. The problem is that Javascript code is not working when the page is accessed through a link that sends variables by "_GET" method. You can check it on: http://soccerstatistics.eu/index.php (I need to tell that the Javascript code I added only on this page (index.php), for testing). But when I click in the page on "Full Time" that brings me to the same page (index.php): http://soccerstatistics.eu/index.php?season=2012-2013&&s_type=Over+2.5+Goals , the rows of the table are not changing the colors anymore. When I go back clicking on "Home", it works again.

Please help me to find a solution. The Javascript code is:

<script>
var rows = document.getElementById("leagues_stands").getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
  if(rows[i].className == "blue_odd") {
    rows[i].onmouseover = function() {
      this.style.backgroundColor = "#00AED1";
    };
    rows[i].onmouseout = function() {
      this.style.backgroundColor = "#CCFFFF";
    };
  }
  else if(rows[i].className == "blue_even") {
    rows[i].onmouseover = function() {
      this.style.backgroundColor = "#00AED1";
    };
    rows[i].onmouseout = function() {
      this.style.backgroundColor = "#9FEEEE";
    };
  }
}
</script>
eburlea 23 Junior Poster

I have found the solution. I think because getElementsByTagName provides an ARRAY of ALL the tags found, I can only check through the respective array for the tags that belong to a certain class. Thus I bring here the Javascript code that finally is working:

<script>
var rows = document.getElementById("leagues_stands").getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
  if(rows[i].className == "blue_odd") {
    rows[i].onmouseover = function() {
      this.style.backgroundColor = "#00AED1";
    };
    rows[i].onmouseout = function() {
      this.style.backgroundColor = "#CCFFFF";
    };
  }
  else if(rows[i].className == "blue_even") {
    rows[i].onmouseover = function() {
      this.style.backgroundColor = "#00AED1";
    };
    rows[i].onmouseout = function() {
      this.style.backgroundColor = "#9FEEEE";
    };
  }
}
</script>
eburlea 23 Junior Poster

I'm wondering just if it is possible to make the same in php without being necessary to press a button.

eburlea 23 Junior Poster

I realised that the background color applied to <td> with CSS overwrites the background color applied to <tr> with Javascript. So that I removed the classes from <td> and placed them to <tr>:

/* Creating the table for leagues statistics */
  echo '<p>Full Time Over 2.5 Goals</p>';
  echo '<table id="leagues_stands">';
    echo '<tr>';
      echo '<td id="s" class="blue_header">#</td>';
      echo '<td id="xl_header" class="blue_header">League</td>';
      echo '<td id="m" class="blue_header">%</td>';
    echo '</tr>';
  $i = 0;
  $n = 1;
  while (isset($var[$i]))
    {
    echo '<tr class="blue_odd">';
      echo '<td id="s">'.$n.'</td>';
      echo '<td id="xl_body"><a href="overview.php?association='.$association[$i].'&&competition='.$league[$i].'&&season='.$s[$i].'">'.$association[$i].' '.$league[$i].'</a></td>';
      echo '<td id="m">'.number_format($var[$i],1).'%</td>';
    echo '</tr>';
    $i++;
    $n++;
    if (isset($var[$i]))
      {
      echo '<tr class="blue_even">';
        echo '<td id="s">'.$n.'</td>';
        echo '<td id="xl_body"><a href="overview.php?association='.$association[$i].'&&competition='.$league[$i].'&&season='.$s[$i].'">'.$association[$i].' '.$league[$i].'</a></td>';
        echo '<td id="m">'.number_format($var[$i],1).'%</td>';
      echo '</tr>';
      $i++;
      $n++;
      }
    }
  echo '</table>';

Javascript code works and it is as follows:

<script>
var myTable = document.getElementById("leagues_stands");
var rows = myTable.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
    rows[i].onmouseover = function() {
        this.style.backgroundColor = "#FF0000";
    };
    rows[i].onmouseout = function() {
        this.style.backgroundColor = "#CCFFFF";
    };
}
</script>

The problem now is other. The table rows are of two different colors, and I need them to be as they were before, after the mouse is out of the row. I have tried to use getElementsByClassName, but it does notwork.

What can be done?

eburlea 23 Junior Poster

Yes, the files are in utf-8 charset format.

eburlea 23 Junior Poster

Interesting fact is that when I include in the code the method alert("It is working!"); the alert message displays in both cases, except changing the color (working only when CSS file is removed).

<script>
var myTable = document.getElementById("leagues_stands");
var rows = myTable.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
    rows[i].onmouseover = function() {
        this.style.backgroundColor = "#FF0000";
        alert("It is working!");
    };
    rows[i].onmouseout = function() {
        this.style.backgroundColor = "#FFFFFF";
    };
}
</script>