views:

22

answers:

1

The jQuery function below returns this string:

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

But it doesn't get executed because the function below doesn't act on the data variable.

What would you need to do to have the result above executed as-is in the function below?

$('.showprayer').click( function(event) 
{
  $.post('/show_prayer', { 'name' : $(this).text() }, function(data) 
  {
      // how to execute the `data` server response as-is?
  });
});
+1  A: 

Your response would need to be valid script first, like this:

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

Then in your function you can call eval(), like this:

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

....but this is almost never a good solution, there's probably a better/more direct route to do what you're after. A slightly better/safer solution is to use the expanded $.ajax() form for a global eval, like this:

$('.showprayer').click( function(event) {
  $.ajax({
    url: '/show_prayer',
    type: 'POST',
    data { 'name' : $(this).text() }, 
    dataType: 'script'
  });
});

The difference is that this uses jQuery.globalEval() which sticks the script in the <head> as if it were a normal GET requested <script>, instead of actually calling eval() on it.

Nick Craver