Michael Michael - 3 months ago 5
Javascript Question

Updating an element via ajax: shall I use global variable to keep element's id or it is a bad habit?

On a page I have a list of dates which I want to edit via AJAX.

Example:

<li>January 2015<a data-update_url="/frame_date/22/update/" class="update" id="update_framedate_22" href="javascript:void(0)">Edit</a>


When the user clicks on the Edit link, I catch element id and the edit link.

Than AJAX requests the update form from the server. And now I have to place the form instead of the element with the mentioned id.

In other words, in frame_date_update_show_get I need element's id. In the example below, I keep it in the global variable date_id. But inside me there is a protest: I was always taught that global variables is a bad practice. But in this case I don't know how to get along without the global variable date_id.

Could you give me some piece of advice: is my code acceptable or there is a better way to cope with the problem.

function frame_date_update_show_get(data){
$("#" + date_id).replaceWith(data);
}

function frame_date_update_get_data(){
date_id = this.getAttribute('id')
var cuaghtUrl = this.getAttribute('data-update_url');

$.ajax({
method: 'get',
url: cuaghtUrl,
success: frame_date_update_show_get,
error: fail
});
}

var date_id = ""

Answer

Use an anonymous function as success callback function and then call frame_date_update_show_get with an additional date_id parameter:

function frame_date_update_show_get(data, date_id) {
  $("#" + date_id).replaceWith(data);
}

function frame_date_update_get_data() {
  var date_id = this.getAttribute('id')
  var cuaghtUrl = this.getAttribute('data-update_url');

  $.ajax({
    method: 'get',
    url: cuaghtUrl,
    success: function(data) {
      frame_date_update_show_get(data, date_id);
    },
    error: fail
  });
}