June 17, 2013

Javascript method is not working on Firefox

Merand’s Question:

My stylesheet is working on ie, however it isnt working on firefox. It gives an error such as:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable @
TypeError: document.getElementById(…) is null.

Here is my code:

<script style="javascript">
    function displayRevision2() {
        for (i = 1; i & lt; j; i++) {
            foo = document.getElementById('row' + i).innerHTML;
            substring = foo.substr(0, foo.search("n") - 1);
            //displayRevision(substring);   
            if (flag == 1) document.getElementById(substring).style.display = "";
            else document.getElementById(substring).style.display = "none";
        }
        if (flag == 1) flag = 0;
        else flag = 1;
    }
</script>
<script style="javascript">
    function dispTD(num) {
        rowtxt = '&lt;TD class="br" align="middle" id="row' + num + '">';
        document.write(rowtxt);
    }
</script>
<script style="javascript">
    function dispEndTD() {
        document.write("&lt;/TD>");
    }
</script>

It may be because the element the script is searching for does not exist on the document. Try to check if the scripts finds the element first before directly accessing its attributes.

fooElement = document.getElementById('row' + i);
if(fooElement) foo = fooElement.innerHTML;
September 5, 2012

How to set a default layout in Magento 1.5 using local.xml?

Question by Reed Richards

So I’ve done some layouts that I want to use and I was thinking that setting this in your local.xml file would fix this for every page. Like this

<default>
<reference name="root">
    <action method="setTemplate">
      <template>page/mytheme.phtml</template>
    </action>
</reference>
</default>

This however doesn’t do anything. Instead if I go

...<customer_account_forgotpassword>
  <reference name="root">
    <action method="setTemplate"><template>page/mytheme.phtml</template></action>
  </reference>
</customer_account_forgotpassword>  

<customer_account_confirmation>
  <reference name="root">
    <action method="setTemplate"><template>page/mytheme.phtml</template></action>
  </reference>
</customer_account_confirmation>...

and so on for every specific place it gets changed on those specific pages. Am I thinking wrong or this the only way to do it?

Answer by Alan Storm

The problem you’re (probably) running into is that something comes along later and sets the template for the root block again, overriding your change.

More recent versions of Magento (1.4somethingish) introduced a way to prevent this from happening. If you look in page.xml, you’ll see a handle like this

<page_one_column translate="label">
    <label>All One-Column Layout Pages</label>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
        <!-- Mark root page block that template is applied -->
        <action method="setIsHandle"><applied>1</applied></action>
    </reference>
</page_one_column>

If the page_one_column handle gets applied to your request, or you manually apply it with

<update handle="page_one_column" />

Magento will change the template and call the setIsHandle method on the block.

<action method="setIsHandle"><applied>1</applied></action>

There’s code in Magento that will look for the IsHandle property, and if it’s true, further calls to setTemplate will be ignored. (that’s over-simplifying things a bit, but is more or less true)

Try something like

<default>
    <reference name="root">
        <action method="setTemplate">
          <template>page/mytheme.phtml</template>
        </action>
        <action method="setIsHandle">
            <applied>1</applied>
        </action>       
    </reference>
</default>  

And see if that helps.

Keep in mind this is one of those grey areas where it’s not clear if third party developers are supposed to tread. Also, changing the template for all pages may have un-desirable effect on parts of the site that expect to be in a certain template.

Answer by Starx

Actually, you are the on the right track. You just didn’t specify the request on your local.xml. You should also include the request you are overriding.

Here is a example code of local.xml

<layout>
    <default>
    ....
    </default>

    <!-- Update Configuration for this request specially -->
    <customer_account_confirmation> 
      <reference name="root">
        <action method="setTemplate"><template>page/mytheme.phtml</template></action>
      </reference>
    </customer_account_confirmation>

</layout>

This much configuration is enough to do, what you need.

April 15, 2012

Importing XML in to phpmyadmin database

Question by paulyay

I’m trying to import XML from this site http://data.gov.uk/dataset/car-parks to a phpmyadmin database, so I can use it in a google maps mashup.

I’m new to this and not sure how to go about getting the XML in to the database. Do I create the database columns first and then import the data?

Answer by Starx

There is a LOAD XML method in mysql, through which you can import the data from XML into your database.

An Example:

LOAD XML LOCAL INFILE '/pathtofile/file.xml' 
INTO TABLE `tablename` (fieldl1, field2, ...);
March 30, 2012

How to display a link in <description> tag of rss feed

Question by Vinay

