Javascript input issue - javascript

I have written a code for redirecting the page on submitting the form.
I have a drop down and textbox in that form.
I typed </script> as input for the textbox , which had lead to normal excution but with ); on screen.
this is what i got from my firebug tool
<script type="text/javascript">
loadSearch('Customer','
</script>
');
PHP CODE for submit
<?php
if($_POST['searchButton']){
echo "<script type='text/javascript'>loadSearch('".$_REQUEST['search_details']."','".$_REQUEST['search_input']."'); </script>";
}
?>
JAVASCRIPT
function loadSearch(selM,selK){
document.location.href="index.php?pg=search&selM="+selM+"&selK="+selK;
}//loadSearch
Note: $_REQUEST['search_input'] is the textbox and if the textbox is given with </script> as input

There is a severe vulnerability in you server side code. You should always clean strings which arise from user inputs using methods like htmlspecialchars.
Replace :
$_REQUEST['search_details']
and
$_REQUEST['search_input']
With :
htmlspecialchars($_REQUEST['search_details'], ENT_QUOTES, 'UTF-8')
and
htmlspecialchars($_REQUEST['search_input'], ENT_QUOTES, 'UTF-8')
Not doing this can make your website vulnerable where a malicious user could include scripts to snoop on your users. What this function does is convert special characters like < to html HTML character entities like < so that it can't be interpreted as code by the browser on the client side.

The problem is that you are dumping the request values into your page without doing any escaping of them. Since this is JavaScript, one quick fix is to use json_encode() to encode the values as JSON:
<?php
if($_POST['searchButton']){
echo "<script type='text/javascript'>loadSearch(".
str_replace(json_encode($_REQUEST['search_details']), '<', '\x3C') . ", " .
str_replace(json_encode($_REQUEST['search_input']), '<', '\x3C').
");</script>";
}
?>
Also, your function should be using encodeURIComponent():
function loadSearch(selM,selK){
document.location.href="index.php?pg=search&selM="+
encodeURIComponent(selM) + "&selK=" +
encodeURIComponent(selK);
}
But the question remains: if what you really want to do is redirect the user to a search page, why are you using this roundabout script approach in the first place? Why not just do a redirect directly from your PHP?

\Why do you not consider to use plain javascript without any php?
<input type="text" id="selM">
<input type="text" id="selK">
<input type="button" onclick="loadSearch(document.getElementById('selM').value,document.getElementById('selK').value);">

Related

grab values from input box with php

I was wondering if it would be possible to have a php file grab data from a html page with an input box, so that the user enters a word, and the php runs using that word in the script once the user hits enter. Any help would be appreciated.
Use a form with the method attribute set to ‘get’ or ‘post’ like this:
<form method=“post”>
<input type=“text” name=“test” value=“test” />
<button type=“submit”>submit</button>
</form>
Then on the same php page, use this to get the result, store it in a variable and output it:
<?php
$result = $_POST[‘test’];
echo $result;
?>
More information:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form
Hope the formatting in this answer is ok, typed it out on my mobile phone.

Php code to modify a document element

I am trying to build a PHP webpage with the following behaviour:
1- A client access the webpage (that contains some buttons);
2- When the webpage is loaded, the PHP script opens a file stored on the server and, based on the information in this file, enables/disables some of the buttons, so that the client can see the webpage with the correct buttons enabled or disabled.
To enable/disable buttons, I know I can use javascript, while to read the file on the server I use PHP as stated above.
How do I put the two things together? Or should I use a PHP code equivalent to the following javascript line:
<script>document.getElementById("button1").disabled = true;</script>
At first I thought that inserting this line in the PHP code was the solution, but then I found out that this can't work for obvious reasons.
Thanks for the help!
Is it correct if I add the following javascript function in the head section of my webpage?
<script>
function enableButtons() {
<?php
if($state=="state1") {
echo 'document.getElementById("button1").disabled = true;';
}
else if($state=="state2") {
echo 'document.getElementById("button2").disabled = true;';
}
?>
}
</script>
I call the enableButtons() function when loading the page by using
<body onload="enableButtons()">
The php code above is just an example, the number of states and buttons is higher, that's why I would like to use this solution.
The common thing to do is to have php read the settings file, and echo the "disabled" attribute on the buttons before sending the output to the user browser. You can get more info about the attribute here here.
You do not need javascript.
Do something like this:
<button type="button" <?php if($state === 'state1') echo 'disabled'; ?>>Button text</button>
Usually you send to the client the buttons already disabled and use js to respond to any event that happens after sending the page, like selecting a combo box value..
You can omit the code, using an if sentence, or hide them using css. First approach is preferred.
Script
<script>
function isValid(f){
if(f.test.value==''){
alert('please enter name');
return false;
}else{
$(".bbutton").html("Processing please wait");
return true;
}
}
</script>
HTML
<form method="post" onsubmit="return isValid(this);">
<input type="hidden" name="te">
<input type="text" name="test">
<div class="bbutton">
<input type="submit" value="send">
</div>
</form>
When you submit the form then it will automatically hide the submit button to avoid pressing again and again, and you can redirect it to other page. May be this idea helpful.

Auto filling a form and submitting based on a ajax search answer

This problem has been frustrating me for a few days, and as I have found some help here for other problems on my project, it seems that someone could provide insight that I am overlooking.
I admit I am very new to sql, javascript, jquery, ajax, css, and php. I did 3 years of Computer science in college (15 years ago) While coding and logic don't change much, its syntax and handshakes, and where the computing is happening that I have either forgotten, overlooked, or am ignorant.
I have completed an ajax based search submission.
this search displays the target php in a div labeled .Admin
this works excellently.
Its answer is a display of a tree and the nodes above and below the searched node.
I want to make each node in the tree a clickable link to the search results for its own node.
In the php result I coded it to write in a html call to a javascript function and it generates a unique id for each , as well as its own function call. (whether or not that is a good idea its what i tried) I would think that it is then easy to get javascript to fill out the form with the created link using information it knows and resubmit as no refresh is needed to search again. I tried having the php write this script so that it is developed with the page, and I have tried writing the script and including it in the parent page, so that it is already loaded... I'm not sure where it should go or how it should be written.
I may be missing an integral part, or I'm trying to do more than I am supposed to with the code or not completely grasping where the operation is happening and need to rethink it entirely.
I will try to include all relevant code, if its not enough, I will happily add. Thanks in advance.
CallSearch.js
$(document).ready(function() {
$('#Search').submit(function(event) {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : $( this ).serialize()
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
Menu.php (where my search form is)
<script src="/JS/CallSearch.js"></script>
...
<li><a>Search</a> <input type= "text" name="Search" id="search_name" class="search-group">
<ul>
<li><input type="radio" name="Table" id="TableRegion" value="R" class="search-group" checked><label for="TableRegion">Region</label></li>
<li><input type="radio" name="Table" id="TableGrape" value="G" class="search-group"><label for="TableGrape">Grape</label></li>
<li><input type="radio" name="Table" id="TableWine" value="W" class="search-group"><label for="TableWine">Wine</label></li>
<li><button type="submit" id="SubmitSearch">Submit</button></li>
</ul>
</li>
</form>
...
MenuSearch.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'Webpage');
define('DB_PASSWORD', 'Guest');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
...
$sqlp ="SELECT * FROM region a JOIN Regionclosure b ON a.idregion=b.parent WHERE b.child= $idReg ORDER BY b.Depth DESC;";
...
$resultp = mysqli_query($db, $sqlp);
$string ="";
while($row = mysqli_fetch_assoc($resultp)){
$Reg = $row["RegName"];
$Parent= $row["Parent"];
echo $string . "|___";
if($_SESSION["Level"] == 'A' or $_SESSION["Level"] == 'C')
echo $Parent . " - ";
echo "<a href='#' id='$Reg'>" . $Reg . "</a><br>";
echo "
<Script>
$('#$Reg').click(function(){ searchforReg('$Reg'); return false; });
</script>";
$string .= " ";
};
I have tried multiple iterations of a function for "searchforReg('$Reg'); to no avail... i feel like it should be something like :
function "searchforReg(Region){
SearchData= "Table=R&Search="+$(Region).val;
(function() {
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
event.preventDefault();
});
});
This however results in activating the "action" search failing to send the answer to the and opens the php (with no CSS... gasp.. its just not pretty) I feel like a simple javascript should be able to handle it, but i tried all of the different ways i could think of (or look up) to make it work to no avail.
I realize I am playing in the "deep end," and I'm in my "water wings" so if you could have mercy and push me to the edge, I would appreciate it.
First, the process of printing a click handler for each link is overkill. Instead, just give each link a class and set up a single handler for any link of that class. In menusearch.php:
echo "<a href='#' id='$Reg' class='reg_link'> $Reg </a><br>";
$string .= " ";
Side note - in PHP, if you echo with "double" quotes, variables will be rendered, so no need to concatenate. That's why $Reg is just hanging out. If you echo with 'single' quotes, the string is interpreted literally.
Then in menu.php, we have a bit of javascript:
<script>
/* This is a non-standard listener, bound to the body so that any
dynamically added elements pulled in via ajax, but not in the original document can still be found.
Also, this can be shortened to a single line, but I split it up for clarity.
The single-line version is commented out. */
$(document.body).on('click', '.reg_link', function(){
//searchforReg($(this).attr('id'));
var id = $(this).attr('id'); //get the id of clicked element
searchforReg(id); //trigger function
});
function searchforReg(Region){
var SearchData= "Table=R&Search="+Region;
//If you're not familiar with console.log, it's a huge help in debugging
//console.log('searchData = ', SearchData);
$.ajax({
type : 'POST',
url : 'MenuSearch.php',
data : SearchData
})
.done(function(results) {
$(".Admin").html(results);
});
}
</script>
Finally, I'm guessing you have some $_POST handling in MenuSearch.php for that data, but I don't see that above so I'll assume it's working...

How to execute javascript without click or onload event from php?

I have one javascript named func.js, in that there is one function called show which takes 2 arguments, what I need to do is I want to call that function from php, I can't use any click or onload event here my script looks like this
<html>
<head></head>
<script type='text/javascript' src='path/to/func.js'></script>
<body>
some div etc
<form method='post' action="" >
.....
.....
</form>
</body>
</html>
<!-- after submit of form validation is in php -->
<?php
/* here I want to call javascript, where arguments are php variables
show('argument1','argument2'); */
// I tried to echo like this
echo "<script>show('$argument1',$argument2')</script>";
?>
So what's the solution for my case ?
The code you have should work… most of the time. Unfortunately, you haven't told us why it doesn't work - is there a PHP error? Is there a JS error? — and you haven't shown us either the resulting JavaScript that PHP is outputting or the contents of the variables so we can figure it out for ourselves.
The two most likely explanations (and the only ones that occur to me at the moment) for the problem are:
There is a problem with the data in the variables
That the variables contain characters which cannot appear inside JavaScript strings or ' characters which must be escaped inside JavaScript strings.
JSON is a sufficient subset of JavaScript that the json_encode function will escape (and quote) most data so it is suitable for use in JS.
<script>
show(<?php echo json_encode($argument1); ?>, <?php echo json_encode($argument2); ?>)
</script>
There is a problem with your timing
You have an HTML comment saying "after submit of form validation is in php", but there is nothing in the code you have shared to enforce that.
You need to have something like if (isset($_POST['some_data_from_your_form'])) { ... } wrapped around the generation of the script so it only appears when the form is submitted and not when it initially loads.
If that doesn't work, then you really do need to look at what the variables are, what the generated JS is, and what your JavaScript error console says.
Script elements are not allowed after the end of the HTML element. While browsers will recover from that error, you really should move the script inside the BODY.
It could be to do with the data inside the arguments, what sort of data is it?
echo "<script>show('".str_replace("'", "\'", $argument1)."', '".str_replace("'", "\'", $argument2)."')</script>";
If you're passing information such as J'min it will cause an issue. Does the data have multiple lines? Then it needs to be filtered.
First of all, your tags are broken
<script type='text/javascript' href='path/to/func.js'</script>
You should change href to src and close the script tag, so it becomes
<script type='text/javascript' src='path/to/func.js'>
Also, javascript is client-sided which means you can't call javascript functions in PHP.
I think a good solution here would be to use an AJAX call to validate your form.
Have you tried putting the arguments outside the quotes?
echo "<script>show('".$argument1."', '".$argument2."')</script>";
echo '<script type="text/javascript">show(' . $argument1 . ',' . $argument2 . ');</script>';
above might work for you.

How would I call a java script function using php if statement with $_SESSION

Hi I am creating a website with a login section this is working I am using HTML and PHP. What I am trying to do is one of my pages has a html button I want this to be disabled for certain users. at the moment this is what I have got.
this is the part that I use for the login details.
<?php
session_start();
$_SESSION["username"];
$_SESSION["password"];
$_SESSION["access"];
?>
I have got if statments that I am currently using which are
if($_SESSION["access"] == "Administrator"){
echo $Admin;
}
what I am trying to do is call a javascript function within a PHP if statement what i have got so far is
<?php
if($_SESSION["access"] == "Consumer")
{
echo '<script type="text/javascript">
Disable();
</script>';
}
if($_SESSION["access"] == "Administrator")
{
echo '<script type="text/javascript">
Enable();
</script>';
}
?>
the javascript functions that i am trying to call are
<script type="text/javascript">
function Enable() {
SubmitButton.disabled = false;
}
function Disable() {
SubmitButton.disabled = true;
}
</script>
I have also tryed
if($_SESSION["access"] == "Consumer")
{
echo "<script> Disable(); </script>";
}
Im just wondering if I have typed something in wrong or if I have forgotten to put something in.
any help would be much appreciated.
Looking at your code you have couple of issues:
Mixing your PHP logic and pure HTML is (usually) not a good idea.
Instead I would suggest you move your access checking logic fully on the server side and display the button accordingly (disabled or enabled) based on the user's access.
Example:
<?php if($_SESSION['access']): // Only show the button for users with access ?>
<button type="submit" value="Submit" <?php echo ($_SESSION['access'] != 'Administrator' ? 'disabled' : ''); // Button disabled for everyone but administrators ?> />
<?php endif; ?>
And let me point out the obvious (as mentioned by the other answers), that's not 100% bulletproof. The user can still manually submit the button even if he is not an administrator by editing the page's HTML on the fly. That's just a UI fix. The real check should be done on the server side once the button is submitted (e.g. is the user logged in, does he have a cookie on his computer that identifies him as an administrator, does he have a session cookie set, etc).
Calling JS in random places, e.g. in the header can have unexpected consequences.
You better wait for the page to be loaded fully before calling any JS functions. You can do that via jQuery easily, but make sure you include the jQuery library before that in your header like so.
Afterwards you can call any JS after the page is loaded by placing them within the following block:
$(function(){
// Place your JS calls here, e.g. call to Enable()
});
String concatenation in PHP is done with a dot . and strings can be multiline
This code which you used is just plain wrong.
echo '<script type="text/javascript">'
, 'Enable();'
, '</script>';
You should use something like:
echo '<script type="text/javascript">'
.'Enable();'
. '</script>';
or better:
echo '<script type="text/javascript">
Enable();
</script>';
PHP doesn't use , sign for joining. Use ..
But otherwise it should work, except that you should define SubmitButton in advance of using it.
<?php
echo "<script type='text/javascript'>";
// if the id of your element is "submitButton"
echo "var submitButton = document.getElementById('submitButton');";
echo " function disable(){ submitButton.disabled=true; }";
echo "</script>";
?>
After that you can use it as you did..
<script type='text/javascript'>
disable();
</script>
Just be advised that denying access to some elements/functionality on your webpage with JavaScript alone is not a good practice - JavaScript is executed locally on the user's computer and therefore the user can modify it to gain an advantage.
Well, the problem may be that you're trying to call the javascript function before the HTML is ready (or finally rendered), so the browser, when executes the function doesn't find the button.
You could solve this placing your javascript code at the end of your page, or using jQuery and doing:
$(document).ready(function() {
<%php if ($_SESSION['access'] == 'xxxxx') {%>
Enable();
<%php } else { %>
Disable();
<%php } %>
});
Anyway, ALWAYS check user permissions on the server side, because someone could enable the button using Firebug or something else...

Categories

Resources