Javascript: How to not directly post a variable - javascript

I am in need of help again, this time with a little Javascript snippet. There's also a little bit of PHP involved. The PHP is as follows (to generate random numbers)
$no1 = rand(0,9);
$no2 = rand(0,9);
$no3 = $no1+$no2;
I'm using this as a captcha method, for a very simple contact form. I'm not a fan of the bulky methods that I find all over google searches.
To validate this code, I use the following Javascript
if(document.forms["feedback"].check.value !== "<?php echo $no3; ?>"){
window.alert("Incorrect security code");
return false;
}
Then inside my form, I just use this:
<?php echo $no1; ?> + <?php echo $no2; ?> = <input name="check" type="text" id="check" size="3">
It all works as it's supposed to, but if there was a way for me to not to just directly echo $no3 in my javascript here:
if(document.forms["feedback"].check.value !== "<?php echo $no3; ?>")
Then that would eliminate any way of viewing the source to find the answer. I'm very much aware that it's a simple math problem, and if anyone knows how to view source, they most definitely can add, but a colleague of mine pretty much insisted on this.
So, does anyone know a way to help me out? I pretty much wrote most of this by hand, including the javascript, so please be nice when telling me that my code is horrible and out dated..
Thanks!

Put the $no1 and $no2 variables inside of span tags (or anything else you can directly target with Javascript) and then get the values from those spans with JS and use that to calculate the sum in JS rather than echoing it into the source with PHP, e.g. give the spans IDs like #captcha-1 and #captcha-2 use getElementByID to retrieve the values, then do the validation entirely in Javascript.
It will still be easy for anyone with a brain to figure out how to bypass but at least the answer will not be present anywhere in the source code other than as a JS variable.
If you want to hide the validation process entirely, you will need to use JS and AJAX to send the sum input by the user to a serverside PHP function which checks to see if it is equal to $no1 + $no2 and then submit the form as part of the response success function.
All that being said, this is still a very weak spam deterrent method.

Related

Hidden input field not being updated properly

