Retrieving javascript output from a form via php - php

I have a hidden field in a form where I'm trying to grab the users screen resolution. Then on the processing end retrieve the screen resolution via php. Unfortunately, my understanding of javascript is pretty limited. Here is what I have. I would really appreciate any help.
<head>
<script type="text/javascript">
function xy(){
document.write(screen.width + "x" + screen.height);
document.getElementById('xy').value;
}
</script>
</head>
<form action="" method=post >
//other fields here
<input type="hidden" name="xy" id="xy" value=""/>
<input type=submit name="button" value="button" />
</form>
When I view the page's source code, shouldn't I see the value set to for example "1366x768"? Now on the processing side, I would like to pull out information with php like this.
if(isset($_POST['xy']) && (!empty($_POST['xy'])){
$blah = $_POST['xy'];
//sanatize $blah;
}

You can use
<script type="text/javascript">
function setResolution()
{
document.getElementById('xy').value = screen.width + "x" + screen.height;
}
</script>
Then, on submit, make sure the function is executed
<input type="submit" name="button" value="button" onclick="setResolution()" />

use
function xy(){
document.getElementById('xy').value = screen.width + "x" + screen.height;
}
and use the script tag or execute the function after rendering of the form else the element would not be found
EDITED: added fiddle

ulliw,
you don't call the function so you don't get anything...
if you will change to this, i beleive it will work for you:
<head>
<script type="text/javascript">
document.write(screen.width + "x" + screen.height); //this will write on the html page
document.getElementById('xy').value=screen.width + "x" + screen.height; // this will put the resolution in your form's hidden field
</script>

Related

Calling php query in javascript

So I have a jscript that creates a new text input and a drop-down select with each addition. That first one i have on the page is fine since the php function gets called on that page. The issue i have is my drop-down does not get populated by my query since i do not have the javascript function calling the php function. Im not sure how to add that in.
Here is my Jscript function.
var counter = 1;
var limit = 45;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Hop " + (counter + 1) + " <br><input type='text' name='myInputs[]'><br>" + "Type "+ (counter + 1) + " <br><select name='myInputs2[]' data-rel='chosen'><?php query() ?></select>" ;
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Here is my html. This drop-down (the first drop-down) Does get populated.
<?php
include_once 'dropfunc2.php';
connect (); ?>
<script src="js/addInput.js" language="JavaScript" type="text/javascript"></script>
<form method="POST">
<div id="dynamicInput">
Hop 1<br><input type="text" name="myInputs[]"><br>
Type 1<br><select name="myInputs2[]" data-rel="chosen"><?php query() ?></select>
</div>
<input type="button" value="Add Hop" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
Now I have tried doing what i have found on this site and making my jscript a .php page and adding the Header("content-type: application/javascript"); but then the function breaks completely and it does not add more inputs. I get a addInputs is not defined jscript error.
Put your PHP code to retrieve the data in a separate file and then call that script with AJAX. You can either send back formatted HTML or a JSON array to parse through and populate the tags in JavaScript.
This will help you out if you're new to AJAX and don't want to use JQuery: http://www.w3schools.com/ajax/default.ASP
If you want to use JQuery, then check this out: http://api.jquery.com/jquery.ajax/

timer based on the user input PHP

I tried to create a timer based on the user input for how long the timer will go
here is my code for user input userinput.html
<form method="post" action="update.php">
<input type="number" name="inputnumber" />
<input type="submit" value="OK" />
</form>
here is my code using javascript and php update.php
<script type="text/javascript">
function countdown(secs, elem){
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
secs--;
var timer = setTimeout('countdown('+secs+',"'+elem+'")', 1000);
}
</script>
</head>
<body>
<div id="status"></div>
<script type="text/javascript">
countdown("<?php $test = $_POST['inputnumber'];?>","status");
</script>
</body>
I'm trying to pass the user input using php to javascript which is from this line
<script type="text/javascript">
countdown("<?php $test = $_POST['inputnumber'];?>","status");
</script>
I want the timer start based on the user input
but the result is the timer always start from 0
is my code wrong to passing the value from php to javascript ??
anyone know how to pass the value??
thanks
You need to echo the post parameter, otherwise it won't print for your JavaScript to use
countdown("<?php echo $_POST['inputnumber'];?>","status");
Or shorthand
countdown("<?=$_POST['inputnumber'];?>","status");

Basic PHP search...in need of reset script

I'm very new to PHP, so bear with my ignorance. I've got the following script that searches an excel sheet for cell data (it's a really basic company phonebook):
<html>
<?php echo "Search:" ?>
<form id="form1" method="post" action ="<?php echo $_SERVER['PHP_SELF']; ?>"> <label>
<input id="search" name="search" type="text" />
</label>
<label>
<input type="submit" />
</label>
<img src="loading.gif" width="16" height="11" />
</form>
<input type="reset" value="Reset">
<?php
$search= $_REQUEST['search'];
if ($search > ''){ $search = $search;} else { $search = '';}
?>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
var visualization;
function drawVisualization() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/pub?key=0Ap2dozrbYI5vdEV5ZmtzU3hCdktzWDU0NTdOQjRSNkE&single=true&gid=0&output=html');
query.setQuery('SELECT A, B, C, D where upper(A) like upper("%<?php echo $search; ?>%") or upper(B) like upper("%<?php echo $search; ?>%") order by A asc label A "Company", B "Contact Name", C "Contact Number", D "Company General Contact"');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {legend: 'bottom'});
}
google.setOnLoadCallback(drawVisualization);
</script>
<div id="table"></div>
</div>
</html>
When no text is entered and the user clicks submit, the view resets to show the complete excel sheet. I'd like to add a reset button that functions the same way (it makes more sense to the user to have an actual "reset" button.
Edit: Just a note that I'm not trying to simply clear the search input. Essentially, I'd like to replicate what the submit button does when a blank search is performed (which is display all the data).
Add this line to your html form:
<input type="reset" value="Reset">
There are a number of issues here that need to be addressed. I've cleaned out some of the code you posted but I didn't want to totally rewrite everything you did. It looks like you might have copied and pasted a couple examples you found on the web into one project. It really helps if you review what a script does before you put it into production. Doing so will help you with some of these issues. For instance, in one line you check a variable to see if it is greater than empty string. You then assign it to itself if it is and you assign it to empty string if it is empty. Basically, that line does nothing. Read through your code so you know what it does.
In the end, I figured out that you didn't really need PHP for anything. You are simply using it to post back to the server and reload the page. Since you are using JavaScript to actually load your information, I decided to do everything in JavaScript. It makes the page simpler and it prevents unnecessary postbacks. I also formatted your code a bit and cleaned it up some. However, this still needs to be further refined and cleaned up. I just got it to a working state:
<html>
<body>
<input id="search" name="search" type="text" />
<button id="submitQuery">Submit Query</button>
<button id="resetQuery">Reset Query</button>
<div id="table"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['table'] });
var visualization;
var searchTerm = '';
function drawVisualization() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/pub?key=0Ap2dozrbYI5vdEV5ZmtzU3hCdktzWDU0NTdOQjRSNkE&single=true&gid=0&output=html');
query.setQuery('SELECT A, B, C, D where upper(A) like upper("%' + searchTerm + '%") or upper(B) like upper("%' + searchTerm + '%") order by A asc label A "Company", B "Contact Name", C "Contact Number", D "Company General Contact"');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, { legend: 'bottom' });
}
google.setOnLoadCallback(drawVisualization);
$(function () {
$('#submitQuery').click(function (e) {
searchTerm = $('#search').val();
drawVisualization();
return false;
});
$('#resetQuery').click(function (e) {
$('#search').val('');
searchTerm = '';
drawVisualization();
return false;
});
});
</script>
</body>
</html>
Instead of using buttons in a form to do a postback, I made the buttons fill in the variable appropriately and call the function to draw the visualization. I did draw in jQuery to make things a bit easier (note the call to the CDN for it). That made the code cleaner and easier to use. You don't have to do it that way but you will need to rework my code if you take it out.
Let me know if you have any questions. As it stands now, this code should do exactly what you want it to do.