I am generating a rss(xml) output form a php file. I have got a link in <description> tag of rss file, I want a link to be displayed inside the description, I have written code as below.

<description><a href='http://www.google.com'>Google</a></description>

But its not displaying the link in the mozilla browser but in the IE, the text is getting printed without link, But google reader and feedburner says that it is not valid,

When I view the file source code, it looks as below

<description><a href=http://www.google.com>Google</a></description>

I know using below methods works

1) I know using htmlentities() function works, but when i view the source “<” replaced by "&lt;" , and “>” by "&gt;"

2) Using CDATA, Instructing the interpreter to not to parse the data enclosed in CDTA

In above cases the rss feed gets generated, As xml file is used to carry the data and not any presentation information, So both the cases violates the xml concept

So. Is there any way to write a valid rss(xml) file.

Answer by Starx

Check how the feed of stackoverflow works. It uses the exact same way as you are using. There is something else causing the problem probably.

March 14, 2012

Sending XML through AJAX

Question by sebbl.sche

I create a xml document in jQuery as following

var xmlDocument = $('<xml/>');
var foo = $('<foo/>');
var bar = $('<bar/>');

foo.append(bar);
xmlDocument.append(foo);

and try to forwards it to the server.

$.ajax({
   url             :   'js/foobar.php',
   type            :   'POST',
   precessData     :   false,
   contentType     :   'text/xml',
   data            :   xmlDocument,
   sucess          :   function( data ) {
      alert('success');
   },
   error           :   function() {
      alert('failed to send ajax request');
   },
   complete        :   function() {
      alert('ajax request completed');
   }
});

Even if the server echos a ‘foo’ only, I get the alert('ajax request completed') and not the alert('success'). What am I doing wrong? Is it the way I’m creating the xml document or is it the way I forward it to the server?

An ajax request without a xml document works fine and I get the ‘foo’ back.

UPDATE #1

After changing precessData to processData and sucess to success i get the failed to send ajax request dialog.

When I change the data parameter in the ajax method to

$.ajax({
   ...
   data :   {
      data: xmlDocument
   },
   ...
});

I also get the failed to send ajax request dialog.

The code on the server side should be fine cause it’s only

<?php
echo 'foo';
?>

UPDATE #2

I converted my string as in AndreasAL’s answer

// Convert to string instead of DOM Elements
xmlDocument = $("<wrap/>").append(xmlDocument).html();

// Url encode the string
xmlDocument = encodeURIComponent(xmlDocument);

but i still get the same dialog box (failed to send the ajax request). So i thought the error could be in my xml document and overwrote my xml document by using the code snipplet from AndreasAL’s answer.

xmlDocument = $('<xml/>');
foo = $('<foo/>').appendTo(xmlDocument);
bar = $('<bar/>').appendTo(foo);

Still the same behaviour.

So I checked my xml document again and printed it in a dialog box and it looks fine.

I’m running out of ideas where the error could be …

Answer by sebbl.sche

Finally, I decided to convert the xml document and send it as a string to the server.

$xmlString = $(xmlDocument).html();

Due to the fact, that I only have to store the recieved data, it makes no difference if I’m revieving it as string or xml.

I only had to change my ajax request at everything works fine now.

$.ajax({
   url             :   'js/foobar.php',
   type            :   'POST',
   data            :   'data=' + xmlString,
   success         :   function( data ) {
      alert(data);
   },
   error           :   function() {
      alert('failed to send ajax request');
   },
   complete        :   function() {
      alert('ajax request completed');
   }
});

Answer by Starx

You are using jQuery Object through the entire process.

Write your XML like this, concatenating the string together. Not making them as DOM Object.

var xmlDocument = '<xml/>';
xmlDocument += '<foo/>';
xmlDocument += '<bar/>';

Then post it, like this

$.ajax({
   url             :   'js/foobar.php',
   type            :   'POST',
   precessData     :   false,
   contentType     :   'text/xml',
   data            :   { 
                           data: xmlDocument //wrapped inside curly braces
                       },

   // Here is your spelling mistake
   success          :   function( data ) {
      alert('success');
   },
   error           :   function() {
      alert('failed to send ajax request');
   },
   complete        :   function() {
      alert('ajax request completed');
   }
});
March 8, 2012

xml to php table alternating row color

Question by bignow23

Trying to display an html table from and xml from php, getting error when trying to alternate the row base on even and odd mostly for styling the table.

