-3

I'm building a website and I have some data within php variables. I'm trying to use that data for jQuery engine for Java enabled browsers.

I came across the problem with using php variables within jQuery script:

Here's the code I can't get to work.

//PHP array:

$filters['ab']='text a';
$filters['cd']='text b';

// jQuery script:

// Key I want to find in array
var test = "ab";

// Reading php array into JSON
filters = $.parseJSON('<?php echo json_encode($filters); ?>');

// Trying to use JSON data to create Array using original keys and values
var filtersArray = new Array();
$.each(filters, function(key) {
    filtersArray[key] = $(filters).attr(key);
});  
alert(filtersArray['ab']); returns "text a";  // Seems to be working

// Trying to find the test variable value
filterIndex = $.inArray(test, filtersArray) // Not found

Sorry for previous careless version of post. I though shorter will be better, but in fact it came out completely useless.

Thanks

hakre
  • 193,403
  • 52
  • 435
  • 836
zee
  • 359
  • 3
  • 16
  • 4
    fist of all arr is not an array. its an object. try printing $.type(arr) and you'll understand what i am talking about – Raghu Sep 03 '13 at 23:24
  • 2
    did you read the docs? http://api.jquery.com/jQuery.inArray/ – hdgarrood Sep 03 '13 at 23:25
  • Thanks for all the comments, I get the "arr" var this way: arr = ; Is there any way to find the index of "d" within "arr" for example? – zee Sep 03 '13 at 23:51
  • possible duplicate of [Javascript object get key by value](http://stackoverflow.com/questions/9907419/javascript-object-get-key-by-value) – Phil Sep 04 '13 at 00:38

2 Answers2

2

I think you need something like this

function inObject(obj, val) {
    return Object.keys(obj).filter(function(key) {
        return obj[key] === val;
    }).length > 0;
}

jsFiddle demo here - http://jsfiddle.net/VZ5A9/

See the following pages for browser compatibility as well as shims for adding support

Update

If you need to find the key, try this one (this is also more compatible with older browsers)

function findFirstKeyByValue(obj, val) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key) && obj[key] === val) {
            return key;
        }
    }
    return null;
}

Demo - http://jsfiddle.net/VZ5A9/1/

Phil
  • 157,677
  • 23
  • 242
  • 245
1

The reason this isn't working is because the variable you named arr isn't an array, it's an object literal. To get this code to work try this (FIDDLE):

arr = ["b","d","f"];
uri = "d";

alert(jQuery.inArray(uri, arr));
Tom
  • 4,422
  • 3
  • 24
  • 36