0

Background Information

I have a php web application that uses a template approach to my pages. So in other words, I have a header.php, footer.php and a leftnav.php. Each view in my php app includes all three pages listed above. So far, so good. Everything works.

As a part of my leftnav.php, I have the following code:

<div class="input-group custom-search-form">
    <input type="text" class="form-control" placeholder="Quick Search..." id="searchtext">
     <span class="input-group-btn">
            <button class="btn btn-default" type="button" id="qsearch">
              <i class="fa fa-search"></i>
               </button>
      </span>
 </div>

The idea is to provide the users with a "quick search" option that they can use where ever they are in the application... It always shows up because every page includes the same menu stored in leftnav.php.

Problem

This code works fine ONLY if you launch my app and trigger the search right away. But if you navigate away from the default controller, and then the user tries to run the search... nothing happens because they're not in the default controller.

So for example, here's the default URL when you launch my web app:

 http://myserver/testapplication/index.php

From here, you can run the quick search and the dashboard controller kicks in.

But from somewhere else like this:

http://myserver/testapplication/index.php/widgets/addwidget

the search button does nothing.

Question

I don't know how to set up my code so that whenever the user clicks on the search submit button, the first thing that happens in the system redirects to the dashboard controller.

The logic that actually runs the search is in my default controller, called "Dashboard". The controller looks like this:

public function index()
{
            $data['main_content'] = "dashboard";
            $this->load->view('includes/template',$data);
}
public function quicksearch()
{
            //grab search text
            $seg3 = $this->uri->segment(3); //hardwaremodel 
    $searchresults = $this->dashboard_model->quick_search($seg3);
    $retval = array();
    foreach ( $searchresults as $id => $value )
    {
        //logic to build results array

        array_push($retval, $temp);         
    }
    echo json_encode($retval);
  }
}

And the view that includes the logic to display the search results is in the "dashboard.php" file.

$(document).ready(function(){
    $(".searchresults").hide();

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

            $('#qsearchresults tbody').empty();
            var searchstring = $('#searchtext').val();
                var searchurl = "<?php echo site_url('dashboard/quicksearch/');?>" + searchstring;
            $.ajax({
                    url:searchurl,
                    type:'POST',
                    dataType:'json',
                    success: function(res) {
                    if (res.length > 0) {
                    var htmlstring = "<tr><th>ID</th><th>PH</th><th>Site</th><th>Location</th><th>Department</th><th>Description</th><th>Fax?</th><th>Last Assigned Date</th><th>Score</th></tr>";
                    for (var key in res) {
                    tmpurl = "<?php echo site_url('did/getdidbyobjid/')?>";
                    //bunch of logic to build html string with search results
                        }
                        $('#qsearchresults tbody').append(htmlstring); 
                    $('.searchresults').show();
                }
                    }, 
                error: function(xhr, req, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    console.log(err.Message);
                }
            });


    });
  });

EDIT 1

I tried to put all the javascript that handles the search button click event into a separate js file called qsearch.js. qsearch.js is now included in the header.php... which in turn in included by all views.

<head>
    <script src="<?php echo base_url(); ?>assets/l/js/qsearch.js"></script>
</head>

Test

This works: (because it's launch the default controller Dashboard)

http://myserver/myapp/index.php/

But let's say i go to:

http://myserver/myapp/index.php/reports/dept

the search IS WORKING... but it has no where to display the results. The javascript that handles the search click event does this in part:

$('#qsearchresults tbody').append(htmlstring); 

"htmlstring" contains the results of the search... but not all pages have the html table called qsearchresults.

So I guess I need to know if it's possible to redirect the user to the dashboard controller and then run the search.

If not, no worries. I will redo the code and use a static form inside the leftnav.php menu. But I'm so close, I'd like to leave it as is... if possible

I found this link: How to redirect on another page and pass parameter in url from table? and I'm trying to see if I can adapt it to my use case.

Community
  • 1
  • 1
Happydevdays
  • 1,982
  • 5
  • 31
  • 57
  • The straightforward solution is to not use ajax, post a form to a particular method and have that method redirect. – Kisaragi Nov 15 '16 at 19:52
  • If I understand correctly, the search javascript is in `dashboard.php`. If that is true, the the answer is to move the js to an external file and use a `` tag either in the `` or just before `` – DFriend Nov 15 '16 at 20:01
  • From the [PHP manual](http://php.net/manual/en/function.array-push.php): "If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function." – DFriend Nov 15 '16 at 20:09
  • @DFriend yes, the javascript is in dashboard.php. I moved it to an external file, included that external file in the header.php. Header.php is included in all views / pages. But ... it still doesn't work. The main page still works (dashboard.php) but when you're on a different page/controller and try entering something in the search box, nothing happens. – Happydevdays Nov 16 '16 at 13:07
  • @DFriend, a little more on what I've found with your suggestion, in case it helps. Please check out EDIT 1 – Happydevdays Nov 16 '16 at 13:13
  • I think you answered your own question - at least in regard to "where" the search results goes. Clearly the html block `$('#qsearchresults tbody')` has to be on each page that you want to show search results. You can either add that block to each page - easy with templating - or you could return that whole html block and push into the DOM in the appropriate place. – DFriend Nov 16 '16 at 15:19
  • DFriend, I don't think I understand your last comment about returning the whole HTML block. Can you explain a little further? – Happydevdays Nov 16 '16 at 15:27

1 Answers1

0

First of all, the form and ajax will only work if your JS is included on every page (which it appears you are only adding on the dashboard from your description). This is easily achieved in a slight customization to the way your template system works, you do not have to add it to every controller.

However, I would suggest you actually use a form with form_open and a submit button styled in any way that suits. The submit button will then submit to your search controller from any page. Having a dedicated non-ajax search results page allows you to do lots of things very easily, without worrying about loading the same js on every page, and disabling it on pages where you do not have the search.

A dedicated search results page is actually very user freindly. The form_open will also give you xss protection if you have that enabled by adding the hidden xss code that will be updated on every page.

You can read about it here: http://www.codeigniter.com/user_guide/helpers/form_helper.html

One of the benefits is that you can show a more complex result set. For instance for a shop you can show exact matches, suggested matches, matching categories, matching sub-categories etc in a layout that is user friendly and easily understood. You can then develop that page to provide more and more information that you think your visitor wants. Ajax, in this situation, might not be the best answer.

A better use of ajax here might be to create a list of clickable search terms that appears when they start typing, which gives you the benefit of suggesting searches that actually produce good results rather than some of the weird searches users actually do.

I have rattled on a bit here but I hope this helps in some way.

Paul.

PaulD
  • 1,161
  • 1
  • 9
  • 14