Best practice with jQuery and AJAX calls

I have a question about best practices when using jQuery / JavaScript / Ajax. Suppose I have some tasks, and there is a calendar for each task. The user can click on a day in the task calendar and book a task on a specific day through AJAX. I have to store the date and task id somewhere, and I use really weird identifiers for such as:

<span class="day_field" id="date_13-02-2013_task_4">13.02.2013</span> 

Then I just attach the listener as follows:

 $('.day_field').on('click',function(){ var date = $(this).id.split('_')[1]; var task_id = $(this).id.split('_')[3]; //place for some validation $.post('book_task.php',{task_id: task_id, date: date},function(data){ //something cool with the result }); }); 

My question is: Is this right, how to do it? I'm not sure, because identifiers can be really long + it contains an identifier in the database, which is probably not stored at all.

Thanks! T.

+6
source share
5 answers

Use HTML5 data attributes:

 <span class="day_field" data-date="13-02-2013" data-task="4">13.02.2013</span> $('.day_field').on('click',function(){ var date = $(this).data("date"); var task_id = $(this).data("task"); //place for some validation $.post('book_task.php',{task_id: task_id, date: date},function(data){ //something cool with the result }); }); 
+8
source

The correct way. The best way to do this is to save the data in the data attributes or to make the span an anchor tag and save the parameter string required in the href attribute.

 <span class="day_field" data-date="13-02-2013" data-task="4>13.02.2013</span> or <a class="day-field" href="?task_id=4&date=13-02-2013">13.02.2013</a> 

with this for the anchor tag:

 $('.day_field').on('click',function(e){ e.preventDefault(); $.post("foo.php",this.href,handler); }); 
+2
source

Instead of an identifier, you can use custom data attributes , for example:

 <span class="day_field" data-date="date_13-02-2013_task_4">13.02.2013</span> 

And then you can access this value in jQuery:

 $(".day_field").data("date"); 
+1
source

Providing the actual identifier of something in your database is not as secure as your database.

Using the id element for an element seems fine to me if it uniquely identifies a thing. Using data attributes is an opportunity to save on separation logic if you want, but you can still use id in tandem.

Traditionally, this is very manual code compared to what jQuery has.

0
source

Another elegant way to associate data with an element is to use jQuery data . However, I would consider creating a jQuery plugin and using one instance for each task. The plugin encapsulates all the data it needs, so you will not need to bind them to the element, which is not very convenient.

0
source

All Articles