how to write php MySql query - php

I would like to be able to make a selection from a select-box and view the selected table.
My skill level with php/MySQL at this point is:
$query = "SELECT * FROM electrical ORDER BY item_id LIMIT $offset, $RPP";
With this query the div is populated on page load.
I have a select box that has 6 choices:
<form>
<select name="dbtables" onchange="showTable(this.value)" id="selectBox">
<option value="">Select a materials table:</option>
<option value="" id="hr"></option>
<option value="equipment">Worker Equipment</option>
<option value="tool">General Tools</option>
<option value="electrical">Electrical Materials</option>
<option value="mechanical">Mechanical Materials</option>
<option value="plumbing">Plumbing Materials</option>
<option value="hvac">HVAC Materials</option>
</select>
</form>
Each choice is a table in a single MySQL database.
Script for showTable is working, after making selection alert shows choice picked.
function showTable(str) {
if (str == "") {
document.getElementById("materials").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("materials").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index.php?q=" + str, true);
xmlhttp.send();
alert(str);
}
Any pointers or help is appreciated appreciated.

I think what you're looking for is the SQL-query to execute on your database. What you should do is to insert the q-variable from the query string into the SQL-query like this
$query = "SELECT * FROM " . $_REQUEST['q'] . " ORDER BY item_id LIMIT $offset, $RPP";
Ofcourse you should check or escape the variables to prevent SQL injections, using something like mysql_real_escape_string, but that's not really the scope of this question.

in your index.php pick the $str value using $_GET method and construct the query. then run that query and echo the data. after that, you can call this function in the script file after alert().
function useHttpResponse() {
if (http.readyState == 4) {
if(http.status == 200) {
var txt = http.responseText;
var response_msg="<h4><span class='darkblue'>" + txt + "</span></h4>"
document.getElementById('showtime').innerHTML = response_msg;
}
} else { //you may skip this else portion
document.getElementById('showtime').innerHTML = '<img src="images/loading.gif" /><span class="darkblue">retrieving data...</span>';
}
}
here your fetched data will show on a div with id "showtime". during the fetching the time a loading gif will be visible in the "showtime" div. or you may skip that else portion.
hope that function will help you.

Related

How to display hidden field in a form after ajax response

I have this form which has one select field for main-category, one select field for sub-category and a hidden field. This hidden field is only displayed when a specific value chosen from sub-category.
This sub-category options are the result of ajax response from main-category.
Here is the form:
<form>
<select id='main-cat' name='maincat' onchange="sortSubcat(this.value)"/>
<option value="">Please select one category</option>
<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
</select>
<div id='subcat-more'>
<select id='subcat' name='subcat'>
<option value=''>Please select a subcategory</option>
</select>
</div>
<div id='morefield' style='display:none'>
<input type='text' name='option1'/>
</div>
</form>
I have a Jquery code which handle this form validation, and it tells whether the #morefield is displayed or not. Here is part of this code:
$("#subcat").change(function(){
if (subcat.val() == 'sub-cat-one'){
$("#morefield").css("display","block");
}else{
$("#morefield").hide();
}
});
Unfortunately, Ajax response only displays option on screen however, it did not change in html so when I viewed source code, I don't see any option for sub-cat. Thats why even I chose option sub-cat-one, I would show the div #morefield.
Is there anyway to solve this problem?
Best Regards,
More informaiton:
Here is my ajax call:
function sortSubcat(str)
{
if (str=="")
{
document.getElementById("subcat").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("subcat").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/member/sortsubcat.php?q="+str,true);
xmlhttp.send();
}
Here is the php file:
<?php
require_once("../configs/dbconnect.php");
if (!empty($_GET['q'])){
$q = basename($_GET['q']);
$sql="SELECT * FROM subcat WHERE maincat=:q";
$result = $conn->prepare($sql);
$result->bindParam(':q', $q);
$result->execute();
echo "<option value=''>Please select a sub cat</option>";
foreach($result as $row)
{
echo "<option value='$row[name]'>$row[name]</option>";
}
}
else{
echo "<option value=''>Please select a subcat</option>";
}
$conn=null;
?>
You have to use
if ($(this).val() == 'sub-cat-one'){
instead of
if (subcat.val() == 'sub-cat-one'){
to access the correct html element (#subcat) in your onchange eventhandler.
You also shouldn't use the id subcat for more than one element. Currently the div and the select are having id subcat.
You have two elements ( div and select ) with same id subcat. id attribute should be unique for all elements .
I think you should try below suggestions:
Use AJAX success callback instead of using onchange.
if ($(this).val() == 'sub-cat-one')
I think I see where your problem is coming from, on each iteration you echo the result. And only that result gets returned to your ajax script. Do this in your php file:
$returned_string = '[';
foreach($result as $row)
{
$returned_string .= '{"name" : "'. $row[name]. '", "value" : "'. $row[name]. '"},';
}
$returned_string = substr($returned_string, 0, -1); //remove trailing ','
$returned_string .= ']';
header("Content-type: application/json");
echo $returned_string;
exit;
Then in your successCallback function:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = JSON.parse(xmlhttp.responseText);
var selectElement = document.getElementById('subcat');
for(var i = 0; i < response.length; i++)
{
var idx = i+1;
selectElement.options[idx] = new Option(response[idx].value, response[idx].name, false, false);
}
}
}
}

Retrieve HTML drop down list value with AJAX

I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];

Passing this.value to an AJAX javascript function which contains white spaces, not returning any results

I have drop down menu that is populated with different US states. When the user selects different states, it sends this.value to an ajax function that populates another drop down menu filled with the different cities within that state.
The good news is that it works... for the most part. however when I select a state with 2 words such as "New York", it doesnt find anything. I recon its because there is a white space in the middle. therefore this.value is actually passing only "New" and not "New York". Below is my PHP code and AJAX function. can anyone tell me what i have missed here?! thanks a million :-)
//if result returns a value
if ($result != NULL){
$row = mysql_fetch_assoc($result);
$countryCode = $row['Code'];
if ($countryCode != NULL){
$sql = "SELECT DISTINCT District FROM City WHERE CountryCode = '$countryCode'";
$result = mysql_query($sql);
?>
<select name="state" onchange="getCity('<?=$country?>',this.value)">
<option>Select State</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value="<?=$row['District']?>"><?=$row['District']?></option>
<? } ?>
</select>
<?php
}
}
function getCity(countryId, stateId) {
var strURL="findCity.php?country="+countryId+"&state="+stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
You should enclose the value in double quotes like this
<option value="<?=$row['District']?>"><?=$row['District']?></option>
The HTML is by default taking first word as a value and the next word as the name of next attribute which doesn't have any value. Enclosing it in quotes will make the whole phrase as single value..

Having ajax trouble when it comes to displaying a selected option

I am terribly failing with an ajax/jquery piece of code I am trying to learn in order to solve a predicament I have.
Below is my ajax:
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
$.post("addstudentsession.php",
{studenttextarea : search_val},
function(data){
if (data.length>0){
$("#studentselect").html(data);
}
});
At the moment I am keeping getting a blank page everytime I load my addstudentsession.php script. This is the only script I am working on so I am not sure if I am suppose to link the ajax to itself. But below is what I am trying to do:
I have a drop down menu below:
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='20'>EWYGC - 10-01-2013 - 09:00</option>
<option value='22'>WDFRK - 11-01-2013 - 10:05</option>
<option value='23'>XJJVS - 12-01-2013 - 10:00</option>
<option value='21'>YANLO - 11-01-2013 - 09:00</option>
<option value='24'>YTMVB - 12-01-2013 - 03:00</option>
</select> </p>
Below I have a Multiple Select box where it displays a list of students that is taking the select assessment from the drop down menu above:
$studentactive = 1;
$currentstudentqry = "
SELECT
ss.SessionId, st.StudentId, st.StudentAlias, st.StudentForename, st.StudentSurname
FROM
Student_Session ss
INNER JOIN
Student st ON ss.StudentId = st.StudentId
WHERE
(ss.SessionId = ? and st.Active = ?)
ORDER BY st.StudentAlias
";
$currentstudentstmt=$mysqli->prepare($currentassessmentqry);
// You only need to call bind_param once
$currentstudentstmt->bind_param("ii",$sessionsdrop, $stuentactive);
// get result and assign variables (prefix with db)
$currentstudentstmt->execute();
$currentstudentstmt->bind_result($dbSessionId,$dbStudentId,$dbStudentAlias,$dbStudentForename.$dbStudentSurname);
$currentstudentstmt->store_result();
$studentnum = $currentstudentstmt->num_rows();
$studentSELECT = '<select name="studenttextarea" id="studentselect" size="6">'.PHP_EOL;
if($studentnum == 0){
$studentSELECT .= "<option disabled='disabled' class='red' value=''>No Students currently in this Assessment</option>";
}else{
while ( $currentstudentstmt->fetch() ) {
$studentSELECT .= sprintf("<option disabled='disabled' value='%s'>%s - %s s</option>", $dbStudentId, $dbStudentAlias, $dbStudentForename, $dbStudentSurname) . PHP_EOL;
}
}
$studentSELECT .= '</select>';
But I have a little problem, I need a way to be able to display the list of students in the select box when the user has selected an option from the drop down menu. The problem with the php code is that the page has to be submitted to find its results.
So that is why I am trying to use ajax to solve this but what am I doing badly wrong?
Try using ajax call as following,
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
XMLHttpRequestObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
XMLHttpRequestObject = false;
}
}
}
$('#sessionsDrop').change( function(){
var search_val = $(this).val();
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", "addstudentsession.php", true);
XMLHttpRequestObject.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
}
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4
&& XMLHttpRequestObject.status == 200) {
y = XMLHttpRequestObject.responseText;
$("#studentselect").html(y);
}
};
};
XMLHttpRequestObject.send("studenttextarea=" + search_val);

