On my site I have a main search (powered by Google, placed throughout the site) and I have now created a second search (on its own page, which searches my DB for images based on user input text) which is a totally separate search to the google one.
What I want to do -
I want both Search forms to share a single text input field, but allow the user to choose which search to use (Google or Images Only) via radiobutton.
So we'd have:
[search input field][go] (o)Use Google (o)Image Search only
I'm no coder but can hack enough to just about get by, it just takes me a day or two to figure out and get working.
What I need and would save me a great deal of time, as I'm stumped on how to proceed with this or if it is even possible! If someone could tell me A) If it's possible, and B) A few pointers if it is. For instance I'm guessing it will probably need a bit of JavaScript to make it possible?
Any pointers would be appreciated, then I can see what I can do.
All the best,
Chris
// My Stand-alone Image Search Page ////////////////////////////////
<form method="post" action="imagesearch?go" id="search-form">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
// code for above form //
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
$sql="SELECT ID FROM ImageTable WHERE Name LIKE '%" . $name . "%' Order by Date Desc LIMIT 50";
//-run the query against the mysql query function
$result=mysql_query($sql);
// Create while loop and loop through result set//
$content .= ' <p><div id="wrapper">';
while($row=mysql_fetch_array($result)){
$id=$row['ID'];
$img = new Image($id);
// Format results//
$content .= '<div id="imgrt"><img src="/img/M/'.$img->ID.'.jpg" class="searchimg"><br>'.$img->Name.'';
$content .= '</div>';
}
$content .= '';$content .= '</div>';
}
else{
$content .= ' <p>Please enter a search query</p>';
}
}
}
// End of Stand-alone image search page /////////////////////////
---------------------------------------------------------------------------
// My sites main Google powered Search
<form action="http://www.example.com/gsresults" id="cse-search-box" class="searchmain">
<input type="hidden" name="cx" value="partner-pub-XXXXXXXXXXXXXXX" />
<input type="hidden" name="cof" value="FORID:XX" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="mainsearch">
<input type="submit" name="sa" value="Go" class="mainsearchbutton"/>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang="></script>
OK so here we go. If you plonk this in an empty html file you can see it in action (Tried to make a jsfiddle but didnt work for some reason). What this does is set an "active" id on the selected combo option, and when you click the submit button it grabs the value of the combo option with that id, and goes to the page of that value. so if you click google and then the button you go to google.html, and same goes for image, image.html. If you want some more specifics you can ask, but thats the main logic there.
<script>
function replaceActive(obj) {
var activeElm = document.getElementById("active");
activeElm.id = activeElm.id.replace("active", "");
obj.id = "active";
}
function formFunction(obj) {
obj.action = document.getElementById("active").value + ".html";
}
</script>
<form action="#" onsubmit="return formFunction(this);" method="post">
<input type="text" />
<select>
<option value="google" id="active" onclick="replaceActive(this);">Google</option>
<option value="image" onclick="replaceActive(this);">Images</option>
</select>
<input type="submit" />
</form>
Basically you can change that "formFunction()" function's code and and use "document.getElementById("active").value" to do what ever you wanted to do.
Related
Sorry for my noobness here I'm trying to create a project with no PHP knowledge at all.
I have a database set up with a list of users and I am able to display users based on specific information through a search. Each search query has a checkbox. What I am trying to do now is limit the amount of selected checkboxes (up to 3 selections only) and save the selected queries to a different page. Can someone point me in the right direction? I'm sure my code is all over the place and probably wrong in many ways so I apologise in advance. I appreciate it.
Search Results Page:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/overallheader.php';
?>
<h1>New Staff Request</h1>
<p>Search for potential staff using the form below</p>
<form method="POST">
<input type="TEXT" name="search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>
<br/>
<p><b> Select only up to 3 results</b></p>
<form method="post" action="StaffingRequest.php">
<?php
if(isset($_POST['submit'])){
$mysqli = NEW mysqli('localhost','root','','lr');
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM users WHERE jobcat LIKE '%$search%' ");
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$education = $rows['education'];
$salary = $rows['salary'];
$jobcat = $rows['jobcat'];
echo "<br /><input type='checkbox' name='query[]' value=''> First Name: $first_name<br />Last Name: $last_name<br />Job Category: $jobcat<br />Education: $education<br />Salary: $salary<br /><br />";
}
} else {
echo "No Results";
}
}
?>
<input type="submit" name="submit" Value="Save">
</form>
<?php include 'includes/overall/overallfooter.php'; ?>
Here is the page I want the results to display on:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/overallheader.php';
?>
<h1>My Staff Requests:</h1>
<p></p>
<?php
$chkbox = $_POST['query'];
$i = 0;
While($i < sizeof($chkbox)) {
echo "CheckBox Selected Values = " . $chkbox[$i] . '</br>';
$i++;
}
?>
<?php include 'includes/overall/overallfooter.php'; ?>
You are going to want to use JS/jQuery to accomplish this.
What you are going to do is add some client side functionality that checks how many check boxes of the same class have a check in them.
I added the code for you. This is what it does.
Add the jQuery library.
Add a classname (class="checkboxes") to the input tag to be referenced later.
Detect when there has been a change to an element with the class name "checkboxes".
Count to see how many elements with the class name "checkboxes" have a checked checkbox.
If there are three checked check boxes, remove the check from the last(4th) selected check box.
Display an error to the user that only three check boxes can be selected.
Like so:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/overallheader.php';
?>
<h1>New Staff Request</h1>
<p>Search for potential staff using the form below</p>
<form method="POST" action="">
<input type="TEXT" name="search" />
<input type="SUBMIT" name="submit" value="Search" />
</form>
<br/>
<p><b> Select only up to 3 results</b></p>
<form method="POST" action="StaffingRequest.php">
<?php
if(isset($_POST['submit'])){
$mysqli = NEW mysqli('localhost','root','','lr');
$search = $mysqli->real_escape_string($_POST['search']);
$resultSet = $mysqli->query("SELECT * FROM users WHERE jobcat LIKE '%$search%' ");
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$education = $rows['education'];
$salary = $rows['salary'];
$jobcat = $rows['jobcat'];
echo '<br /><input type="checkbox" name="query[]" class="checkboxes" value=""> First Name: ' . $first_name . '<br />Last Name: ' . $last_name . '<br />Job Category: ' . $jobcat . '<br />Education: ' . $education . '<br />Salary: ' . $salary . '<br /><br />';
}
} else {
echo "No Results";
}
}
?>
<input type="submit" name="submit" Value="Save">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".checkboxes").change(function (){
if($('.checkboxes:checkbox:checked').length > 3){
$(this).prop('checked', false);
alert("You can only select 3 checkboxes.");
}
});
});
</script>
<?php include 'includes/overall/overallfooter.php'; ?>
A couple other things.
I try real hard not to have more than one form on a page. For the most part you should only need one. I would say that if you have two forms it's a special case. Your first form that you use for the search could easily be replaced with an AJAX routine.
When echoing HTML though PHP, I recommend using single quotes. This will prevent alot of problems dealing with the quotes for the elements attributes. Here is an example of how I do it:
echo '<input id="myId">Test</input>';
This will save you some headaches down the road.
Hope this works for you..
I have a html file which loads a list from my database and allows the front end user to remove a particular entry.
The HTML Code looks like this:
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend=$("#clientid").val();
$("#responseDiv").html("<h2>Removing from Database...</h2>");
$.post("RemoveClient.php",{
ClientId: dataSend
},function(data) {
$("#responseDiv").html(data);
$("#clientlist").empty();
$("#clientlist").html("{client_list nocache}");
});
return false;
}
// ]]></script>
</p>
<div id="MainForm"><form class="form" onsubmit="return sendForm()">
<h2 class="formstyle">Client Wizard</h2>
<p>Please fill all the required fields.</p>
<div id="clientlist">{client_list nocache}</div>
<p><input style="font-size: 1.5em; font-color: #000000;" onclick="sendForm()" type="submit" value="Delete" /></p>
</form>
<div id="responseDiv"> </div>
</div>
The UDT called for {client_list} is given below.
$dbhost='127.0.0.1';
$dbuser='user';
$dbpass='pass';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$sql="SELECT clientid,clientname FROM client order by clientid";
echo "<label> Select Client: </label>";
echo "<select id=clientid name=clientid>";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
echo "<option value=".$row['clientid'].">".$row['clientname']."</option>";
}
echo "</select>";
Now, once I click on delete, I want the drop down list to refresh with the new list not having the deleted client. I tried doing that by emptying the div and then reloading the UDT. Unfortunately this does not seem to be working, the way I want it to, as the list does not get refreshed until and unless I refresh the page. Is there anyway I can make this work?
The quick/easiest option would be to assign it an id and to remove the entry via javascript.
Second, would be to have RemoveClient.php return it as part of the response from the AJAX.
var response = data.split('|');
$("#responseDiv").html(response[0]);
$("#clientlist").html(response[1]);
Third, I would strongly advise against this way but it is the question you ask, put the UDT alone on new page then load the page with the ?showtemplate=false parameter.
$("#clientlist").load("//www.mydomain.com/myudt.html?showtemplate=false");
I have a form that autocompletes the client name based on the input from the user.
HTML:
<label for="client">Facility Name/Account Number: </label>
<input type="text" oninput="dropdownTip(this.value)" id="client" NAME="client" style="width:100%;">
<label for="iname">Interpreter Name:</label>
<input type="text" style="width:100%; text-transform:capitalize;" id="interpreter" name="iname" value="<?echo $interpreter;?>"/><BR>
Javascript:
jQuery(document).ready(function(){
$('#interpreter').autocomplete({source:'otp_autocomplete.php', minLength:2});
});
jQuery(document).ready(function(){
$('#client').autocomplete({source:'otp_client_autocomplete.php', minLength:2});
});
The same form also populates additional fields based on the value of the client field using the following php generated javascript:
PHP:
<script type="text/javascript">
function dropdownTip(value){
var preamble = 'No Special Instructions';
<?//Load options from DB.
while($row = mysqli_fetch_array($statuses)){
echo "if(value == '" . $row['client_id'] . " - " . str_replace("'","\'",$row['client_name']) . "') {
preamble = '" . $row['Special_Instruction'] . "';
} ";
}
?>
console.log(value);
document.getElementById("result").innerHTML = preamble;
}
</script>
Everything is working great, except that I would like the function "dropdownTip" to trigger as soon as the autofill option is selected. Currently it only activates once another field is clicked on, and does not activate at all in Internet Explorer.
I have been trying different HTML DOM events listed here:
https://en.wikipedia.org/wiki/DOM_events
But I can't seem to find the right one. Is there one that will provide the functionality I am looking for, and work with IE?
I'm currently studying html and php and I made this little project about a "notification system". I guess I first have to explain this before I go in detail on my real problem.
My table looks like this:
My first php command would get the values of each feature column and store them into $a, $b, $c, $d and $e.
My second php command would echo 5 textboxes and mark them as checked based on the value of $a,$b,$c,$d and $e so the output based on my table would show five checkboxes with the 1st, 2nd and 4th checkbox with a check.
My third php command would gather the values from the checkboxes because the user might want to change his preferred notifications. After clicking submit the code would update the new values of the textboxes.
Below is the code on my current progress:
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('main_database') or die(mysql_error());
$fetchchoice=mysql_query("SELECT * FROM notification_table WHERE username='carl'");
while($getchoice=mysql_fetch_assoc($fetchchoice)){
$a=$getchoice['feature1'];;
$b=$getchoice['feature2'];
$c=$getchoice['feature3'];
$d=$getchoice['feature4'];
$e=$getchoice['feature5'];
}
?>
<html>
<head>
</head>
<body>
<form method="POST">
<?php
echo
'
<input type="hidden" name="choice1" value="">
<input type="checkbox" name="choice1" value="checked" '.$a.' > Feature 1 <br>
<input type="hidden" name="choice2" value="">
<input type="checkbox" name="choice2" value="checked" '.$b.' > Feature 2 <br>
<input type="hidden" name="choice3" value="">
<input type="checkbox" name="choice3" value="checked" '.$c.' > Feature 3 <br>
<input type="hidden" name="choice4" value="">
<input type="checkbox" name="choice4" value="checked" '.$d.' > Feature 4 <br>
<input type="hidden" name="choice5" value="">
<input type="checkbox" name="choice5" value="checked" '.$e.' > Feature 5 <br>
';
?>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
$f1choice = $_POST['choice1'];
$f2choice = $_POST['choice2'];
$f3choice = $_POST['choice3'];
$f4choice = $_POST['choice4'];
$f5choice = $_POST['choice5'];
echo "1.";
echo $f1choice;
echo "<br />";
echo "2.";
echo $f2choice;
echo "<br />";
echo "3.";
echo $f3choice;
echo "<br />";
echo "4.";
echo $f4choice;
echo "<br />";
echo "5.";
echo $f5choice;
$kweri = "UPDATE `main_database`.`notification_table` SET `feature1` = '".$f1choice."', `feature2` = '".$f2choice."', `feature3` = '".$f3choice."', `feature4` = '".$f4choice."', `feature5` = '".$f5choice."' WHERE `notification_table`.`username` = 'carl'";
mysql_query($kweri);
}
?>
</body>
</html>
PROBLEM
My problem now is that I have to refresh the page to have the updated checkbox to appear since this was only done on php, I have no experience in javascript at all but I think it's the best way to show my current textbox on realtime, however, I have no idea where to start or if there is another way I could go about showing my checkbox on realtime.
EXTRA PROBLEM (This has something to do with my system but not regarding this code. If you guys could take a look at this problem it would mean a lot.)
As you guys have seen, the table above was just to keep track of what a user's preference regarding notifications would be. But the system doesn't stop there, I need to figure out how to pass notifications after a feature has been used. What my idea was is that I should add an extra sql command after every feature to put what has happened on a different table. Example would be registration, after the insert command for the registration details to be saved, I would also insert that, user "example" has "registered" on "date" in a separate table, namely "notif_table". My columns would be, username, action and date so my notifications page can show that "User" has "Registered" on "January 18, 2015".
But then again, that was just my theory on notifications and I'm very open to suggestions and corrections.
Just put the part with if(isset($_POST['submit'])) prior to your select statement.
EXTRA PROBLEM:
Just add a column to your existing table (e.g. 'created') and put now() into it when inserting the row.
So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo