escape html in jQuery for WordPress
I am a bit confused in properly escaping html and attributes while preparing HTML string in jQuery.
This is my current approach
$.ajax({
type: 'POST',
success:function(response){
var html = '';
if( response ){
$.each(response,function(key,value){
html += 'tr';
html += 'td';
html += 'input type=hidden name='+key+' value=tf_'+value+' /';
html += 'div class=tf-wrapper'+value+'/div';
html += '/td';
html += '/tr';
});
}
var table = $('#content_table');
table.find('tbody').append(html);
},
error: function(a, b, c){
alert('error');
}
});
The ajax callback in PHP would be
public function get_settings(){
$settings = get_option('pea_options', array());
wp_send_json( $settings );
}
Here the data appended via jQuery is not properly escaped. So I think I need to use some custom jQuery functions to escape the values here.
But I am thinking of something like below, say Case 2
jQuery Ajax call would be
$.ajax({
type: 'POST',
success:function(response){
if( response){
var table = $('#content_table');
table.find('tbody').append(response);
}
},
error: function(a, b, c){
alert('error');
}
});
Ajax call in PHP
public function get_settings(){
$settings = get_option('pea_options', array());
ob_start();
foreach ($settings as $key = $value) {
?
tr
td
input type=hidden name=?php echo esc_attr( $key ); ? value=tf_?php echo esc_attr($key); ?
div class=tf-wrapper?php esc_html( $value ); ?/div
/td
/tr
?php
}
return ob_get_clean();
}
The reason is WordPress plugin handbook contain coding standards which should be followed. For the jQuery part, I don't know what should be done to follow WordPress standards in this particular case. Does the case 2 look good or am I missing something here ?
Topic escaping jquery plugin-development Wordpress
Category Web