I have this URL format:
http://localhost/find_retailers/index.html?modelCode=ABCD1234
I have an XML file consisting of:
<products>
<product modelcode="ABCD1234">
<retailer id="1">
<name>Retailer One</name>
<logo>retailer_one.png</logo>
<url>http://www.retailer-one.com/ABCD1234</url>
</retailer>
</product>
<product modelcode="EFGH5678">
<retailer id="2">
<name>Retailer Two</name>
<logo>retailer_two.png</logo>
<url>http://www.retailer-two.com/EFGH5678</url>
</retailer>
</product>
etc.
And I have the following jquery:
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "xml/retailers_param.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('product').each(function(){
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var productUrl = getUrlVars()["modelCode"];
var modelcode = $(this).attr('modelcode');
if(modelcode == productUrl) {
$(this).find('retailer').each(function(){
var id = $(this).attr('id');
var name = $(this).find('name').text();
var logo = $(this).find('logo').text();
var url = $(this).find('url').text();
$('<div class="retailer" id="retailer_'+id+'"></div>').html('<h3>'+name+'</h3><p><img src="img/logo/'+logo+'" alt="'+name+'" class="logo"/></p><div class="btnVisit"><a href="'+url+'" class="btnStyle" target="_blank"><span>Visit Store</span></a></div>').appendTo('#retailers');
});
}
else {
$('<div class="noRetailer"></div>').html('<h3>No Retailers for:</h3></br>'+productUrl+'').appendTo('#retailers');
}
});
}
});
});
</script>
The problem is that it runs for every product node in the XML file. This means it displays the products but also the error message for every product node in the XML file.
I have tried including return(false); in the else statement but this does not work as it stops it progressing passed the first XML node.
Any ideas?
If I leave the else node empty or remove it then all is good but I really want to include a “No retailers for ‘modelcode'” type error for UX reasons.
You should move the error test outside
each, use a Boolean to test if a product was found or not.