1

I need to process an AJAX request twice, first, when the site has been opened first time, and second, when a button is clicked. I dont want to write 2 similar functions. So I created an ajaxPost function. I wonder how to detect what event has called the ajaxPost function? opening the browser or clicking a button?

function ajaxPost() {
    url = "post.php";
    if (this!=Window) {
        button = $(this).attr("class");
    } else {
        button = "";
    }
    var posting = $.post(url,{"button": button});
    posting.done(function(data) {
        $(".word").html(data);
    });
}
$(document).ready(function() {
    ajaxPost();
    $("input[type=button]").click(ajaxPost);
});
PeterKA
  • 24,158
  • 5
  • 26
  • 48
Alvin Mahmudov
  • 103
  • 1
  • 11
  • 1
    possible duplicate of [How do you find out the caller function in JavaScript?](http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript) – putvande Jul 07 '14 at 13:59
  • 3
    Or you could pass in a parameter – Liam Jul 07 '14 at 13:59

2 Answers2

1

Check for the jQuery event that you're passing with a click.

function ajaxPost(event) {
    url = "post.php";
    if (event == undefined || event == null) { //Was not generated by a user click
        button = $(this).attr("class");
    } else {
        button = "";
    }
    var posting = $.post(url,{"button": button});
    posting.done(function(data) {
        $(".word").html(data);
    });
}
$(document).ready(function() {
    ajaxPost();
    $("input[type=button]").click(ajaxPost);
});
hotforfeature
  • 2,558
  • 1
  • 16
  • 24
1

A simple solution would be to include an additional parameter when calling the function:

function ajaxPost( caller ) {
  switch( caller ){
    case "initial_load":
      // called on page load
    break;
    case "button_click":
      // called on button click
    break;
  }
  ...
}

Now you would need to pass this parameter from the two different types of calls:

$(document).ready(function() {
  ajaxPost( "initial_load" ); 
  $("input[type=button]").on( "click", function(){
    ajaxPost( "button_click" );
  });
});
Lix
  • 47,311
  • 12
  • 103
  • 131