user2137186
user2137186

Reputation: 837

Call same function on page load and when form submit

 $("#GetLog").submit(function (e) {
        e.preventDefault();
        $.ajax({
                 //some code

         });
   });
   <form id="GetLog"> 
         <input type="submit">
   </form>

I want to call this function when the page loads and when the user presses the submit button.

I have tried document.getElementById("GetLog").submit() on page load but it does call the function.

Upvotes: 0

Views: 265

Answers (5)

Adil Shaikh
Adil Shaikh

Reputation: 44740

$(function(){
 $("#GetLog").submit(function (e) {
       e.preventDefault();
       $.ajax({
            ...
       })
 }).submit();
});

Upvotes: 0

Daniele
Daniele

Reputation: 1938

Try defining a separate function and call on load and on submit

function ajaxCall(){
   $.ajax({
             //some code

     });
}

$(document).ready(function(){
    ajaxCall();
});

$("#GetLog").submit(function (e) {
    e.preventDefault();
    ajaxCall();
});

Upvotes: 2

Kousik
Kousik

Reputation: 22425

window.onload = function(){
    //call the function
}

$(document).ready(function(){
    $(document).on('click','#GetLog',function (e) {
        e.preventDefault();
        $.ajax({
            //some code

        });
    });
})
<form id="GetLog"> 
    <input type="submit">
</form>

Upvotes: 2

barrigaj
barrigaj

Reputation: 371

 $(document).ready(function(){
   $("#GetLog").submit(function (e) {
      e.preventDefault();
      $.ajax({
             //some code

      });
   });
   //I want to call this function when page loads
   $('#GetLog').trigger('submit');

});

Upvotes: 1

Erty Seidohl
Erty Seidohl

Reputation: 4559

Try using a non-anonymous function, and just pass that function in to the various listeners.

Example:

function submitFtn = function (e) {
    e.preventDefault();
    $.ajax({
             //some code

     } 
$("#GetLog").submit(submitFtn);
$(document).ready(submitFtn)

<form id="GetLog"> 
      <input type="submit">
</form>

Upvotes: 2

Related Questions