views:

27

answers:

2
$('.showprayer').click( function(event) 
{
  $.post('/show_prayer', { 'name' : $(this).text() }, function(data) 
  {
      eval(data);
  });
});

The jQuery function above returns the following string as the ajax response coming back from the server:

'#prayer_date'.html("03/19/1968");

Someone seeing this code earlier responded that "returning javascript instead of JSON is a terrible way of using Ajax".

My problem is, I thought this was the only way of doing it.

So if someone could enlighten me . . . if I wanted to do the same thing by returning JSON, what would that look like and would it involve significantly more code than my current ajax response which very succinctly changes the value of the prayer_date element to its new date value?

+1  A: 

You should return just the json object like { "date": "03/19/1968" } and then rather than doing an eval, do $("#prayer_date").text(data.date); (or html as you show in your example. So, the bottom line is that the code being called ultimately is the same, but it's designed a bit better, and you aren't using eval.

rchern
+2  A: 

Just have the server return the date as a JSON object and reference the property in the client. Don't forget to let the AJAX function know what type of data is expected since you won't be returning the default (html).

$('.showprayer').click( function(event) 
{
  $.post('/show_prayer', { 'name' : $(this).text() }, function(data) 
  {
      $('#prayer_date').html(data.Date);
  },'json');
});

Server returns:

"{ 'Date' : '03/19/1968' }"
tvanfosson
Do you think the JSON approach is "better"?
Ken Hume
@Ken - In this case, I would actually just return HTML as you're just returning a simple string. JSON would be better if it were a complex object, but for a simple string you don't need it. To use HTML just return the date string (instead of JSON) and remove the datatype parameter (HTML is default). I definitely wouldn't return and execute javascript.
tvanfosson
@tvanfosson: Thanks for the followup. That makes sense.
Ken Hume