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?

asked Dec 7, 2013 at 16:32
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
 });
 }); 
});
answered Dec 7, 2013 at 16:37
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');
answered Dec 7, 2013 at 16:37

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");
answered Dec 7, 2013 at 16:37

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); 
 }
 });
}
BenMorel
37.1k53 gold badges208 silver badges339 bronze badges
answered Dec 7, 2013 at 16:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.