I have writing a website that has several categories for which the data has to be pulled from the mongo database. So far i had written plan ajax calls but since this requirement need me to keep using the same ajax calls for variety of things i have begun to think about reusable code/patterns. I am a newbie to Javascript module patterns but so far what i read and understood , looks like the Revealing module pattern might be a good start for me rather than getting too much confused with rest of the object oriented stuff.
I know there are a lot of links , docs available in SOF and internet but i really could not get the direct answer for my simple requirement to start with so that i take it to the next level with what understand.
I have written a testing code here...
var myApp = new function () {
var Var1 = [];
getData = function (sendData) {
return $.ajax({
type: "POST",
url: URL,
data: sendData,
datatype: "json",
success: function (results) {}
});
};
getOffers = function (sendData) {
getData(sendData);
};
return {
getOffers: getOffers
};
}();
getData is kept private to pull records from database and getOffers is public that call from outside as i understand. But, how do i get the success return of my ajax call outside of them ?
What i want to achieve is have an easy method to call my functions like below ..
myApp.getOffers({
'showData': 1,
'myLocation': "Location1",
'clientID': "Client1"
});
myApp.getOffers({
'showData': 1,
'myLocation': "Location2",
'clientID': "Client2"
});
that fetches data from my mongodb so that i can alter them based on my requirement. Each of them when returned values , i would manipulate to show them in diff Div's so that action need to be outside of my definition as these are not static.
How do i achieve it since it works when i return something from the function directly but when it has to return from ajax it does not due to the callback i have to write. But how is this generally written so that we can reuse the code and alter sending variety of fields with a simplest approach ?
Please alter this code so that i understand it better and start with something very basic to suit my requirement. OR send me few links that really explains my basics.
Also, I stick to ajax "POST" method for myApp for a reason i think is that when a "GET" method is used, users knowing what variable i pass(from its source-code) can directly send them as action.php?variable=1&variable=2. How do i avoid it if i can use GET method safely ?