Skip to content Skip to sidebar Skip to footer

Searching Mysql Database With Php, Ajax And Jquery

I'm trying to write a very simple search system where the user searches for a product in a small database of only about 50 entries. I'm trying to use jQuery and AJAX to send the se

Solution 1:

Your Javascript code is not correct, the event functions you have added inside the function makeAjaxRequest and hence its never called. It should be as

<scripttype="text/javascript">
$(document).ready(function(){
    functionmakeAjaxRequest() {
        $.ajax({
            url: 'search_execute.php',
            type: 'get',
            datatype: 'html',
            data: {search: $('#searchbox').val()},
            success: function(response) {
                    alert("Success!");
            }, 
            error : function() {
                    alert("Something went wrong!");
            }
        });
    }

    $('#searchbutton').click(function(){
            makeAjaxRequest();
    });

    $('form').submit(function(e){
            e.preventDefault();
            makeAjaxRequest();
    });
});          

Solution 2:

Your brackets are kind of weird in the JavaScript code. The way it looks right now, event bindings are inside the makeAjaxRequest() function, so the handlers never get bound to the events until the function is first called. Of course, the function is only ever called from the event handlers, so it's never called.

To fix this, just copy-paste the bindings outside the function.

You can also change the first binding to

$('#searchbutton').click(makeAjaxRequest);

for a small performance gain.

Solution 3:

You should use your query like

$q = '%' .$search. '%'$stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE ?");
$stmt->execute(array($q));

Solution 4:

<scripttype="text/javascript">
$(document).ready(function(){
    var sval = $('#searchbox').val();
    var datastring = "search="+sval;

    $('#searchbutton').click(function(){
        $.ajax({
            url: 'search_execute.php',
            type: 'get',
            datatype: 'html',
            data: datastring,
            success: function(response) {
                alert("Success!");
            }, error : function() {
                alert("Something went wrong!");
           }
        });
    });
});
</script>

In php file change sql

$stmt = $dbc->prepare("SELECT product_id, product_name FROM products WHERE product_name LIKE '%".$search."%' ");

Post a Comment for "Searching Mysql Database With Php, Ajax And Jquery"