coffeemonitor
coffeemonitor

Reputation: 13120

JQuery - eval Html to Element

On some of my PHP pages I like to load data from another place, and populate an input or textarea.

I run into problems when there's html tags involved. (apostrophes too) I notice in FF that the html simply isn't too good at being passed around with javascript in general. (error console)

So I'm looking for help in how to HONE this, if possible.

Main Page:

<textarea name="templatetext" id="templatetext"></textarea>

<script language="javascript" type="text/javascript">
$(document).ready(function(){

   /* calls page2.php */
   $.ajax({data:"formId=loadtemplatetext",
        success:function(response){ 
                                    eval(response); 
                                  } 
       });
        return false;
   });

});
</script>

Page2.php

<?php
$templatetext = '<p>This is a test email<br /><br /><br /></p>
<p><span style="color: #808080; font-size: 12px; font-family: Tahoma,sans-serif;"><strong>Some Text here with an apostophe or image: <br /><img title="Test Img" src="http://somefakeurl.com/img/somefakeimg.gif" alt="test img" width="112" height="59" />';

die('$("#templatetext").val("'.addslashes($templatetext).'");');
?>

This works great with regular/plain text. Am I able to clean this up for populating the value inside a <textarea>?

Upvotes: 1

Views: 1597

Answers (1)

Brad Christie
Brad Christie

Reputation: 101604

I would recommend changing how you perform this. Either within the client code know where the new content is going, or make an object that makes parsing it client-side easier. e.g.

Version one: Server-specific handling (and client-side processing)

<?php

  $result = array();
  $result['template'] = '<p>this is a test email<br/ >...';
  $result['target'] = '#templatetext';

  echo json_encode($result);

Then your AJAX code becomes:

$.ajax({
  data:'formId=loadtemplatetext',
  success: function(d){
    $(d.target).html(d.template);
  }
});

Version two: Server processing, client handling

<?php

  echo '<p>This is a test email<br />...';

Then your AJAX becomes:

$('#template').load('/page.php?formId=loadtemplatetext');

Resist using eval as all costs. This can lead to a lot of security threats.

Upvotes: 4

Related Questions