0

In my laravel 4 project users can submit textarea data. I know I can escape user data with {{{ }}} in my views, But what should i do if i get the data with ajax ? It is a jquery variable i cant escape it with the brackets. For example if I handle response from ajax like :

$.each(response, function( key, value ) 
{
    $('#div').append('<div>'+value.notEscapedData+'<div>')
});

And the controller where the data comes from is for example.

$response = Data::all()
return $response;
Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • You want HTML Escape. Check [this thread](http://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery) for great answers. – UltraInstinct Dec 24 '14 at 11:07

1 Answers1

2

You can either do it with javascript (and you will find plenty solutions on the internet. e.g. the link @Thrustmaster posted in the comments) or you can do it in Laravel.

When you use Blades triple curly braces {{{ }}} it compiles to a call to e() (which then calls htmlentities)

So you can use e('string-containing-html') to escape the string.

You could use a model attribute accessor for the escaping but I suppose you will need the string unescaped sometimes so here are a two other options:

toArray()

Override the toArray() method in your model

public function toArray(){
    $array = parent::toArray();
    $array['attribute_name'] = e($array['attribute_name']);
    return $array;
}

This way every time the model gets converted into an array (which is used for converting it into JSON=, the property will be escaped.

Loop over it in your controller

$data = Data::all();
$data->each(function($d){
    $d->attribute_name = e($d->attribute_name);
});
return Response::json($data);
Community
  • 1
  • 1
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270