0

i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location. I am able to seacrh when user enters name in the search box(tab-1). In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.

First time with Ajax, any help would be highly appreciated.

AJAX script:

$(document).ready(function () {
    $("#search_results").slideUp();
    $("#button_find").click(function (event) {
        event.preventDefault();
        search_ajax_way();
    });
    $("#search_query").keyup(function (event) {
        event.preventDefault();
        search_ajax_way();
    });
});

function search_ajax_way() {
    $("#search_results").show();
    var search_this = $("#search_query").val();
    $.post("search.php", {
        searchit: search_this
    }, function (data) {
        $("#display_results").html(data);
    })
}

html:

<form id="searchform" method="post">
    <input id="search_query" name="search_query" placeholder="What You Are Looking For?"   
        size="50" type="text" />
    <input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>

<div class="tab">
    <input id="tab-2" name="tab-group-1" type="radio" />
    <label for="tab-2">Search by Category</label>
    <div class="content">
        <div id="searchbycategory">
            <div id="nav_1_a">      
                <ul>
                    <li><a href="#">All Categories</a></li>
                    <li><a href="#" id="dummy">Category-1</a></li>
                    <li><a href="#">Category-2</a></li>
                    <li><a href="#">Category-3</a></li>
                </ul>
                <div id="display_results">
                </div>
            </div>
            <!-- END nav_1_a -->
        </div>
    </div>
</div>
<div class="tab">
    <input id="tab-3" name="tab-group-1" type="radio" />
    <label for="tab-3">Search by location</label>
    <div class="content">
        <div id="searchbylocation">
            <div id="nav_1_a">      
                <ul>
                    <li><a href="#">All</a></li>
                    <li><a href="#">Location-1</a></li>
                    <li><a href="#">Location-2</a></li>
                    <li><a href="#">Location-3</a></li>
                    <li><a href="#">Location-4</a></li>
                </ul>
            </div>

search.php:

<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term); 
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like 
  '{$term}%'", $connection);

 echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
    echo "<a href=\"http://" . $info['col1'] . ".html\">" . $info['col2'] . "</a>";
    echo "</li>";
}

}else{
echo "No matches found!";
}

echo "</ul>";
}
?>
6
  • Don't use mysql_* functions anymore, they're deprecated (see the red box). Moreover, mysql_escape_string doesn't take the current character set into account and doesn't escape _ and % (use addcslashes for that). Furthermore, you should use htmlspecialchars on $info[*] to prevent XSS attacks. Commented Jan 30, 2013 at 17:19
  • Point noted, I would change the php script, but how do I pass the id name (when links are clicked) as a variable to my php script? Commented Jan 30, 2013 at 17:25
  • when user clicks a link, the id is passed in the ajax scrip Which ID you are talking about? ID of the radio button or there will be textboxs with the IDs in the other tabs? Commented Jan 30, 2013 at 17:28
  • you have an else with no if after echo "Enter name to search"; Commented Jan 30, 2013 at 17:29
  • @TheRealCoder: I want to give id's to my href's so that those id's can be passed to my script. Commented Jan 30, 2013 at 17:37

2 Answers 2

2

Pass block id to search_ajax_way function:

$("#search_query").keyup(function(event){
    event.preventDefault();
    search_ajax_way(this.id);
});

Then pass block id in data param in ajax request:

function search_ajax_way(blockId){
   $("#search_results").show();
   var search_this=$("#search_query").val();
   $.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
      $("#display_results").html(data);

   })
}

Now blockId will be availible in your php script as $_POST['blockId'].

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

5 Comments

I am gonna try this right away and get back to you. Thanks much!
So , I tried these changes above and also edited my script by adding display-results under the list of categories but nothing displays when I click on category-1 with id=dummy. Tab-1 still works fine like earlier though.
What ID you need to pass? In my answer you are passing $("#search_query") element id. If you need something else - change search_ajax_way(this.id) to search_ajax_way($(this).searchWhatEverYouWant()[0].id) with replacing searchWhatEverYouWant method to any jQuery traversing method that searches element you need.
I have different links which would have different id's, so depending on what usr clicks, I want that Id to be passed, and hence change the query. Really appreciate your help, thanks.
Everything you need is already in my answer. Think a bit. Your question was: "passing id name on click using ajax to php". I've answered how could you pass an additional argument to an AJAX call, now find ID that you need in click handler and pass it.
0

You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:

$("a").click(function (event) {
    event.preventDefault();
    search_ajax_way(this.id);
});

function search_ajax_way(clickedId) {
    $("#search_results").show();
    var postData = { searchit: $("#search_query").val() };
    if (clickedId) {
        postData.clickedId = clickedId;
    }
    $.post("search.php", postData, function (data) {
        $("#display_results").html(data);
    })
}

The id will be available in PHP as $_POST['clickedId']

Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:

$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);

function search_ajax_way(event) {
    event.preventDefault();
    $("#search_results").show();
    var postData = {
        searchit: $("#search_query").val(),
        clickedId: this.id
    };
    $.post("search.php", postData, function (data) {
        $("#display_results").html(data);
    })
}

3 Comments

I have tried both the ways above, I am definitely messing something up. Just not able to find out what. Links are just not passing the id name. I am pretty sure, something goes wrong while I switch tabs and click links. Any ideas?
@alice - Are you looking for $_POST['clickedId'] in your PHP? The property name you give in your JavaScript postData object is the field name that is submitted to PHP. Use that field name to access the value with PHP in $_POST[<field name>].
so, would this: $term = strip_tags(substr($_POST['searchit'],0, 100)); change to: $term = strip_tags(substr($_POST['clickedId'],0, 100)); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.