0

I have a javascript string which looks like this:

['Chris','Johannes','test','[email protected]','[email protected]','[email protected]','[email protected]'] 

I want to pass this to a php document as an array/object. What is the easiest (jQuery?) way to do this?

Edit: I grab this string from the DOM:

<div class="container" data-users="['Chris','Johannes','test','[email protected]','[email protected]','[email protected]','[email protected]']" data-userids="[1,2,3,12,13,15,16]">
1
  • 2
    Use a proper JSON string and JSON.parse Commented Aug 25, 2013 at 18:44

2 Answers 2

2

First, convert the data-users and data-userids into JSON (see http://www.php.net/manual/en/function.json-encode.php). That means the all quotes must be double quotes ("").

<div class="container" data-users='["Chris","Johannes","test","[email protected]","[email protected]","[email protected]","[email protected]"]' data-userids='[1,2,3,12,13,15,16]'>

Then you can get the data like this:

var dataUsers = JSON.parse($('div.container').attr('data-users'))
// dataUsers[0], dataUsers[1], dataUsers.length ....
var dataUserIds = JSON.parse($('div.container').attr('data-userids'))
Sign up to request clarification or add additional context in comments.

Comments

1

Use the jQuery data() function, which will automatically cast values to the correct javascript datatype, including arrays and objects:

var container = $('.container');
var users = container.data('users');
var userIds = container.data('userids');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.