javascriptjqueryajax

JavaScript - send ajax request without string concatenation


I have a page in which the user will write a code (in a programming language). the code can be very long (more than 2000 characters) and can contain any type of characters. And when they press the send button the code will be sent (using JavaScript ajax) to a script file on the server etc.

currently I am using this to send the code with ajax:

jxobj.open('POST', 'www.my-website.com/my_script.php', true);
jxobj.send('code=' + code);

but if the code contains some characters like & then the value of code will be broken into many pieces and I can't retrieve it in my script file.

Is there any way to send ajax request without a string concatenation? I would like to use only JavaScript if possible and thanks.


Solution

  • The data format is well documented and the standard JavaScript encodeURIComponent function will encode data for it.

    jxobj.send('code=' + encodeURIComponent(code));
    

    Is there any way to send ajax request without a string concatenation?

    Not really. The send method takes a string, so you have to build a string using some mechanism or another. You could achieve it with (for instance) arrays and joins, but it still comes down to the same basic principles.