views:

57

answers:

1

This is my Javascript below I want to show records on load and also show new records when added to the database

showrecords(); displays the records in the database where abouts can I put this in my code where it will work correctly.

$(document).ready(function()
{
    //showrecords()

    function showrecords()
    {
        $.ajax({
            type: "POST",
            url: "demo_show.php",
            cache: false,
            success: function(html){

                $("#display").after(html);

                document.getElementById('content').value='';
                $("#flash").hide();

             }

        });
    }

    $(".comment_button").click(function() {

        var element = $(this);
        var test = $("#content").val();
        var dataString = 'content='+ test;

        if(test=='')
        {
            alert("Please Enter Some Text");

        }
        else
        {
            $("#flash").show();
            $("#flash").fadeIn(400)
                .html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle">&nbsp;<span class="loading">Loading Comment...</span>');


            $.ajax({
                type: "POST",
                url: "demo_insert.php",
                data: dataString,
                cache: false,
                success: function(html){


                    // $("#display").after(html);
                    document.getElementById('content').value='';
                    $("#flash").hide();

                    //Function for showing records
                    //showrecords();

                 }
            });
        }

    return false;
    });
});
A: 

Though polluting the global namespace is not recommended. Here is what I would recommend for your code. Move the showRecords() out of Document ready function and refactor the update ajax code to another function 'updateRecords()'. Have only the event bindings inside the document ready function.

You could return the entire comments as response to POST 'demo_insert.php' service and call 'showRecords()' in the update service success callback.

shazmo
what are the event bindings in this case.Can you explain what you said abit more as I am abit of a javascript newbieThankyouPete
Pete