I'm new to ajax and its async nature, so I'm having several issues with that that this site helped me to solved, but I can't really get on this one.
Having a list: what I'm trying to do is to get the text of the element when clicking on it, and use it in the ajax call that fires.
The result of the ajax call should be stored in a global variable array (var results). The problem is that even though each ajax call does store the result in the specific position of the array, when I print the result, only the last value seems to be saved.
I have something like this:
<head>
<script type="text/javascript">
var webServiceURL;
var soapMessage;
var results = []; // array where each ajax call result will be stored
var array= {"Mobile": 0,"TV": 1,"AirCon": 2,"Photo":3,"AudioSys": 4};
// depending on which element of the list I click, returns the position of the array where it has to store the result of the ajax call.
//For instance: when clicking on "Mobile", the ajax call should store the result in the index 0 of results, which we get by doing: array[Mobile]
function ajaxCall(electronic_type){
webServiceURL = 'http://.....';
soapMessage = '<?xml version="1.0"....' + electronic_type + '.</S:Envelope>';
var promise= $.ajax({
url: webServiceURL,
type: "POST",
dataType: "xml",
data: soapMessage,
processData: true,
contentType: "text/xml; charset=\"utf-8\"",
success: storeResult,
error: OnError
});
promises.push(promise);
function storeResult(text) {
results[array[electronic_type]]=response_from_server;
}
$.when.apply(null, promises).done(function(){
// print results array to check if everything is stored.
// do other stuff when all clicks have been processed
});
}
$(document).ready(function ()
if( request.getParameter("value") !== null){
String electronicType = request.getParameter("value");
ajaxCall(electronicType);
}
});
</script>
</head>
</body>
<ul>
<li><a href="electronics.jsp?value=Mobile">Mobile Phones</a></li>
<li><a href="electronics.jsp?value=TV">Television</a></li>
<li><a href="electronics.jsp?value=AirCon">Air Conditioners</a></li>
<li><a href="electronics.jsp?value=Photo">Photo & Optics</a></li>
<li><a href="electronics.jsp?value=AudioSys">Audio Systems</a></li>
</ul>
</body>
What happens is:
1st click on "Mobile": print of res[array[Mobile]] does have the result. 2nd clic on "TV": print of res[array[TV]] does have the result, but the previous one has disappeared.
Anyone knows what could be the issue? I've tried wrapping the ajaxCall() function in an anonymous function like said here but no luck.
Also: Ideally, the user should click in a link, wait for the ajax call to finish and show some info on the screen, and then is allowed to click in another link. Not sure if for this to happen I should set async: false, but either way it doesn't work since I have the same issue storing the results.
Many thanks.