javascriptjqueryajaxfunctiondocument-ready

Run a function on document.ready and onClick


Is there a way to make this ajax-response run on document.ready, AND onClik without copy/paste the code in another function?

$(document).ready(function() {
var ads = $('#ads').val();
function ajax(){
    $.ajax({
        url: "./services/finn_bilder.php",
        type:"POST",
        data:{ads: ads},
        success:function(data){
            $('#AdsDiv').html(data);
        }

I want this to run onClick $('#id').click(function()); and the way its working now, without copy/paste?


Solution

  • Just call it inside document ready and bind it to document.click.

    $(document).ready(function() {
        var ads = $('#ads').val();
        function ajax(){
            $.ajax({
                url: "./services/finn_bilder.php",
                type:"POST",
                data:{ads: ads},
                success:function(data){
                    $('#AdsDiv').html(data);
                }
            });
        }
        ajax();
        $(document).click(function() {
            ajax();
        });
    }