-3

I am creating one form dynamically and submitting it like the below code where data is a js object.

var inputStr = '';
if (typeof data != undefined) {
  for (var prop in data) {
    if (data.hasOwnProperty(prop)) {
       inputStr += "<input type='text' name='" + prop + "' value='" + data[prop] + "' />";
    }
  }
}
var form = $('<form style="display:none;" action="/someurl.do" method="post">' + inputStr + '</form>');
$('body').append(form);
$(form).attr('target', '_blank');
$(form).submit();

Now I am having trouble with special characters. if any property of the data contains any special character its getting converted to some junk characters. Any pointers on how to solve this issue.

Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70

2 Answers2

1

The problem is that you are creating the elements manually by concatenating strings. You can create elements dynamically by passing a closed tag to the jQuery object. For example, if you want to create a new <input/> element, simple do:

var input = $('<input/>');

If you need to specify the attributes/properties of that element, pass in an object as the second argument like so:

var input = $('<input/>',{
    name : 'theName',
    value : 'theValue'
});

Values passed in this manner will be escaped correctly (special characters will be parsed). You could also do it like this:

var input = $('<input/>',{
    name : 'theName'
}).val('theValue');

I refactored your code accordingly:

http://jsfiddle.net/vdxnn/1/

//Sample data
var data = {
    field1 : 'Q@#*&^$@$)@^#$',
    field2 : 'value2',
};

//Create the form
var form = $('<form/>',{
    target: 'blank',
    action: '/someurl.do',
    method: 'post'
    //NOTE: `style : 'display:none'` isn't necessary;
    //      just use the hide() method
});

//Loop through data object
if (typeof data !== 'undefined') {
  for (var prop in data) {
      //Create a new <input/> element
      var input = $('<input/>',{
          type:'text',
          name: prop,
          value: data[prop]
      });
      //Append it to the form
      form.append(input);
  }
}

//Hide the form
form.hide()

//Append the form to the body
$('body').append(form);

//Submit the form
$(form).submit();
Aaron Blenkush
  • 3,034
  • 2
  • 28
  • 54
0
  • What are the special characters?
  • Where did data come from?
  • What is data's value?

Lesson of the day: Instead of if (typeof data != undefined)... you can do if (data)...

  • data is a js object which contain values from textarea. I am having trouble with the presence of ISO 8859-1 symbol entities like § £ in textarea value. – Hector Barbossa Mar 12 '13 at 18:17
  • 1
    `if (data)` is *not* a substitute for `if (typeof data != undefined)` – Brad M Mar 12 '13 at 18:19
  • Thanks for pointing about if (typeof data != undefined). This is wrong for one more reason that typeof returns a string ... :) – Hector Barbossa Mar 12 '13 at 18:20