I'm writing a php script that takes some c code and tests it against a few test cases. But since the source code can have single and double quotes along with slashes, my script doesn't get the entire data when passed via a textarea. I'm posting using the .ajax method of jQuery
When I tried, here's what happens
$code_string = $_POST['code'];
echo $code_string;
the input is
int a,b;
scanf("%d%d",&a,&b);
printf("%d",a+b);
The jQuery code that posts the data is
$('#submitButton').click(
function(evt){
userCode = $('#answer').val();
$.ajax({
type : 'POST',
url : 'scripts/php/check_answer.php',
data : 'code=' + escape( userCode ),
dataType : 'text',
success : populateResponseToQuestion
});
evt.preventDefault;
});
and the output is
int a,b;
scanf("%d%d",&a,&b);
printf("%d",a b);
I want to be able to pass the data to php without anything being trimmed off. In this case the + symbol is lost. With more code, I realize more stuff would be lost or modified.
Your post data is preserved, but if you want it display correctly in HTML document you have to use <br>
for new lines, so function nl2br
will be helpful. You should also use htmlspecialchars
or mentioned earlier htmlentities
to avoid problems when posting code with <
character (it can be interpreted as opening HTML tag).
[+]
As for JavaScript part, you are doing it wrong. Either use encodeURIComponent()
instead of escape()
or pass object to the $.ajax
:
$.ajax({
type : 'POST',
url : 'scripts/php/check_answer.php',
data : { "code" : userCode },
dataType : 'text',
success : populateResponseToQuestion
});
This way jQuery will handle it for you.
htmlentities is what you're looking for.
<textarea><?php echo htmlentities($code, ENT_QUOTES, "UTF-8") ?></textarea>
You could try:
echo htmlentities($code_string);