foreach($bookdata as $book) // loop through our books
{
$i = 0;
        if($i%2 == 0)
   {
      $class = 'even';
   }
   else
   {
      $class = 'odd';
   }

  { 


        echo <<<EOF
        <tbody>
     <tr class='$class'>
                <td>{$book->date} </td>

                <td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
               <td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>


      </tr>
    }
       $i++;
    }


EOF;
}
 echo '</tbody>';
echo '</table>';

Any help most welcome

Answer by Starx

You are reseting the $i to 0 on every loop.

Remove

$i = 0;

from your code. And I didn’t notice this before but the EOF is misplaced. Here is a full working solution

foreach($bookdata as $book) // loop through our books
{
    if($i%2 == 0) { $class = 'even'; }
    else { $class = 'odd'; }
    echo <<<EOF
        <tbody>
            <tr class='$class'>
                <td>{$book->date} </td>
                <td><a href='http://www.website.com{$book->dataNo}.html'>{$book->Name}</td>
               <td><a href='http://www.website.com/-{$book->authorcodeNo}.html'>{$book->author}</td>
            </tr>
EOF;
       $i++;
}
March 4, 2012

PHP cant use variable defined outside functions

Question by Adonis K.

Im working on a project (simple xml CMS) just to learn some basic PHP.

first i include a config.php file which contains information about the CMS, then i include a route.php for the url routing and after that i include a functions.php file which is pretty similar to the wordpress’ one (contains all the functions to for example load posts, tags, categories etc).

The structure looks like this:

    function products($search = FALSE, $query= '', $page = 1, $results = 5){
    }

    function getProductById($id){
    }

    function getProductTitleById($id){
    }

    function getProductByExcerpt($excerpt){
    }

    function getProductTitleByExcerpt($excerpt){
    }

    function getPost($id, $title, $description, $category, $excerpt = FALSE){
    }

    function getTitle(){
    }

    function breadcrumb($params, $first){
    }

    function pagination($page, $pages){
    }
?>

In config.php file i also use this code:

$xml = simplexml_load_file('products.xml') or die('The Product xml file couldnt be loaded.');

But when i try to access $xml from within the functions i prepared in functions.php, i get a undefined variable notice. (i also tried placing the $xml variable inside the functions.php before the definition of the functions but got the same result).

Can someone please tell me my mistake? I know its simple, i just cant see clearly right now.

Thanks in advance.

Answer by Another Code

You have a scoping issue. The variables declared in the global scope aren’t visible inside your functions. The manual explains what you can do about it. An overview:

  • Import the variable from the global scope into the local scope of your function with global $xml; at the start of the function
  • Store the variable as a key of the global variables superglobal, i.e. $GLOBALS['xml']
  • Make the variable a static member of a class or create a singleton construction
  • Pass the variable as an argument to every function that needs it

Note that when using a good OOP-style architecture these kind of problems can often be avoided, e.g. $xml would be a property of class instances that need direct access to the DOM object.

Answer by Starx

Functions or methods do not have scopes outside them. In order to use a variable declared outside. Using global keyword, to tell the server to use the variable defined in higher scope.

$varname = "value";
function yourfunctionname() {
    //In order to use the variable declare you want to use the globally declared 
    global $varname;
    //now $varname will have "value` as its value

   //continue with your logic
}
February 26, 2012

Php that generates XML

Question by dane rias

<?php

require("phpsqlajax_dbinfo.php");
$dom  = new DOMDocument("1.0");
$dp   = fopen('samp.xml', 'w');
$node = $dom->createElement("Groceries");
fwrite($dp, '$node');
$parnode = $dom->appendChild($node);