Problem updating select tag with ajax on IE

I have a problem with inner html funcion when updating tag options. In the first select tag I am chosing a country and ajax code must update cities in the other select tag. My code works in all major browsers except IE. Here is the js code for calling php script:
>function show_zones(str)
>{
>if (window.XMLHttpRequest)
> {// code for IE7+, Firefox, Chrome, Opera, Safari
> xmlhttp=new XMLHttpRequest();
> }
>else
> {// code for IE6, IE5
> xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
> }
>xmlhttp.onreadystatechange=function()
> {
> if (xmlhttp.readyState==4 && xmlhttp.status==200)
> {
> document.getElementById('region_to').innerHTML="";
> jQuery.noConflict();
> (function($) {
> $('#region_to').append(xmlhttp.responseText);
> })(jQuery);
> alert(xmlhttp.responseText);
> }
> }
>xmlhttp.open("GET","ajax/zones.php?country="+str,true);
>xmlhttp.send();
>}
In all browsers alerted code returns appropriate option tags but in IE it returns "Undifined". I am using Jquery to append xmlhttp.responseText because IE does not support innerhtml for select tags. noConflict function is used to avoid conflict between mootolls and jquery libraries. I can`t just place select tag in a div and print it instead of printing just options because I am using custom select which is being created by js code when the window.onload event occurs.
here is the php code:
>require_once("../../connect.php");
>$country_query="SELECT* FROM `tour_countries` WHERE >country_name='".$_GET['country']."'";
>$country_result=mysql_query($country_query);
>$country_row=mysql_fetch_array($country_result);
>$zone_query="SELECT* FROM `tour_zones` WHERE country_ID='".$country_row[0]."'";
>$zone_result=mysql_query($zone_query);
>while($zone_row=mysql_fetch_array($zone_result))
>{
> echo '<option value="'.$zone_row[1].'">'.$zone_row[1].'</option>';
>}
Thanks for replys and sorry for my poor englesh.
I had the same issue with IE and .innerHtml() with ajax calls. I solved it by making the AJAX a POST request and using jQuery .html() instead of .innerHTML(), for some reason IE is pretty glitchy with innerHtml(). Here's the working function I used:
function getCitiesFromState(state, select, spinnerNum)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var ran = Math.round((new Date()).getTime() / 1000),
terms = "state="+state+'&r='+ran;
xmlhttp.open("POST","ajax5.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
/***********************************************************
* These two lines cause Chrome to throw non-fatal errors.
* Removing them didn't change the functionality of the
* request, but this may end up needing a conditional.
***********************************************************/
//xmlhttp.setRequestHeader('Content-length', terms.length);
//xmlhttp.setRequestHeader('Connection', 'close');
xmlhttp.onreadystatechange = function()
{
$('#spinner'+spinnerNum).fadeIn(300);
if (xmlhttp.readyState == 4
&& xmlhttp.status == 200)
{
$('#spinner'+spinnerNum).fadeOut(100);
$('#'+select).html(xmlhttp.responseText);
}
}
xmlhttp.send(terms);
}
And the ajax5.php file:
<?php
include 'db.class2.php';
$DB = new DB_MySql2;
$DB->connect();
$state = mysql_real_escape_string($_POST['state']);
$q = $DB->query("SELECT DISTINCT `city`, `zip_code`
FROM `usa_master`
WHERE `state` = '".$state."'
GROUP BY `city`
ORDER BY `population` DESC LIMIT 0, 150");
while($r = $DB->fetch_assoc($q)) {
$city[] = $r['city'];
$zips[] = $r['zip_code'];
}
array_multisort($city, $zips);
echo '<option value="" selected="selected">Select City</option>';
$size = sizeof($city);
for ($x = 0; $x < $size; $x++)
{
if (strlen($zips[$x]) == 4)
{
$zips[$x] = '0' . $zips[$x];
}
echo '<option class="city_list" value="'.$zips[$x].'">'.$city[$x].'</option>';
}
?>
Hope this helps.

Categories