skip to Main Content

I am making a function that posts AJAX requests.

I need to call it from multiple pages, how can I make a callback method inside the done method? Or even a second callback for beforesend events.

function post_ajax(URL,CONTENT_TYPE,$RENDERING_DIV,PARAMS={},callback_function){
   $.post(URL, PARAMS, null, CONTENT_TYPE)
      .done(data => {
          callback_function()
      }).fail(() => alert('an error occurred'));
}

//function call
$('#mybtn').click(()=>{
    post_ajax('a_script.php','html','#div_res',{},callback_function())
})

2

Answers


  1. your declaration is correct (expet sending result data to callback), the problem is in the call manner of the callback function

    you need to pass a function declaration (not execution) or, just implement that function directly , by example :

    first you have to pass the result as parameter to your callback in the done

    .done(data => {
            callback_function(data) // <---- here pass data
        }).fail(() => alert('an error occurred')
    

    then in the function event call :

    //function call
    $('#mybtn').click(()=>{
        post_ajax('a_script.php','html','#div_res',{},(data) => {
            console.log(data);
            //some stuff here manipulating data 
        });
    })
    
    Login or Signup to reply.
  2. Here is an example of callback:

    function post_ajax(URL, CONTENT_TYPE, $RENDERING_DIV, PARAMS={}, callback_function) {
        $.post(URL, PARAMS, null, CONTENT_TYPE)
        .done(data => {
            if (typeof callback_function === 'function') {
                callback_function(data);
            }
        })
        .fail(() => alert('an error occurred'));
    }
    

    And now you can call it:

    $('#mybtn').click(() => {
        post_ajax('a_script.php', 'html', '#div_res',{}, (data) => { 
            console.log(data);
            alert('You are here'); 
        });
    
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search