1

Im beginner in AJAX & JS so please bear with me.

I have an AJAX that will work in 2 events :

  1. When the page loaded
  2. When a button clicked

This AJAX have an url with some variables for pagination :

url: "http://localhost/myurl/" + keyword + "/" + limit + "/" + offset

This AJAX is working fine when the page loaded, but i dont know how to call/use it again when the user click the button.

And i put the .click function in the AJAX it self, so basically i need to recall the parent. This is a code to show you what i want to do :

$.ajax({
        url: "example" + limit + offset
        type: "GET",
        error : function(jq, st, err) {
            alert(st + " : " + err);
        },
        success: function(result){
        $("#btnLoad").click(function(){
                    //recall this AJAX again here
                                            offset = (page - 1) * limit;
                    page++;
                });
        }
        });

I know copy-paste the code might work, but i dont want to do that because the AJAX is pretty long.

Any help is appreciated, Thanks :D

2
  • 3
    you can extract the function inside click() to be a new Javascript function. Re-use the new function on click() and $(document).ready() Commented Aug 2, 2013 at 10:07
  • Simply just define a function with required arguments and call that. Commented Aug 2, 2013 at 10:12

7 Answers 7

7

Add it in the event handler, and trigger the event on pageload:

$("#btnLoad").on('click', function() {
    $.ajax({
        url: "example" + limit + offset
        type: "GET",
        ....
    });
}).trigger('click');
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. Sorry i dont really understand your code. If i use your code, does it mean that the $.ajax just will work when i click a button? I need it on the page load too.
It will work in both cases, because the script adds the handler to the click event(so it's appended, which means that when you click the element the event is fired and the ajax call is executed), but it is also fired just after it is appended, and the triggering will happen on page load.
@BlazeTama Its trigerring click event. So Ajax gets called on page load as well.
Thanks for your help. Its working now :D However, theres a problem with the pagination, please kindly see it here : stackoverflow.com/questions/18015131/pagination-with-ajax-url
3

You can abstract the AJAX call out. Like this:

$(document).ready(function(){
  //this is called when the page is loaded

  //variable that hold your offset and limit in the scope of the this function
  var limit = 10,
      offset = 0,
      page = 1;

  function ajaxCall(){
    $.ajax({
        url: "example" + limit + offset
        type: "GET",
        error : function(jq, st, err) {
            alert(st + " : " + err);
        },
        success: function(result){
          offset = (page - 1) * limit;
          page++;
        });
  };

  //register event for click on button
  $("#btnLoad").on('click', ajaxCall);


  //do the initial ajax call
  ajaxCall();

});

This is not a perfect solution but should get you closer to where you want to be. Things to consider here are:

  • what happens when a user clicks the button a second time before the success callback has updated the offset and page?

Comments

2

You can extract your ajax call in method:

// here you should to define 'limit' and 'offset' variables with init values
$("#btnLoad").on('click', method); 

var method = function() {
    $.ajax({
        url: "example" + limit + offset
        type: "GET",
        ....
    });
}

method(); // call method on page load

Comments

2

Note:this will be inside the $(document).ready()

your ajax on click:

$("#my_btn").on("click",my_click_ajax)

        function my_click_ajax(){
                $.ajax({
                 type: 'POST',
                 url: 'your_url',
                 data: {a:some_value},
                 success: function(data) {
                        alert(data)
                 }
             });
            }

your onload ajax:

Note:this will be outside the $(document).ready()

window.onload=my_onload_ajax();
    function my_onload_ajax(){
         $.ajax({
                     type: 'POST',
                     url: 'your_url',
                     data: {a:some_value},
                     success: function(data) {
                            alert(data)
                     }
                 });
    }

1 Comment

Thanks. How about on the pageload?
1

put your .ajax file into $(document).ready() like this:

$(document).ready(function(){
   $('#yourid').click(function(){
   //some code here...
});
});

Comments

1

Like Shivan said: create a function and call it when the page loads and when something is clicked. Like this:

$(function(){
    MyAJAXFunction();
    $(".button").click(function(){
        MyAJAXFunction();
    });
});

function MyAJAXFunction() {
    // AJAX call here
}

Comments

1

As I understand, you want to the ajax to fire when the user clicks a button. It would be better if you create a function outside of the ajax call. Then call that function when it is successful.

div id="callAjaxRequestButton">Ajax Request</div>

$( "#callAjaxRequestButton" ).click(function() {  
                $.ajax({
                 type: 'POST',
                 url: "http://localhost/myurl/" + keyword + "/" + limit + "/" + offset,
                 data: {a:some_value},
              success: function(data) {
                    console.log(data)
              }
             });
);
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.