Question

I have a form with two input boxes. Song and Artist. When the search button is pressed, it uses the JQuery function of .post() to post the data to a PHP page and return results back to the page.

Here is my JavaScript code:

<script>
    $(function() {

        $("#submitSearch").bind("click", function() {
            var songTitle = $("#song").val();
            var artistName = $("#artist").val();

            $.post("getSearchResults.php", {
                artist: artistName, 
                song: songTitle
            },
            function( data, status ) {
                $("#searchResults tbody").last().append( data );
            });
        });
    });
</script>

The goal is to put the results into the <tbody> of the "searchResults" table.

<table id="searchResults">
    <thead>
        <tr>
            <th>Title</th>
            <th>Artist</th>
            <th>Album</th>
            <th>Add To List</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

However, it doesn't seem to be inserting the results into the table.

It's not until I put an alert() message in the Javascript Code that it shows it.

<script>
    $(function() {

        $("#submitSearch").bind("click", function() {
            var songTitle = $("#song").val();
            var artistName = $("#artist").val();

            $.post("getSearchResults.php", {
                artist: artistName, 
                song: songTitle
            },
            function( data, status ) {
                $("#searchResults tbody").last().append( data );
            });

            alert("test");

        });
    });
</script>

When I dismiss the "test" alert, it puts the results into the table and very quickly they disappear.

What am I missing here? Please help me! I am stumped. Thanks in advance.

Was it helpful?

Solution

Try this...

<script>
    $(function() {

        $("#submitSearch").bind("click", function(e) {
            e.preventDefault();
            var songTitle = $("#song").val();
            var artistName = $("#artist").val();

            $.post("getSearchResults.php", {
                artist: artistName, 
                song: songTitle
            },
            function( data, status ) {
                $("#searchResults tbody").last().append( data );
            });
        });
    });
</script>

I added an event parameter to the click function, and e.preventDefault(). this stops the submit actually taking place, which is reloading your page. Also, depending on which version of jQuery you are using you may want to use on() instead of bind(). (It's exactly the same syntax as above.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top