$.inArray issues with passing string from php script
I'm having a problem with the inArray function not sure why. I'm passing a string back to the Javascript from my PHP it looks something like this 22,24 ect. I've tried using the split com开发者_开发问答mand to convert it to a Javascript array and I've tried it just as is. Either way the inArray function isn't finding 22, I've tried 22 with and without speak marks in the inArray function.
$.ajax({
url: "<?=base_url(); ?>/products/update_dropdown/"+<?=$product['product_id']?>+"/"+strUser,
type: 'GET',
success: function(msg) {
var test;
test = $.inArray(22, msg);
alert(test);
}
});
Thank you for any help this is really driving me nuts!
So from your comments it looks like the problem is that there is whitespace before the number 22 in your string ([" 22", "24"]
).
You can run:
msg = msg.replace(/\s/g, '').split(',');
test = $.inArray('22', msg);
See http://jsfiddle.net/KAdRD/ for a worked example.
var test = "22,24,25";
test = test.split(",")
test = $.inArray(22+'', test); // explicitly convert search to string.
alert(test); // alerts index of found element.
http://jsfiddle.net/s3X8V/1/
I tried this out, this would return 1 for a match, -1 for no match:
var string = "33,34,35";
var test = $.inArray("34",string.split(","));
alert(test);
I'm guessing your return type may not be a string? Like the comment said try logging the variable or maybe the typeof
What about using indexOf function? If the variable set from PHP to JS is a string, you can use it this way:
if(msg.indexof('22', 0) != -1) {
// this is the case when 22 is a part of msg...
} else {
// this is the case when 22 is not present in msg...
}
Or is there any need of array from msg? Then I advise use of pure JS split() function:
test = msg.split(".");
Then You can call $.inArray()
.
Obviously the value returned from php isn't an array in javascript. Its returned as a string.
$.ajax({
url: "<?=base_url(); ?>/products/update_dropdown/"+<?=$product['product_id']?>+"/"+strUser,
type: 'GET',
success: function(msg) {
var test;
test = msg.search(/22/i)
alert(test);
}
});
Or something like that
If you dont want to search string values you must split the msg string to an array and search the newly formed array instead.
精彩评论