I am trying to get the referrer and update the referrer so that my users can go back to the page they came back from. I have a hidden input field which holds the value of the redirect. I have a static value in there just in case the referrer is empty. If the referrer is not empty, I want to update the value of it. Here is the code I have written, I even tested it and it said it was updated, however, I am not being redirected properly, so it is not working.
JavaScript and HTML I have written (keep in mind, I have correctly linked the file and such):
$(document).ready(function(){
if (document.referrer != "") {
document.getElementsByName("redirect").value = document.referrer;
var test = "false";
if (document.getElementsByName("redirect").value == document.referrer){
test = "true";
}
alert(test);
}
});
<script src="js/referrer.js"></script>
<input type="hidden" name="redirect" value="https://www.google.com" />
I feel like this is a minor error or there might be some sort of standard I am not following.
Thanks for the help! I appreciate any insight!
I can't see what the problem is off hand by what you've given me. But what I can say is that if you are going to use JQuery in one place (document ready function) then you should also use it to grab the value of your input field.
It would also help if you put an Id on the input field instead of doing it by name. Ids are the best way to get a specific element. That could be your problem too.
Then call it using:
$("#ID").val()
so your code would become:
if($("#ID").val() === document.referrer)
I would also suggest using triple equals as well. But that is completely up to you.
I've never done anything with document.referrer, but there might be a better way of doing that as well.
One odd thing is that you are setting these 2 things equal to each other
document.getElementsByName("redirect").value = document.referrer;
and then immediately testing if they're equal to each other.
if (document.getElementsByName("redirect").value == document.referrer)
I can't say that this is your issue, but it's bad coding and should be fixed.
I think a single letter is tripping you up here.
if (document.getElement**s**ByName("redirect").value == document.referrer){
There's no singular equivalent for 'byName', so you do end up with an array (or at least, an array-like object). Unlike IDs, it is allowable for multiple inputs to have the same name. The easiest solution is this:
if (document.getElementsByName("redirect")[0].value == document.referrer){
Doing document.getElementsByName will return an object array that DOES NOT include the value. There is no way to change the value (That I know of and have tried) when using the getElementsByName. I have solved this issue by using getElementById, it actually works properly for me.

How to obfuscate JavaScript on the server side?

I have a script I want to obfuscate or encrypt to hide from competition viewing the source code. I have found simple JS obfuscators but the issue with my script is I have PHP echoing variables into the JavaScript. The PHP is echoing strings and true/false.
Here is a piece of the JavaScript with PHP in it.
function redirect() {
var r = <?php echo $rvar; ?>;
if (r) {
window.location = prepare("<?php echo $redirect; ?>");
}
}
Can someone tell me what I can do to hide my JavaScript but be able to dynamically build the JS with PHP?
The only time I have ever wanted to obfuscate code is when I have been utterly ashamed of it. Retrospectively, I would probably obfuscate everything I have ever written. If protecting source is integral to your well-being, consider a shift to desktop programming.
Nevertheless, if there is one thing experience and memory has afforded me, it is that any serious newcomer to this field will stubbornly move forward with their own ideas, regardless of how bad it is, how much it grinds against commonsense and best practice, or how much a thread poo-poos all over the question. If you keep at it, hindsight will generously remind you of this period--cringes and all; the chastisements of a few strangers will pale in comparison, so I will give you one possible answer.
Use PHP's output buffering controls. You will want to start output buffering at the top of the script that will output all the JavaScript. This will capture everything into the buffer, which can then be assigned to a simple variable. This variable will contain everything that was supposed to be echoed out to the page immediately, but was instead captured and saved into the variable. This variable is just a regular string. Pass it to one of those JS obfuscators you found. This assumes it is done with PHP and is a PHP library for doing that. When it is obfuscated, echo it out. That is it. Here is an example:
<?php
// Start output buffering.
ob_start();
?>
function redirect() {
var r = <?php echo $rvar; ?>;
if (r) {
window.location = prepare("<?php echo $redirect; ?>");
}
}
<?php
// Get all the output captured in the buffer, and turn off output buffering.
// This will be a string.
$js_source = ob_get_flush();
// Obfuscate the $js_source string, by passing it to the obfuscator
// library you found.
$obfuscated_js_source = obfuscator5000($js_source);
// Send the source code to the browser by echoing it out.
echo $obfuscated_js_source;

Dealing with JSON in HTML forms

I'm asking this because I'm using a trick that works but I think my be problematic in the future.
I generate a html form in php using SimpleXML and DOM to manage the source (a html file with all forms needed). So I got my form and got to fill some properties. Here is an example:
<input type="hidden" name="arquivo_tipos" value="{arquivo_tipos}" />
{arquivos_tipos} is a JSON string, won't work inside double-quotes. However, if I create the source code like this:
<input type="hidden" name="arquivo_tipos" value='{arquivo_tipos}' />
After being processed by php, it will return to double-quotes (I pick the form from a lot as a xml node). So my solution is replacing the property with this kind of script:
html = html.replace('"{arquivo_tipos}"', '\'[{"ext":"jpg","nome":"Imagem JPEG"},{"ext":"jpeg","nome":"Imagem JPEG"},{"ext":"gif","nome":"Bitmap GIF"},{"ext":"png","nome":"Imagem PNG"}]\'');
This is JavaScript, but in php I use the same trick with str_replace.
The point is, this is the final code, so it works, but smells like it will fails in the future if another process take this result. Is there a better way, a right way of doing this?
Use php htmlspecialchars function, it can escape
double-quotes to "
single-quotes to '
http://tw1.php.net/htmlspecialchars

Check for correct answer (quiz) using PHP and AJAX

I have a picture quiz with a single input field for each image. I need a way to check if the value entered into the input field matches the correct answer and if it does, perform a few operations like add/remove a few CSS classes and increase the score count. And I need this to be done in real time using AJAX.
This is the pseudo-code for the functionality that I want...
if input value == correct answer {
some jQuery to add/remove a few classes
some PHP (I assume) to add 1 to the score count
} else {
some jQuery to add/remove a few classes
}
However, how do I get the value of the input field in real time? Do I still use PHP Post to get the value? What AJAX do I need to do this without a page refresh?
Any help would be greatly appreciated... I'm okay with PHP but very little experience with AJAX. Thank you.
yes this can be done with AJAX, and with jquery (which is not the same).
You can get input string with $("#input_id").val() , show a simple error message with alert("my message"), and use the onchange event. see also what is e.preventDefault() to make the form not submitable if all is not correct
If you want to check if datas are correct with a php request, that's also possible with $.ajax()
See jquery documentation on the web for further information about all theses functions
In case this is useful for anyone else, this is how I achieved my original goal. Contrary to what I first thought, this can all be done using JS and does not require PHP or AJAX to update in real time.
$('input').keyup(function () {
if (($(this).val() == 'test') {
//Stuff
} else {
//Other Stuff
};
});
The .keyup() function is what allows this to work in real-time, as it is called whenever a key is hit on your keyboard.
Then within this, the .val() function is what is used to check the actual user-entered value of the input field. In this case, if this value equals 'test', then it performs whatever you place in the if statement.
Hope that helps if anyone has stumbled across this question hoping for this answer!

How to add a text box on a button click?

I am writing a JSP page where an admin can prepare the question format for the users. All the questions have multiple choices ranging from 2 (for yes or no) to 5. I want to provide a button for the admin which on click has to generate a text box corresponding to 1 answer. This button should also check that the answer boxes have not exceeded 5 as there can be no more than 5 multiple choices.
How can I go about this problem? How to stuff the JavaScript variable inside the innerHTML? I have done something like this:
function addAnswer(queryNum, ansCount){
var d=document.getElementById("div");
var i = queryNum;
alert(i);
var j = ansCount;
alert(j);
d.innerHTML+="<label class='optsurvey-answer' for='answer_'>Answer</label>"+"<input class='optsurvey-answerinput' type='text' name='<portlet:namespace />answer_'>";
}
</script>
Here queryNum and ansCount are params passed by JSP. I want to stuff them inside the d.innerHTML. Something like this
d.innerHTML+="<label class='optsurvey-answer' for='answer_'>Answer<HERE I HAVE TO STUFF "ansCOUNT" ></label>"+"<input class='optsurvey-answerinput' type='text' name='<portlet:namespace />answer_'>";
You are going to need to use JavaScript. You might want to start by reading up on JavaScript and DHTML. This would be a good place to start: http://www.devx.com/codemag/Article/15585
You need to get this working like below mentioned methods
1) Write a Javascript which displays the text box.
When do we call the above javs script? ON click of the button call the JS and Show it to the user
2) on Action, send the values from the jsp to the servlets or Action class for processing.
I hope this is clear, else dont hesitate to put ur comments, will reply you
Like in Java you can concatenate strings in JavaScript using the + operator.
var foo = 'some JS string';
div.innerHTML += '<someElement>' + foo + '</someElement>';
To learn more about JavaScript, I recommend to go through this w3schools quick tutorial/reference. If you want to go a bit further, go through this advanced presentation/exercise of John Resig. If you want a genious and easy to-use JavaScript framework, have a look at jQuery. If you want to learn more about communication between Java/JSP and JavaScript, check this article.

Categories

Resources