mercredi 6 mai 2015

Escape/Special Characters from user input to HTML5 data-attributes using URL Encode/Decode

This is my first question on stackoverflow - needing help from all you experts. Our web app allows the user to input escape/special characters. We are doing some testing for extreme cases. I'm able to pass the escape characters through ajax/json.

var test = JSON.stringify({
  typeName: $("#typeName").val(),
  invoiceType: 'NewTypeArea'
});
$.ajax({
  type: "POST",
  url: "BackEnd/WebService.php",
  data: {
    newInvoice: test
  },
  dataType: 'json'
});
<script src="http://ift.tt/1g1yFpr"></script>

My backend developer does their thing with escape/special characters. When I make another call I get the following JSON data

[{"propName":"Special '\"'\\","typeName":"type'\"\\"}]

This data returned is correct. For simplicity - I have only one object for this example - I take this data and put it into a dropdown list.

$.each(data, function(i, val) {
var output = '<option class="type" id="' + this.qfInvoiceNum + '" value="' + this.typeName + '">' + this.typeName +'</option>';
$('select#typeList').append(output);

});

It displays all the escape/special characters correctly. For instance: "type'\"\" displays as type'\"\

The user then selects one of the list items. I've tried capturing the typeName numerous ways with data-attributes, value, etc. Here is one example:

$( '.selectChange1').change(function() {
typeGrab = $('select option.type:selected').val();
pullArea();
});

But this is where the problem comes in. If they select a list item with special/escape characters the value from the console returns

"type'"

not

"type'\"\\"

So of course when I pass in the var typeGrab for the JSON/AJAX call it is wrong.

Is there a good solution on on how to get escape/special characters from a dropdown? Or maybe I'm going wrong with $.each when I loop through the data? Or, quite possibly, I'm missing something very simple. Any help or insight would be great.

Thank you.

Additional Info. The first solution does work. However, I didn't use this initially due to the fact that there are a couple of times where the displayed text is not what I want to grab - which is why I was trying data*-attributes.

For example:

$.each(data, function(i, val) {
var output = '<option id="' + this.qfInvoiceNum + '" class="type" data-index="' + this.typeName + '" >' + this.typeName +' | #' + this.qfInvoiceNum +'</option>';
$('select#typeList').append(output);
}); 

If I want the value of this.typeName with escape/special characters the provided solution does not work. I can't use data-attributes or the html option value.

However, after much research, I found a great solution for this problem if you are looking to pass in values to data-attributes that have escape/special characters. Please my answer below.

Aucun commentaire:

Enregistrer un commentaire