0

I have this ajax request where i try to find some tags and add it to search results

The problems comes when i try with my php script to find something then it doesn't find anything

<div>
<form action="search()" method="post">
    <label for="tagsearch">Search tags: </label>
    <input type="text" id="tagSearch" name="tagsearch"/>
    <input type="button" id="tagenter" value="Add tag"/>
</div>
<div id="tagHolder">
    <!--Tags here-->
</div>
</div>
<script type="text/javascript">
    $(document).ready(function(){
        function search(){
            var tag=$("tagSearch").val();

            if(tag!=""){
                $("#tagHolder").html();
                $.ajax({
                   type:"post",
                    url:"gettag.php",
                    data:"tag="+encodeURIComponent(tag),
                    success:function(data){
                        $("#tagHolder").html(data);
                        $("#tagSearch").val("");
                    }
                });
            }
        }

        $("#tagenter").click(function(){
            search();
        });

        $('#tagSearch').keyup(function(e){
            if(e.keyCode == 13){
                search();
            }
        });
    });
</script>

The above code is the ajax request.

This is the php script

//Connect to database
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

//Check if connection is up
if(mysqli_connect_errno()){
    echo "Couldn't connect". mysqli_connect_error($con);
}

$tag = $_POST["tag"];

$result=mysqli_query($con, "SELECT * FROM tags WHERE tag = '".$tag."'");
$found=mysqli_num_rows($result);

if($found>0){
    while($row=mysqli_fetch_array($result)){
        echo "<div>". $row['tag'] . "</div>";
    }
}else{
    echo "<div>No suggestions</div>";
}

mysqli_close($con);

Im getting the "No suggestions" as search result. My guess is that the SQL query is wrong or the $found variable is wrong.

  • Let's see your HTML form. I see no `
    ` tags in your posted code. `$_POST["tag"]` is taken from a POST form method.
    – Funk Forty Niner Sep 28 '14 at 16:21
  • It's probably not the problem, but `data:"tag="+tag` is wrong. It should be `data:{tag:tag}` (preferred) or `data:"tag="+encodeURIComponent(tag)`. – T.J. Crowder Sep 28 '14 at 16:22
  • Obligatory link: http://xkcd.com/327/ (you're leaving yourself wide open to SQL injection attacks). – T.J. Crowder Sep 28 '14 at 16:23
  • @Fred-ii-: The OP is using `type: "POST"` in their ajax call. – T.J. Crowder Sep 28 '14 at 16:25
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Sep 28 '14 at 16:25
  • @T.J.Crowder Ok, yet shouldn't the `` etc. be wrapped in a form tag? Or does Ajax take care of all that? – Funk Forty Niner Sep 28 '14 at 16:26
  • @Fred-ii-: No, `ajax` doesn't require forms (or form elements) at all. In this case, the OP is using a form element, but only as a means of getting the value to send. – T.J. Crowder Sep 28 '14 at 16:28
  • @T.J.Crowder Ok thanks. Now, taken the OP's edit `
    ` tag.
    – Funk Forty Niner Sep 28 '14 at 16:30
  • 1
    @Fred-ii-: Quite true. The click on `tagEnter` would work, though. But yes, on browsers that submit the form when you press the Enter key in a text field if the text field is the only field, pressing the Enter key in that field would not have the desired effect. :-) The missing `` tag probably doesn't matter. – T.J. Crowder Sep 28 '14 at 16:32
  • @OP See the comments above, plus you have `name="tagsearch"` and `var tag=$("tagSearch").val();` - am under the impression that it's case-sensitive, so try also changing all `tagSearch` to `tagsearch` or `name="tagsearch"` to `name="tagSearch"` – Funk Forty Niner Sep 28 '14 at 16:34
  • 1
    @Fred-ii-: `$("#tagSearch")` looks for the `id`, not the `name`. The `id` has the capital `S`. – T.J. Crowder Sep 28 '14 at 16:42
  • @T.J.Crowder Got it. In regards to your comment further up `data:{tag:tag}` - Am under the impression that since OP is using the named form element `name="tagsearch"` then the POST `$_POST["tag"]` shouldn't that be `data:{tag:tagsearch}`? I'm just confused as to the relation of the POST element. POST usually looks for an element of the same name. I stand at being wrong about `data:{tag:tagsearch}` though. Ajax isn't my strong point, but PHP/SQL are. – Funk Forty Niner Sep 28 '14 at 16:48
  • 1
    @Fred-ii-: We're not posting the form, so nothing related to the form matters. What `data: {tag: tag}` does is pass `ajax` an object with a property called `tag` whose value is taken from the `tag` variable. Perhaps a bit more clearly: `var foo = "bar"; $.ajax({url: "/page", type: "post", data: {prop: foo}});` would pass `prop` to the page with the value `"bar"`: `echo $_POST['prop']` would show `bar`. – T.J. Crowder Sep 28 '14 at 16:54

2 Answers2

1

There are several significant problems here.

  1. As Jeff cryptically points out, you're not getting your value from tagSearch correctly, because $("tagSearch") looks for an element with the tag name tagSearch, not the id tagSearch. To use the id, add the # to your selector: var tag=$("#tagSearch").val(); This is the primary cause of the problem you've described, but keep reading, there's a lot more to do.

  2. You're wide open to SQL injection attacks. Humorous example:

    enter image description here

    Read more about them here, and about how to defend against them here.

  3. In your ajax call, data:"tag="+tag is wrong. It should be data:{tag:tag} (preferred) or data:"tag="+encodeURIComponent(tag). With your original code, if tag contains any character that isn't directly valid in URI-encoding (loosely, in a URL), your PHP page won't quite receive what you're sending. When use use an object (my first example), jQuery will handle encoding it for you; otherwise, do the encoding yourself with encodeURIComponent.

  4. As Fred -ii- helpfully points out, Your form action is wrong, and some browsers will try to use it when the user presses the Enter key in your text field. It should be action="javascript:search()", not just action="search()". The latter will be treated as a URL.

  5. Also as Fred -ii- points out, You probably wanted to close your form element with a </form> above the </div>.


Error checking

You're also not checking for any errors in your code, such as error reporting and mysqli_error().

Those are important tools you should use during development.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

var tag=$("tagSearch").val(); try var tag=$("#tagSearch").val(); if you want to select which id is "tagSearch", use $("#tagSearch") There is more about selector in jquery http://www.w3schools.com/jquery/jquery_selectors.asp

Jeff
  • 166
  • 5