简体   繁体   中英

Ajax Live Search - Get 2 Fields instead of 1

I have a small problem, I want to a live search that returns me a POST_TITLE and a POST_ID. the title is for the people to see but my main reason is that I want the POST_ID to work with it.

Can someone help me, I posted the code below...

   <script>
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
    }
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
    if (searchReq.readyState == 4 || searchReq.readyState == 0) {
        var str = escape(document.getElementById('txtSearch').value);
        searchReq.open("GET", '/wp-content/themes/twentyten/livesearch.php?search=' + str, true);
        searchReq.onreadystatechange = handleSearchSuggest;
        searchReq.send(null);
    }        
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
    if (searchReq.readyState == 4) {


           var sx = document.getElementById('restaurantid')
        sx.innerHTML = '';

        var ss = document.getElementById('search_suggest')
        ss.innerHTML = '';
        var str = searchReq.responseText.split("\n");
        for(i=0; i < str.length - 1; i++) {
            //Build our element string.  This is cleaner using the DOM, but
            //IE doesn't support dynamically added attributes.
            var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
            suggest += 'onmouseout="javascript:suggestOut(this);" ';
            suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
            suggest += 'class="suggest_link">' + str[i] + '</div>';
            ss.innerHTML += suggest;
            ss
        }
    }
}

//Mouse over function
function suggestOver(div_value) {
    div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
    div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
    document.getElementById('txtSearch').value = value;
    document.getElementById('restaurantid').value = value;
    document.getElementById('search_suggest').innerHTML = '';
}
</script>


<form id="frmSearch" action="">
    <input type="text" id="restaurantid" name="restaurantid" style="display: none;" />
                    <input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
                    <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" />
                    <div id="search_suggest"></div>
                </form>
</code>

livesearch.php - THE AJAX PAGE

<code>
<?php

$con = mysql_connect('x', 'x', 'x);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("xx", $con);
if (isset($_GET['search']) && $_GET['search'] != '') {
    //Add slashes to any quotes to avoid SQL problems.
    $search = addslashes($_GET['search']);
    //Get every page title for the site.
    $suggest_query = mysql_query('SELECT * FROM `mrr_posts` WHERE `post_title` LIKE \'%'.$search.'%\' AND `post_status` LIKE \'publish\' LIMIT 0, 30') or trigger_error("Query: $suggest_query\n<br />MySQL Error: " .mysql_error());            
    while ($suggest = mysql_fetch_array($suggest_query, MYSQL_ASSOC)) {    
    //while($suggest = db_fetch_array($suggest_query)) {
        //Return each page title seperated by a newline.
        echo $suggest['post_title'] . "\n";
    }
}





mysql_close($con);
?>

I noticed in the discussion above you're returning JSON now, and parsing it from the client side. And I noticed you tagged your question with jQuery, so I guess you're using that. This isn't an answer to your question, but here are some tips for javascript coding with jQuery that will help simplify your code a ton.

  • instead of doing your ajax calls using the XMLHttpRequest object directly, just use $.get(url, successFunction)
  • instead of using getElementById('some-id'), use $('#some-id'), then to do things like empty out the inner html, you can do $('#some-id').html(''). Using the jQuery element instead of HTMLElement, you can also manipulate the DOM in a cross-browser compatible way: http://api.jquery.com/category/manipulation/
  • instead of building your javascript into your HTML (all those onmouseover and onmouseout handlers), use $('div.suggest_link') to select all divs on the page that have a class of "suggest_link". Then, attach a live event handler which will work on dynamically generated html, like this: $('div.suggest_link').live('mouseover', handleMouseOverForSuggestLink). You can read more about this on jQuery's page: http://api.jquery.com/live/

All these suggestions will work in modern browsers, and will help cut down a lot of code. Good luck!

You should return data from server in JSON (or XML, but JSON is easier), and then parse it in Javascript. Show titles to user, id keep for yourself.

In general xajax might simplify things quite much. Have a look at my answer here:

how to assign a javascript variable to a smarty variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM