Basic PHP search...in need of reset script - php

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.

Related

Use data asscociated with a DOM element just with PHP?

You know jQuery.data() can be very useful, but can I use this in a form and to check it directly with PHP? Like $_POST['inputValue'] but $_POST['dataAttribute'] ? Or even to set it with PHP ?
One thing I seem to see a lot of PHP developers forgetting is that PHP is a server language and can't really do much interaction with the client without the assistance of a client side language like Javascript.
You should be able to generate the data-* attributes on the server side with DOMDocument operations, or even by string concatenation if you're that old-fashioned. If you use the DOMDocument approach modifying the values should also be pretty easy while you're in the process of building your DOM tree.
$doc = new DOMDocument ();
$elem = $doc -> createElement ('input');
$doc -> appendChild ($elem);
$elem -> setAttribute ('data-foo', '123');
// etc
As soon as you transform the DOM model to text for sending to the browser, any subsequent modifications become meaningless because they won't be reflected in the browser.
If you need changes made client-side to be known to the server, then you'll need to do some javascript in the client to collect all the data-values, serialise them and post them to the server.
In order to past data values you can create hidden variables in the form with all data attributes you want before the submit event.
Html:
<div id="element" data-myattr="any_data_value"></div>
<form ...>
</form>
jQuery:
<script>
$(function() {
$("form:first").submit(function() {
// any validation
var v = $("#element").data("myattr");
$("form:first").append('<input type="hidden" name="data_myattr" value="' + v +'">');
return true;
});
});
</script>
Rendering data attributes using PHP:
<?php
$myattrvalue= $_POST['data_myattr'];
?>
<div id="element" data-myattr="<?php echo $myattrvalue; ?>"></div>
Hmmph. I've been working at this for 1+ hrs amid other things. Now there are other, very good answers.
Still, fwiw, here's another:
Here is an example where a div is hidden initially, and a data- attribute is used to decide whether the div should be revealed.
AJAX is used to communicate with a back-end PHP file that just spits out "yes" (if the field value is still "no", but otherwise spits nothing).
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
var ax, dd, kk=0;
dd = $('#hid').data('lnreq');
if (dd=="no") $('#lnDIV').hide();
$('#fname').keyup(function() {
if (kk < 4){
dd = $('#hid').data('lnreq');
$.ajax({
type: "POST",
url: "myprocessor.php",
data: "ddVar=" + dd,
success: function(recd) {
//alert(recd);
$('#hid').data('lnreq', recd);
if ($('#hid').data('lnreq') == 'yes') {
$('#lnDIV').show();
}
}
});
kk++; //Do only a few times
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<form id="myForm" action="" method="POST">
First Name: <input id="fname" name="fname" type="text" /><br />
<div id="lnDIV">
Last Name: <input id="lname" name="lname" type="text" />
</div>
<input id="hid" type="hidden" data-lnreq="no" />
</form>
</body>
</html>
PHP SIDE: myprocessor.php
<?php
$rr = $_POST['ddVar'];
if ($rr == "no") echo 'yes';

Getting variable from the Url

I have a jquery function that retrieves information that a user clicks on in a database table.The user can select any one of ten rows that becomes highlighted when mouseover and when the user clicks the highlighted row the function retrieves it and puts it into a textbox. Then if the user submits this request for purchase I want to echo the textbox on the next page which is an order form.
The code below works well up until I try to retrieve the information from the url. I can see that it is passed in the url to the next page but after trying for two days I have not been able to retrieve it. I don't know where to go from here. Can someone look at this and see if I have not coded properly or done something wrong.
I have copied down the code that applies...
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("table tr").click(function(){
$("#txttread").val($.map($(this).children('td:not(:eq(7))'), function (item) { return $(item).text() }).join(' - '));
});
});
$(document).ready(function() {
$('.pickme tr').not(':first').hover(
function() { $(this).addClass('highlight'); },
function() { $(this).removeClass('highlight'); }
).click( function() {
$('.selected').removeClass('selected');
$(this).addClass('selected').find('input').attr('checked','checked');
});
});
</script>
</head>
<body>
<form action="Order.html" method="GET" name="myform2" />
<div>
<div style="text-align:left height:250px;">
<DIV STYLE="font-family: Arial Black;
color: black; font-size: 20pt;">
Select from inventory below:<br/><input type="text" style="width:500px; height:35px;" rows="1" STYLE="font-family: Arial Black;
color: red; font-size: 20pt;" name="txttread" id="txttread" DISABLED /></div></div></div>
<div>
<div style="text-align:center;">
<br/><input type="button" button id="getone" name="getone" value="Submit your request for purchase" onclick="window.location.href = 'http://localhost/order.html?txttread='+ ( $('#txttread').val() )"><br/><hr/>
</body>
</html>
The url on the next page is....
http://localhost/order.html?txttread=Firestone - All Season - FR-710 - 225/60/16 - 4 - 3 - 60.00
I think this has to do with the URL not being encoded correctly. On that last line where you append the $('#txttread').val(), you should wrap it with encodeURIComponent():
<input type="button"
button id="getone"
name="getone"
value="Submit your request for purchase"
onclick="window.location.href = 'http://localhost/order.html?txttread=' + encodeURIComponent($('#txttread').val());">
This might not answer your question completely, but consider this:
window.location.href = 'http://localhost/order.html?txttread='+ ( $('#txttread').val() )
You should apply proper escaping when you pass parameters:
window.location.href = 'http://localhost/order.html?txttread=' + encodeURIComponent( $('#txttread').val() );
To access the value of txttread from an HTML page:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
As found here: https://stackoverflow.com/a/901144/1338292

Retrieving javascript output from a form via 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>

Dynamicly add/remove form elements w/ mysql support

I'm trying to create page where the user can add & delete "soliders".
I'm looking for something like this:
[Text-box][Delete]
[Text-box][Delete]
[Add-Solider]
And I want it to support mysql, so the user can change the values later.
I've been searching, but i can't seem to find any with mysql-support.
It should also have a max-amount.
Have any of you dealt with something similar before? I would greatly appreciate any help!
I give here an example for Add and Remove elements.
<html>
<head>
<title>Add Element</title>
<script language="javascript">
this.num = 1;
function addElement(){
$top = document.getElementById('top');
newId = document.createElement('div');
id = 'my'+this.num;
newId.setAttribute('id', id );
newId.innerHTML = "<a href='javascript:void(0); ' onclick='removedThis( "+id +")' >Added Element"+id+"</a>";
$top.appendChild(newId);
this.num++;
}
function removedThis( id ){
var d = document.getElementById('top');
d.removeChild(id);
}
</script>
</head>
<body>
<input type="button" name="button" value="Add Element" onclick="addElement()" />
<div id="top" ></div>
</body>
</html>
Reference: javascript/php/mysal
I give here an example of jQuery. Then you can save <div id="boxes"> into mysql and induce again.
jQuery
<script type="text/javascript">
$(function () {
$("#add_new").click(function () {
var box = $("<div>[Text-box]<a class=\"del\" href=\"javascript:void;\">[Delete]</a></div>");
$("#boxes").append(box);
$(box).find(".del").click(function () {
$(box).remove();
});
});
});
</script>
HTML:
<div id="boxes"></div>
<button id="add_new">[Add-Solider]</button>

PHP Echo from Search Query on HTML Page

I am trying to display search query results on a separate page. I copied the code from a forum, but since the display page isn't php, I'm not sure it will work.
Here is the code from the home page:
<form action="search" method="post">
<input type="text" name="q" />
<input type="submit" name="search" value="Search" />
</form>
I want the search results to show on mysite.com/search (obviously)
The code on mysite.com/search is as follows:
<div id="cse" style="width: 100%;">Loading</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">//
google.load('jquery', '1');
google.load('search', '1');
google.setOnLoadCallback(function(){
var customSearchControl = new google.search.CustomSearchControl('XXXXX');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
$(".gsc-input").val("<?php echo $_POST['q']; ?>");//insert into search field requested search text
$(".gsc-search-button").click();//call button click event, show results
}, true);
// ]]></script>
Do I have any options? Is there a workaround?
since the display page isn't php
Then you can't use $(".gsc-input").val("<?php echo $_POST['q']; ?>");, but could use something like
$.get('path-to-php-script/query.php', function(data) {
$(".gsc-input").html(data);
alert('Load was performed.');
});
The idea is that you just use jQuery to retrieve and manipulate the data that you need to run through PHP script(s) before they're returned to the HTML-only display page.
You can achive like this
Put this code in your head tag
<script language="javascript">
function changeData(fromDiv)
{
document.getElementById('toDiv').innerHTML = fromDiv.innerHTML;
}
</script>
And This in your body tag
<div id="toDiv"></div>
<div id="fromDiv" onclick="changeData(this)">Hello World I am here</div>

Categories