Reputation:
The is a button on whose click certain task is performed through ajax. through ajax i get a result in json format that looks like this in console
["25", 16, "ABC", "DEF", 1]
Now i want that whenever there is 1
in 4th position i wish to hide few buttons. the code that i wrote is
$.ajax({
type: 'post',
url: 'script.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
if(returndata[4]=='1')
{
$("#first").hide();
$("#second").hide();
$("#third").hide();
}
},
error: function() {
console.error('Failed to process ajax !');
}
});
the if condition seems to work because i tried to put an alert box within the if condition and it worked, however the buttons are still getting displayed.
the code i tried for test with alert box is
if (returndata[4] == 1)
{
alert("1");
}
Can anyone please tell why is this happening
Upvotes: 6
Views: 1237
Reputation: 20132
In comments I see thatYou have posted ajax result which is:
["25", 16, "ABC", "DEF", 1]
Your problem is comparission which is ==="1"( I saw that type of comparison in question when I started writing this answer ) and You have 1 as number not "1" as string, === means type comparission, so in correct way it gives false because 1 is numbet and "1" is string. You can fix this by changing condition to:
returndata[4]===1
or without type check:
returndata[4]==1
That's it.
To more understand this answer I have prepared few examples.
console.log("1 === '1'");
console.log(1==='1');
console.log("1 === 1");
console.log(1===1);
console.log("1 == '1' ( no type comarision )");
console.log(1=='1');
Upvotes: 0
Reputation: 1
try follow changes in your ajax method...
no need to use dataType:'json'
$.ajax({
type: 'GET',
url: 'script.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
if(returndata[4]=='1')
{
$("#first").hide();
$("#second").hide();
$("#third").hide();
}
},
error: function() {
console.error('Failed to process ajax !');
}
});
regards prem
Upvotes: 0
Reputation: 1
You have matched one '1' as a string
in your hide section, but in the alert section matched one 1 as number
. This may be the problem.
Avoid this
if(returndata[4]=='1')
Use this
if(returndata[4] == 1)
Upvotes: 0
Reputation: 167182
I know this is what you have done. I am in a challenge to solve your issue. Let's do one by one. First attempt, try this instead of your code:
$.post("script.php", {txt: txtbox, hidden: hiddenTxt}, function (res) {
alert("Response: " + res);
alert("Type: " + typeof res);
});
Please let me know your results in the comments. Cheers.
Upvotes: 1