2

I would like to build a tracking system for a Web-based Application built in CakePHP 2.x. The idea is to have all the tracked link having written as below:

<a 
 href="#" 
 class="track-click" 
 data-tracking='{ 
 "trackers": [
 {
 "tracker": "----", 
 "eventId": "---",
 "tracking_options": { 
 "eventTargetUrl": "---", 
 "props": [{ 
 "key": "----", 
 "value": "---" 
 }]
 } 
 } 
 ]
 }'
/>

The javascript that handles the track requests should be able to gather the information that resides inside the data-tracking attribute. This would be done by attaching a click event on the "track-click" class onClick event.

Below is how I use the link above:

$('.track-click').click(function(e){
 //Lets grab the data thats within the data-tracking attribute and do something with it
 var data = $(this).attr('data-tracking');
 alert(data.trackers);
 e.preventDefault();
});

At this present moment if I alert the above I get undefined. If I put $(this).attr('data-tracking').val() on my code I get the error below:

TypeError: $(...).attr(...).val is not a function

What is the best way of manipulating links that have a json data as shown above?

Miaonster
1,5222 gold badges18 silver badges34 bronze badges
asked Apr 20, 2015 at 10:20
2
  • 1
    Did you try closing in HTML the last attribute (data-tracking) with single quote, ' ? It seems not to be closed. Commented Apr 20, 2015 at 10:23
  • Close your a tag and put single quote at the end of this string. Commented Apr 20, 2015 at 10:24

1 Answer 1

5

You need to use

var data = JSON.parse($(this).attr('data-tracking'));

This will return you the object.

Else you must use

 var data = $(this).data('tracking');

.data() will return you the object. whereas .attr() will stringify and return that object.

DEMO

answered Apr 20, 2015 at 10:24
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks dude this is exactly what I wanted. I could see [object Object] being alerted i my browser which is a good sign.... :-)
Great. you can console.log and see the entire object in console :)
Yes, I wqas able to see the whole data rather than the [object Object] notation with the alert. Thanks a lot. I am now trying to build the implementation for my custom tracking... :-)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.