$connection = mysql_connect($host, $user, $pass);
if (!$connection) {
    die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
    die ('Can't use db : ' . mysql_error());
}

$query  = "SELECT * FROM tbl_groceryitem";
$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

echo "<groceries>";
while ($row = @mysql_fetch_assoc($result)) {

    $node = $dom->createElement("item");
    echo "<echo>";
    fwrite($dp, '$node');
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("auto_id", $row['auto_id']);
    echo "<auto_id>", $row[auto_id];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_barcode", $row['Gro_barcode']);
    echo "<Gro_barcode>", $row[Gro_barcode];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_name", $row['Gro_name']);
    echo "<Gro_name>", $row[Gro_name];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_brand", $row['Gro_brand']);
    echo "<Gro_brand>", $row[Gro_brand];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_category", $row['Gro_category']);
    echo "<Gro_category>", $row[Gro_category];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_aisle", $row['Gro_aisle']);
    echo "<Gro_category>", $row[Gro_aisle];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_qty", $row['Gro_qty']);
    echo "<Gro_qty>", $row[Gro_qty];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_netwt", $row['Gro_netwt']);
    echo "<Gro_netwt>", $row[Gro_netwt];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_pic", $row['Gro_pic']);
    echo "<Gro_pic>", $row[Gro_pic];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_price", $row['Gro_price']);
    echo "<Gro_price>", $row[Gro_price];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_tax", $row['Gro_tax']);
    echo "<Gro_tax>", $row[Gro_tax];
    fwrite($dp, '$newnode');
    echo "</item>";
    fwrite($dp, '</item>');
}
fwrite($dp, '</groceries');
echo $dom->saveXML($xml);

?>

I’m new in php.

I’m creating a php file that can generate xml file with data from myPHPAdmin. Thanks :D. Hope someone can help me.

At first try, the code has been displayed in php and when I open to check for the created XML. the display was ‘$node‘, it reflects the exact string a place inside fwrite, when I try to delete the string quote (”) like this fwrite($dp,$node);. I got error.

And when I try to return the code to fwrite($dp,’$node’);. There was no Display. the XML page is blank.

Answer by Starx

You need to use XML headers when you are creating a XML file with PHP.

<?xml version="1.0" encoding="utf-8"?>

But this is not needed when you are using saveXML() on the end.

Here is an example, picked out from php’s manual.

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:n";
echo $doc->saveXML() . "n";

echo "Saving only the title part:n";
echo $doc->saveXML($title);
?>
August 9, 2011

Problem reading xml file from Zend

Question by mrN

I created a simple xml file to store name of stylesheets, where is my xml file.

<?xml version="1.0" encoding="UTF-8"?>
<skin>
    <stylesheets>
        <stylesheet>default.css</stylesheet>
    </stylesheets>
</skin>

Now I tried to read the data using the following code

protected function loadSkin() {
    $skinData = new Zend_Config_Xml('./template/'.$this -> _template.'/skins/'.$this -> _skin.'/skin.xml');
    var_dump($skinData);
    $stylesheets = $skinData -> stylesheets -> stylesheet -> toArray();
    if(is_array($stylesheets)) {
        foreach($stylesheets as $stylesheet) {
            $this -> view -> headLink() -> appendStylesheet('/template/'.$this -> _template.'/skins/' . $this -> _skin . '/css/' . $stylesheet);
        }
    }       
}

But its gives Call to a member function toArray() on a non-object. What am i doing wrong?

Answer by Starx

Actually, there is nothing wrong with your code. Its just a logical error. You have told Zend_Config_Xml to parse the stylesheet as an array. But since there is just one stylesheet you are giving, it will not parse it as an array.

Your Solution

Just add another stylesheet to the xml file.

Like

<?xml version="1.0" encoding="UTF-8"?>
<skin>
    <stylesheets>
        <stylesheet>default.css</stylesheet>
        <stylesheet>another.css</stylesheet>
    </stylesheets>
</skin>
March 18, 2011

Changing database records to xml file using php

Question by user643160

I am trying to pass items from a mysql database into an xml file using php. I have the php code that creates the xml file. But the values that are passed to it aren’t the ones from the mysql database. The database has 13 cols with 62 rows. I have five items in my foreach statement and when they displays on the web screen the values are output as follows:

Number of properties found : 62

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 R R R R R E E E E E W W W W W A A A A A h h h h h 1 1 1 1 1 < < < < < 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1

There are 65 items in the line above which is the 5 items in my foreach statement times the 13 cols in my database. This I think has something to do with it.

The following is my code:

<?php

@$db = new mysqli('localhost', 'root', '', 'siamsatire');

if (mysqli_connect_errno()) {
    echo 'error connecting to db';
    exit;
}
$query = "SELECT * from events";
$result = $db->query($query);
$num_results = $result->num_rows;
echo 'Number of properties found : <strong>' . $num_results . '</strong><br><br>';

for ($i=0; $i < $num_results; $i++) { 

    $row = $result->fetch_object(); 

    $name = $row->name; 
    $subtitle = $row->sub_title; 
    $date = $row->display_date; 
    $description = $row->slug; 
    $photo= $row->photo; 
    $thumb= $row->thumb; 

    /*echo '<tr>';
    echo "<td>$name</td>";
    echo "<td>$subtitle</td>";
    echo "<td>$date</td>";
    echo "<td>$description</td>";
    echo "<td>$photo</td>";
    echo "<td>$thumb</td>";1+0
    echo '<tr>';*/

} 

$doc = new DOMDocument("1.0");
$doc->formatOutput = true;

$r = $doc->createElement("events");
$doc->appendChild( $r );

foreach($row as $fieldvalue)
{
    $b = $doc->createElement( "event" );

    $name1 = $doc->createElement( "title" );
    $name1->appendChild( $doc->createTextNode( $fieldvalue['title'] ));
    $b->appendChild( $name1 );

    $subtitle1 = $doc->createElement( "subtitle" );
    $subtitle1->appendChild($doc->createTextNode( $fieldvalue['subtitle'] ));
    $b->appendChild( $subtitle1 );

    $date1 = $doc->createElement( "display_date" );
    $date1->appendChild($doc->createTextNode( $fieldvalue['display_date'] ));
    $b->appendChild( $date1 );

    $description1 = $doc->createElement( "slug" );
    $description1->appendChild( $doc->createTextNode( $fieldvalue['slug'] ));
    $b->appendChild( $description1 );

    $photo1 = $doc->createElement( "photo" );
    $photo1->appendChild( $doc->createTextNode( $fieldvalue['photo'] ) );
    $b->appendChild( $photo1 );

    $thumb1 = $doc->createElement( "thumb" );
    $thumb1->appendChild( $doc->createTextNode( $fieldvalue['thumb'] ) );
    $b->appendChild( $thumb1 );

    $r->appendChild( $b );
}

echo $doc->saveXML();
$doc->save("write.xml");

$result->free();
$db->close();
?>

Does anyone have any ideas as to what I’m doing wrong?

UPDATE


@starx – I changed my code around to look like this according to your code and this is what it looks like now.

<?php

    @$db = new mysqli( 'localhost', 'root', '', 'siamsatire');

    if (mysqli_connect_errno()) {
    echo 'error connecting to db';
    exit;
    }

    $query = "SELECT * from events";

    $result = mysql_query($query);  

    if(mysql_num_rows($result)) {
    $doc = new DOMDocument("1.0");
    $doc->formatOutput = true;

    while($row = mysql_fetch_assoc($result)) {
        $r = $doc->createElement( "events" );
        foreach($row as $field=>$value) {
            $tChild = $doc->createElement( $field );
            $tChild->appendChild( $doc->createTextNode($value) );
            $r->appendChild( $tChild );     
        }
        $doc->appendChild($r);
    }
        $doc->appendChild( $r );
        echo $doc->saveXML();
        $doc->save("write.xml");
    }

    //$result->free();
        //$db->close();
    ?>

And these are the errors I got with it.’

Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:xampphtdocssiamsatire1.php on line 12

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:xampphtdocssiamsatire1.php on line 12

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:xampphtdocssiamsatire1.php on line 14'

Do you know why I got them?

I then changed mysql_query to mysqli_query which cut the errors down to:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:xampphtdocssiamsatire1.php on line 12

Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:xampphtdocssiamsatire1.php on line 14

Answer by Starx

Here is a better and correct solution

$query = "SELECT * from events";
$result = mysql_query($query);
if(mysql_num_rows($result)) {
    $doc = new DOMDocument("1.0");
    $doc->formatOutput = true;

    while($row = mysql_fetch_assoc($result)) {
        $r = $doc->createElement( "events" );
        foreach($row as $field=>$value) {
            $tChild = $doc->createElement( $field );
            $tChild->appendChild( $doc->createTextNode($value) );
            $r->appendChild( $tChild );     
        }
        $doc->appendChild($r);
    }
    $doc->appendChild( $r );
    echo $doc->saveXML();
    $doc->save("write.xml");
}

You can integrate above code with your library if you want.

UPDATE (after question Update)


Here is your working solution using mysqli

<?
@$db = new mysqli( 'localhost', 'root', '', 'siamsatire');
if (mysqli_connect_errno()) {
    echo 'error connecting to db';
    exit;
}
$query = "SELECT * from events";
$result = mysqli_query($db,$query);  
if(mysqli_num_rows($result)) {
    $doc = new DOMDocument("1.0");
    $doc->formatOutput = true;

        while($row = mysqli_fetch_assoc($result)) {
            $r = $doc->createElement( "events" );
            foreach($row as $field=>$value) {
                $tChild = $doc->createElement( $field );
                $tChild->appendChild( $doc->createTextNode($value) );
                $r->appendChild( $tChild );     
            }
            $doc->appendChild($r);
        }
        $doc->appendChild( $r );
        echo $doc->saveXML();
        $doc->save("write.xml");
}

//$result->free();
//$db->close();
?>
...

Please fill the form - I will response as fast as I can!