Alpaus
Alpaus

Reputation: 646

Add html parameters for jquery ajax data

I'm using jquery to make ajax calls to a database which displays the returned records in a div. This works fine but I'm using a hack that breaks w3c validation in order to pass the parameter to the ajax call (i.e. The id to retrieve records from the database for)

My list of hyperlinks is generated in php by getting valid categories from the database and outputting hyperlinks with parameters such as 'blah.php?cat_id=6'. The hack is to just also have cat_id = x inside each of the tags (where x is the category id) which jquery then passes to the backend in the ajax call.

Is there a way to get this data to the ajax call without setting it inside the tag like I am? I can't use jquery to create the list if hyperlinks because I want it to fallback seamlessly when JS is disabled. The ids will not come out of the database sequentially so while the jquery data() function seems to be the way to go, I can't figure out how to get the category id to assign to each DOM element (without messy regex parsing on the url parameters from the string)

Thanks Aaron

Upvotes: 0

Views: 402

Answers (1)

SLaks
SLaks

Reputation: 888185

You should use HTML5 data-* attributes:

<a data-cat-id="6" href="...">

You can then read it using jQuery's data API:

$(this).data('cat-id')

Upvotes: 4

Related Questions