Reputation: 2845
I am calling getjson inside for loop. Currently my code prints all the items doesnt ommit the items that are not on sale!
This is the part that checks if the item is on sale or not:
$.getJSON('http://anyorigin.com/get?url=http://www.asite.com/itemtocheck.php='+ itemName + '/&callback=?', function(data){
var siteContents = data.contents;
var n=siteContents.search("This item is not on sale");
if(n=-1)
{
//alert("This item is on sale. n:"+n);
var siteContents2 = "This item is on sale:"+itemName;
document.getElementById("myDiv").innerHTML += siteContents2;
};
I dont know what is problem with this if statement it always comes true even if the item is not on sale! is there a way i put a delay between each call to getjson inside "for loop"(very short delay so getjson fetch data and have enough time to filter it)?
i am not sure but i think maybe "for loop" is calling getjson so fast not giving enough time for each item to be checked. i even tried doing like this:
setTimeout(GetJSONResult('pen'), 500);
but for some reason it didnt work! Could any one help fix my code so it filters out items that are not on sale ?Thanks
<script>
function GetJSONResult(itemName)
{
//alert("test:"+itemName);
$.getJSON('http://anyorigin.com/get?url=http://www.asite.com/itemtocheck.php='+ itemName + '/&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var n=siteContents.search("This item is not on sale");
document.write("value of n"+n);
if(n=-1)
{
//alert("This item is on sale. n:"+n);
var siteContents2 = "This item is on sale:"+itemName;
document.getElementById("myDiv").innerHTML += siteContents2;
};
});
};
items=["pen","paper","book","tshirt","cup","coffee","plate","cherry","apple","mango","orange"];
for (var i=0;i<items.length;i++)
{
document.write(items[i] + "<br>");
GetJSONResult(items[i]);
}
////setTimeout(GetJSONResult('pen'), 500);
////setTimeout(GetJSONResult('paper'), 500);
////setTimeout(GetJSONResult('book'), 500);
////setTimeout(GetJSONResult('tshirt'), 500);
////GetJSONResult('cup');
////GetJSONResult('coffee');
////GetJSONResult('plate');
////GetJSONResult('cherry');
////GetJSONResult('apple');
////GetJSONResult('mango');
////GetJSONResult('orange');
</script>
</head>
<body>
<br>
<div id="myDiv"></div>
<br>
</body>
</html>
Upvotes: 0
Views: 517
Reputation: 71
did you notice that in your if statement you are doing an assignment?
if(n=-1)
should probably be
if(n == -1)
or if you want to be REALLY safe
if(n === -1)
Upvotes: 1