Why is $_POST empty when I can see the POST variables in firebug?

I am posting a form in an expressionengine (1.6.8) template. I'm doing it using jquery but have tried an HTML form too - same result. The PHP superglobal $_POST is empty after posting the form, even though I have PHP enabled on my templates (on input for the template containing the form and output on the processing template) and can see the POST variables in firebug.
Can anyone suggest what might cause this?
<html>
<head>
<script type="text/javascript" src="/_scripts/jquery-1.6.1.min.js"></script>
</head>
<body>
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(e){
e.preventDefault();
var path = "/select-locale/processing"
var form = $('<form/>');
form.attr("method", "post");
form.attr("action", path);
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", 'locale');
field.attr("value", 'NZ');
form.append(field);
$('body').append(form);
form.submit();
});
});
</script>
</body>
</html>
server-side code (inherited, not my own) :
<?php
var_dump($_POST);
var_dump($_GET);exit;
if ( ! isset($_POST['locale']))
{
$locale = FALSE;
$returnPage = "/";
}
else
{
$locale = $_POST['locale'];
$returnPage = $_POST['returnPage'];
}
if (isset($_GET['locale'])) {
$locale = $_GET['locale'];
$returnPage = "/";
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"} <?php
}
?>
{exp:cookie_plus:set name="cklocale" value="<?php echo $locale;?>" seconds="2678400"}
{exp:session_variables:set name="userLocale" value="<?php echo $locale;?>"}
{exp:session_variables:get name="testSession"}
{if '{exp:session_variables:get name="testSession"}'=='yes' }
{redirect="<?php echo $returnPage;?>"}
{if:else}
{redirect="/nocookies/"}
{/if}
check the network tab if the parameters you want are really sent out
check the url if it's correct
if you use any sort of routing mechanism or url rewrite, you might wanna review it also
check your validation and XSS rules (if any) as it may reject the whole array once hints of XSS is found.
happened to me a while ago (CI) and i was sending it to the wrong url
You might want to re-check the action attribute, are u sure you're sending the data to the right url? I doubt that anything could be filtered.
it seems like form is getting submitted twice because of either action attribute of form tag or oath value in jquery function
It may be useful
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body name="test">
<form action="/select-locale/processing" method="POST">
<input type="text" name="test"/>
<input type="submit" name="submit" value="submit">
</form>
<a id="test" href="">link</a>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#test').bind('click', function(){
var form ='<form action="/select-locale/processing" name="newform" method="POST"><input type="hidden1" name="locale" value="NZ"></form>';
$('body').append(form);
alert('added');
document.newform.submit();
});
});
</script>`

Document.write and Save to db with php

I was wondering if it is possible to save some data with PHP getting the value from a form placed in the page by javascript with document.write, the value of which has been set by javascript with document.getElementbyId(id).value.
I know that with .innerHTML() it doesn't work, since the save button doesn't get a value set with the .innerHTML() method.
So I was wondering, would it work if I have javascript place an input box with document.write and then its value is set by another js function?
Yes, as long as you place the <input> inside a form.
Here is a simple example:
PHP:
<?php
if( !empty( $_POST['hidden_input']))
{
die( 'Value: ' . $_POST['hidden_input']);
}
HTML:
<form action="test.php" method="POST">
<script type="text/javascript">
document.write( '<input id="hidden_input" type="hidden" name="hidden_input" value="0" />');
</script>
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
window.onload = function() {
document.getElementById('hidden_input').value = 'Changed with JS';
}
</script>

Categories