2

Client is making a ajax call via jquery. After fetching the data from DB, I am returning the response. In this response i am applying lots of classes and styles to different html tags. This making the code look ugly.

while (my @data = $statement->fetchrow_array())
{
print " <li class='productWrap $data[7]' style='height:200px; width:150px;'>
            <center> 
                <div class=\"productImageWrap\" id=\"productImageWrapID_$data[0]\">
                <img src=$data[5] width='75' height='75'' />
                </div>
                <div>
                    <div style='font-size: 11px; font-family: \"Verdana\"; '> $data[6] $data[1] $data[2] </div>
                    <b>                             
                        <span>  <strike>   $data[3]  </strike>  $data[4] </span>
                        <a href='#' id=\"featuredProduct_$data[0]\" onclick=\" adjust_menu(this.id); simpleCart.add('name=$data[6] $data[1] $data[2]', 'price=$data[4]','image=$data[5]');           return false;\">   
                            <img src='images/add-to-basket2.gif' alt='Add To Basket' width='111' height='32' id='featuredProduct+$data[0]' />
                        </a>
                    </b>

                </div>
            </center>
        </li>";
}

Is there any way, so that i can avoid this. and apply the classes and styles at client side itself after getting the response?

2
  • have you thought of using template that can be populated with JSON? Commented Nov 13, 2013 at 13:09
  • It might be better to use JSON as the output format and do the styling completely in the frontend. With this, you can influence the whole markup client side and use status codes in your ajax calls to better understand what results are given (e.g. none found, 1 found, to many results aso.). Commented Nov 13, 2013 at 13:10

1 Answer 1

1

A good solution is to encode data in a JSON string, pass that to the client and let it render the results.

There are a couple of jquery template engines. An interesting approach is this one:

<script type="text/template" id="itemTemplate">
    <ul>
        <li class='productWrap' style='height:200px; width:150px;'>
            ...
       </li>
    </ul>
</script>

Since this isn't JavaScript, the browser won't execute it. It also won't try to render it. But you can use jQuery $('#itemTemplate ul li') to get the list item. Now you can use all the jQuery magic to insert the data into the template and add CSS styles, etc:

var item = $('#itemTemplate ul li');
item.addClass(data[7]);

Related:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.