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);
Related
I have a search field where users paste URLs (url is the search query). Most urls work fine, but urls with escaped characters are getting 'unescaped'. For example :
When I copy some url from Chrome browser I get escaped url:
url = input query : 'http://website.com/search/my%20query'
echo $_POST['q'] ~ result is 'http://website.com/search/my query'
The query is submitted by $.ajax :
var qurl = $("#url input[name=q]").val();
var queryString = "q="+qurl;
$.ajax({
url : "script.php",
type: "POST",
data: queryString,
.....
How can I receive the query with the escaped characters ?
Should I bother and process(escape the query of my query) the query url myself?
Magic quotes you are off:
php.ini
magic_quotes_gpc=Off
magic_quotes_runtime=Off
magic_quotes_sybase=Off
Your question is a bit short on detail so, unfortunately, there is a fair bit of speculation in this answer:
The % in %20 should be encoded as %25 (giving %2520) when the data is submitted.
PHP will then decode it to give you %20 in $_POST.
I've never heard of PHP double decoding the data before. So it sounds like the problem is that whatever is making the request is failing to encode the data. This is most likely caused by not using a regular form to submit it and using JavaScript instead.
The solution therefore, is to encode it properly in the JavaScript.
For example:
data = "query=" + encodeURIComponent( document.getElementById('myInput').value );
Update in response to JavaScript being added to the question:
var qurl = $("#url input[name=q]").val();
var queryString = "q="+qurl;
My earlier speculation is confirmed. You haven't encoded the data into the correct format for a query string. Since you are using jQuery.ajax, you can use that to handle your encoding (by passing it an object of data) instead of building the query string manually (and then passing a string):
$.ajax({
url : "script.php",
type: "POST",
data: {
q: $("#url input[name=q]").val()
},
I'm trying to create an ajax search page, which shows live results similar to google.
Right now I am struggling with how to convert a search query such as small dog to a GET parameter, in this case it would be "searchresults?search=small+dog". The thing I want is to replace all white space between words to + and to remove whitespaces before and after words.
I think it's possible with regex, or is there some javascript or jquery function to encode that?
I tried using escape, encodeURI, ... , but it made whitespace %20. Will PHP understand that they are multiple words?
To manually escape a query component in Javascript, simply use encodeURIComponent:
var url = '/searchresults?seach=' + encodeURIComponent(query);
To trim the query string before, use .trim() on the string.
Probably also useful: What every web developer must know about URL encoding
$.get("searchresults", {search : query}, function(data){
// do something
});
it'll add '+' automatically, on the php side, you can simply call urldecode($str);
Instead of putting it in the URL which causes all sorts of escaping issues you should just POST and send data to your search file like this:
Your AJAX
$.ajax({
url: 'search.php'
,async: true
,cache: false
,type: 'POST' // <-- method of sending to server
,data: {
'search': ' small dog '; // notice white space before and after
}
,dataType: 'json' // server returns info in this format
,success: function(data){
// do something here with return data
console.log(data);
}
});
search.php
echo trim($_POST['search']); // gives you 'small dog'
I have a window on my site where the visitors can change them password.
The problem is that the & character is never taken :
If I put those two new passwords :
stack&
stack& (the second is the confirmation)
The insertion in the BD is stack (without the &).
This is the js code :
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
the alert shwos me "stack&"
In PHP, a var_dump of $_POST gives me :
stack (without the &).
Is & a reserved word for jquery ?
This is my js code :
$.ajax({
type: 'POST',
url: 'modification_mdp.php',
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
dataType: 'text',
success: function(reponse) {
reponse = $.trim(reponse);
Have you an idea to reselove this problem please ?
Thanks in advance.
Encode the field value
data: 'nouveau_mdp=' + encodeURI($('input#champ_nouveau_mdp').val()),
by this way & is encoded with the ascii number.
Try passing an associative array, which jQuery will encode for you:
data: { nouveau_mdp: $('input#champ_nouveau_mdp').val() }
You'll need to change the PHP code that receives this value to match (it gets an array rather than a string).
The ampersand character is not allowed to pass by Get method or by Post method in PHP. As the usual syntax to access the PHP by GET method is ines.php?user=username&password=mypassword,
the '&' character separates the two Variables.
That is why it is does not take '&' from 'Stack&' You may use Javascript to Validate if & is not entered in the text Box. Use JavaScript to encode the varaible... No decoding is required at the PHP end
encodeURIComponent("stack&")
This line is the problem:
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
The & character has a special meaning in HTTP. If you had multiple parameters they would be separated by & e.g. nouveau_mdp=mynewpassword&old_mdp=myoldpassword
What you need to do is encode characters such as &, = etc as their hex equivalents i.e. %26 and %3D respectively.
In JavaScript you can do this with the encodeURI() function.
Though, as mentioned in the other answer, jQuery also allows you to pass a JSON dictionary of parameters, and it will do the encoding for you.
I have a problem with my jQuery script that send data via POST method. The problem is whenever it sends data via Ajax that has an "&" ampersand in the sentence, it will cut the sentence when found "&".
Please check the images below for more info.
htmlentites
This function is identical to htmlspecialchars() in all ways, except with htmlentites(), all characters which have HTML character entity equivalents are translated into these entities.
If you're wanting to decode instead (the reverse) you can use html_entity_decode().
Example:
echo htmlentities("&"); // &
if your directly doing this in the browser you should be able to use:
encodeURIComponent(string input);
Example:
encodeURIComponent($.trim($("input[name=t-tim_rendered-"+id+"]").val().toString()));
I've been having a huge problem exactly with this situation.
This is just to say that the last answer from Andrew Koester is the perfect answer I was looking for.
In case you are passing multiple form entries from a jQuery form to PHP through the .ajax() call like this:
data: "name=" + name + "&message=" + message + ...
DON'T USE THIS METHOD, it will block the ampersand(&) character from being written by the user on any of the input fields of your form.
Use this one instead as suggested by Andrew:
data: {"name": name, "email": email, "subject": subject, "comments": comments},
This way the user can write any kind of special character whithout worrying a about conflicting with the ajax declaration.
You can use a native javascript escape() function
In line 74
data: : "&task_d=" + escape(task_d) + ""
Alternatively, you could enclose your query string values in quotes
data: : "&task_d='" + task_d + "'"
If you pass your data parameter as a Javascript object, it will convert the characters for you (and IMO make the code look neater). So you should change your $.ajax call to the following:
data: {"user_id": user_id, "time_r": time_r, "task_d": task_d, "p_id": p_id, "df": finished},
You could use 'encodeURIComponent' to accomplish the URL encoding for that component. I used this and validated with browsers IE, Firefox, and Chrome.
I'm building a CMS for a client (Building on top of wordpress). I'm having an issue with some data I am returning from my database.
Basically I am building Javascript Objects from PHP data so that I can update certain areas of my site upon mouse click.
example (this would work fine):
<script language = "Javascript>
var myObject = new Object();
function updateDiv(id)
{
myObject.name = '<?php echo $valueName ?>'; // $varHeadline = "Bob"
myObject.headline = '<?php echo $value_headline ?>'; // $varHeadline = "My Story"
var div = document.getElementById(id).innerHTML = myObject.name +
'<br>' + myObject.headline';
}
</script>
The problem comes up when the data I bring back from my database already has some html, or line breaks in it.
Example:
echo $varHeadline;
// returns <h1>This is my headline</h1>
// This is part of the value too.
So if I create a Javascript Object with that data:
function updateDiv(id)
{
myObject.headline = '<?php echo $varHeadline; ?>';
var div = document.getElementById(id).innerHTML = myObject.headline;
}
I get errors in my Javascript.
I would like to continue populating my divs with Javascript Object data, but am unable to on account of some of the data containing HTML (or even single or double quotes for that matter).
I DO want to retain my HTML formatting (the <h1> tags and so forth) so using htmlspecialchars or strip_tags is out of the question. Is there any die hard way of storing returned HTML without killing Javascript?
Thanks in advance.
-J
json_encode() the string and take away the quotes:
myObject.headline = <?php echo json_encode($varHeadline;) ?>;
Of course, you could rewrite this as:
<script language = "Javascript>
var myObject = <?php echo json_encode(array('name'=>$valueName,'headline'=>$value_headline)); ?>;
function updateDiv(id)
{
var div = document.getElementById(id).innerHTML = myObject.name +
'<br>' + myObject.headline';
}
</script>
edit: as noted in the comments below, always make sure you can trust the HTML you're placing on the page. If $valueName or $value_headline is coming from user input, this is a bad idea if you don't validate the HTML in some other fashion, you're open to XSS attacks and the like: http://en.wikipedia.org/wiki/Cross-site_scripting
When you "quote" server-side values being dropped into a page, the quoting has to be different when the context is Javascript code and not HTML. For HTML, of course, you do things like turn ampersands into "&" and less-than symbols into "<", and so on. Well inside Javascript strings, less-than and ampersand aren't a problem - they might be later if you're going to stuff the string into HTML, but right there at the time the Javascript parser is reading the string, there's no problem. What is a problem are quotes and characters outside the good ol' 7-bit ASCII range. (That's a generalization, but you see what I mean.)
I don't know PHP but it seems like there has to be some way to tell it NOT to perform the quoting appropriate for HTML/XML, and to instead do something to protect the characters that are special inside Javascript string constants.