d3bug3r
d3bug3r

Reputation: 2586

Better PHP with Json

Hi currently i have an app on Zend php framework, and i heavily using json to fetch data from controller. Now i am not sure whether the way i parse json data into hmtl within javascript are good or not. Below are my sample code.

controller:

public function searchAction()
    {
        $search = $this->getRequest()->getParam('search');
        $user = new Application_Model_User();
        $userMapper = new Application_Model_Mapper_UserMapper();

        $usersearch = $userMapper->findByString($search);

        for($i=0; $i<count($usersearch); $i++)
        {
            $usersearch[$i]['pic'] = $this->view->getLoginUserImage($usersearch[$i]['social_id'],$usersearch[$i]['login_type'],null,null,square);
        }
          $this->_helper->json($usersearch);

    }

View: member.phtml

<div class="container">
    <div class="clearfix page-header">
        <h1 class="heading">Member Search</h1>
    </div>

<div class="clearfix layout-block layout-a">
<div class="column column-alpha member-search-container">
                <div class="search-input-container clearfix">

            <form action="/member_search?query=" class="member-search-form" id="member-search-form" method="get" name="member_search_form" data-component-bound="true">

                        <fieldset>
                            <legend>Member Search</legend>
                            <label for="name_field">
                                <strong>    Name</strong>
                            </label>
                            <span class="formNote">
                                    (e.g. Bob Smith, Bob S.)
                            </span><br>
                            <input type="hidden" name="action_search" value="Search">
                            <input class="name-field" id="story-title" name="query" size="90" type="text" placeholder="search" autocomplete="off" style="width:220px;">
                            <div id="search-box"></div>
                            <div class="auto-name" style="display: none;"></div>
                        </fieldset>

</form>         


                </div>
                <div class="member-search-results">
                </div>

</div>

</div>

</div>
<script type="text/javascript">
$(document).ready(function(){

});



$('#story-title').keyup(function(e){
    var searchbox = $(this).val();

    if(searchbox == '')
    {
        $(".similar_story_block").hide();
    }else {

    $.ajax({
        url:"<?= $this->baseUrl('index/search')?>",
        data:{'search':$('#story-title').val()},
        dataType:"json",
        type:"POST",
        cache:false,
        success:function(data){
            if(data.length > 0)
            {
                        var divHtml = '<div class="similar_story_block" style="display: block;">'+
                        '<div class="head">'+
                        '<p>People</p>'+
                        '<a href="#" id="close-element-form" onclick="javascript:closeSearchBoxMember(event)"></a>'+
                        '</div>'+
                        '<ul>';

                       for(var count=0; count<data.length;count++)
                       {
                            if(data[count]['reviews_num'] != null )
                            {
                                 data[count]['reviews_num']
                            }
                            else 
                            {
                                data[count]['reviews_num'] = 0
                            }

                            divHtml+='<li>'+

                            '<a class="pushstate no-confirm" href="' + baseUrl + 'user/' + data[count]['user_unique_name'] + '">'+
                            '<div class="image">'+
                            '<img alt="" src="'+data[count]['pic']+'">'+
                            '</div>'+
                            '<div class="fleft col-400">'+
                            '<p>'+ data[count]['name'] +'</p>'+
                            '<span>'+data[count]['reviews_num']+' Reviews</span>'+
                            '</div>'+
                            '</a>'+
                            '</li>';                        
                       }
                        divHtml += '</ul></div>';
                        $("#search-box").html(divHtml);
                        $(".search-box").show();                        


            }
            else {
                         $("#search-box").html('');
                        $(".search-box").hide();
            }
        }
    }) }
});

    function closeSearchBox(event)
    {
        disabledEventPreventDefault(event);
        $(".similar_story_block").hide();
    }



</script>

Currently the above code will do a live query of members who already signup to the site. The code work very well, but i am not sure if this is right way of doing. Below is how it looks on chrome debug console

console debug

it seems i am exposing too much of details. It would be appreciated if anyone can suggest a better way of fetch a data from controller, or how it can be done by using partial template. Thanks for your help !!!

Upvotes: 3

Views: 638

Answers (2)

Mikhail Kinchin
Mikhail Kinchin

Reputation: 1

I think if your project has a lot of visitors and this operation uses often you can relay this function to them. It's could reduce little load on the server. But it could work only if you have very many visitors (pageview). But if your project not so big you can't feel the difference and "PHP way" could be easier on my mind.

Upvotes: 0

noetix
noetix

Reputation: 4933

You can either render your template via PHP and send HTML down the wire, or you can send JSON and render your template using JavaScript.

I would suggest the latter using something like HandlebarsJS.

Define the HTML template:

<script id="member-template" type="text/x-handlebars-template">
  <p>Name: {{ name }}</p>
  <p>Role: {{ role }}</p>
</script>

Our example JSON data:

var data = {"name": "Bob", "role": "Manager"};

Render our template with our JSON data:

var template = Handlebars.compile($("#member-template").html());
var html     = template(data);

The html variable will be your compiled HTML that you can insert witin your <div class="member-search-results"> div.

Upvotes: 1

Related Questions