0

This is a relatively novice question. I have the following jQuery function:

$(function () 
  {
    $.ajax({                                      
      url: 'testapi.php',       
      data: "query="+queryType,
      dataType: 'json', 
      success: function(data) 
      {
        var id = data[0];
        $('#'+divID).html(id); 
      }
    });
  }); 

I'm looking to name and parameterize the function so that I can call it repeatedly (with the parameters queryType and divID which are already included in the code). I've tried unsuccessfully multiple times. Would anyone have any insight?

1

4 Answers 4

2

Just stick it in a function

function doAjax(queryType, divID) {
    return $.ajax({                                      
        url: 'testapi.php',       
        data: {query : queryType},
        dataType: 'json'
    }).done(function(data) {
        var id = data[0];
        $('#'+divID).html(id);
    });
}

and use it

$(function() {
    element.on('click', function() {
        var id = this.id
        doAjax('get_content', id);
    }); 
});

or

$(function() {
    element.on('click', function() {
        var id = this.id
        doAjax('get_content', id).done(function(data) {
              // do something more with the returned data
        });
    }); 
});
Sign up to request clarification or add additional context in comments.

Comments

0

If you're just looking for a simple function to wrap the ajax call give this a try. Place this function above the document ready code.

function callAjax(queryType, divID) {
    $.ajax({                                      
        url: 'testapi.php',       
        data: "query="+queryType,
        dataType: 'json', 
        success: function(data) {
            var id = data[0];
            $('#'+divID).html(id); 
        }
    });
}

To call the function do this:

callAjax('YourQueryHere', 'YourDivIdHere');

Comments

0
function myFunction(queryType, divID) 
{
  $.ajax({                                      
    url: 'testapi.php',       
    data: "query="+queryType,
    dataType: 'json', 
    success: function(data) 
      {
        var id = data[0];
        $('#'+divID).html(id); 
      }
  });
}

and to call it simply use

myFunction("someQueryType", "myDiv");

Comments

0
function doThis(queryType, divID)
{
    $.ajax({                                      
      url: 'testapi.php',       
      data: "query="+queryType,
      dataType: 'json', 
      success: function(data) 
      {
        var id = data[0];
        $('#'+divID).html(id); 
      }
    });
}

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.