Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Here's the background info for my question: I'm selecting data from an SQL table, which has the columns "ID (osm_id)", "Names" and "Coordinates (way)" with around 300 entries each. I got a dropdown menu to work displaying all the possible names of pubs (they are in column "Names").
Now I wanna get the coordinates of a selected pub and have those displayed on the page.
Here's my code so far:
<?php
...
$query = "SELECT osm_id, name, ST_asText(ST_transform(way,4326)) FROM planet_osm_polygon WHERE amenity LIKE 'pub' ORDER BY name ASC;";
$result = pg_query($query) or die("Query error: " . pg_last_error());
?>
<select id="pub_select" name="pub_select" size="1">
<option value="">--- Select a Pub ---</option>
<?php
$options='';
while($line = pg_fetch_row($result))
{
$pub_id = $line[0];
$pub_names = $line[1];
$way_coords = $line[2];
$options.="<option value='" . $pub_names . "'>$pub_names</option>";
echo $options;
}
pg_free_result($result);
pg_close($dbconn);
?>
</select>
<input type="submit" name="submit" value="Get building coordinates" />
My tutor suggested that I could use:
<select id="pub_select" name="pub_select" size="1" onchange="getMoreInfo()">
and call a function getMoreInfo() in order to do the detailed query (Pub ID -> Pub coordinates) and use pub_select = document.getElementById('pub_select'); for the ID in Javascript/Ajax-Call of my php code and basically filter with the ID to get the coordinates. But I dont know how to do that :/
EDIT:
So, basically my question is: I have a database table, I choose a pub from a drop down menu. How do I get further information from the same table, like the coordinates from the corresponding column.
You could modify the HTML you generate slightly to include a dataset attribute for each option in the select menu.
The Javascript event handler getmoreinfo will read that dataset attribute and use it in part of an ajax request to some backend php script that will fetch more results from the db.
<select id='pub_select' name='pub_select' size='1' onchange='getmoreinfo(e)'>
<option selected disabled hidden>--- Select a Pub ---
<?php
while( $line = pg_fetch_row( $result ) ){
printf(
'<option value="%s" data-latlng="%s">%s',
$line[0],
$line[2],
$line[1]
);
}
?>
</select>
A simple version of what you might use in the getmoreinfo function to send an ajax request using the fetch api.
<script>
function getmoreinfo(e){
/* choose the correct path for backend script */
let baseurl='/path/to/backend/script.php';
/* create the request payload */
let args={
'latlng':e.target.dataset.latlng,
'id':e.target.value
};
/* generate the full url & querystring for the GET request */
let url=baseurl + '?' + Object.keys(args).map(key=>{
return [ encodeURIComponent(key), encodeURIComponent(args[key]) ].join('=')
}).join('&');
/* issue the ajax request */
fetch( url )
.then( r=>r.text() )
.then( text=>{
/* process the final response here */
alert( text )
})
}
</script>
A pseudo-code version of the backend script that the ajax request is sent to... this is pseudo code and untested.
<?php
# /path/to/backend/script.php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset(
$_GET['latlng'],
$_GET['id']
)){
$latlng=$_GET['latlng'];
$id=$_GET['id'];
$sql='select from sometable where id=? and latlng=?';
$stmt=$dbo->prepare($sql);
#... etc
}
?>
To clarify a few things. You can pass the selected value from the select element i.e.
<select id="pub_select" name="pub_select" size="1" onchange="getMoreInfo(this.value)">
In the Javascript code you would have
<script>
function getMoreInfo( value ) {
...
}
If you do not have to use AJAX to get the results you can plug this info into the option value i.e.
while($line = pg_fetch_row($result)) {
$data = implode( "|", $line );
$pub_names = $line[1];
echo "<option value='" . $data . "'>$pub_names</option>";
}
This will but the | delimiter between each piece of data.
In your JavaScript function you would extra it by:
<script>
function getMoreInfo( value ) {
var data = value.split("|");
}
To sent the information out to the web page you need an element where you can display the data. Use a div i.e.
<div id='results'></div>
Now put your data into the div i.e.
<script>
function getMoreInfo( value ) {
var data = value.split("|");
document.getElementById('results').innerHTML = "Name : "+data[1]+"<br>Co-ords : "+data[2];
}
If you have to use AJAX then things get a lot more complicated.
Related
According to the official Contact Form 7 docs, it is possible to pass a a default value to CF7 from the shortcode, in this way:
// field in CF7 in Wordpress admin area
[email* destination-email default:shortcode_attr]
// shortcode in a Wordpress php template
[contact-form-7 id="123" title="Contact Form" destination-email="xxxxxx#example.com"]
// function in functions.php
add_filter( 'shortcode_atts_wpcf7', 'custom_shortcode_atts_wpcf7_filter', 10, 3 );
function custom_shortcode_atts_wpcf7_filter( $out, $pairs, $atts ) {
$my_attr = 'destination-email';
if ( isset( $atts[$my_attr] ) ) {
$out[$my_attr] = $atts[$my_attr];
}
return $out;
}
This works for a simple text field, but I need to pass an array of values to a <select> field and use them as <option>s inside it; I've tried to modify a bit this code, but apparently it isn't working, or at least I've not been able to.
Is it possible to use the shortcode to send dynamic data to CF7 even if not a single plain text like this?
If not, I'm open to every other kind of solution, even if it involves another method, or some additional plugin; is there some other way to dynamically send an array of values to <select> fields in Contact Form 7?
These values are data queried from the database (such as post names, custom fields, and so on), so they need to come from php first even if there is a solution that involves javascript.
Here's an example of a form tag I've used for getting US States. This is a <select> generated from an array. This is probably more along the lines of what you want to do.
You can see that I also use the usermeta billing_state to pre-select the choice.
With that said, you should also be able to use this same method to create a select tag that performs any WP_Query and puts the results into an option tag.
<?php
add_action('wpcf7_init', function (){
wpcf7_add_form_tag( array('dd_states', 'dd_states*'), 'cf7_state_dropdown' , true );
});
function cf7_state_dropdown($tag) {
$tag = new WPCF7_FormTag( $tag );
$atts = array();
$validation_error = wpcf7_get_validation_error( $tag->type );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts['class'] = $tag->get_class_option( $class );
$atts['aria-required'] = 'true';
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$atts = wpcf7_format_atts( $atts );
// Get User ID and Billing State from DB
$userid = get_current_user_id();
$user_state = get_user_meta($userid, 'billing_state', true);
$states = array ( 'FL'=>'Florida','AL'=>'Alabama','AK'=>'Alaska','AZ'=>'Arizona','AR'=>'Arkansas','CA'=>'California','CO'=>'Colorado','CT'=>'Connecticut','DE'=>'Delaware','DC'=>'District of Columbia','GA'=>'Georgia','HI'=>'Hawaii','ID'=>'Idaho','IL'=>'Illinois','IN'=>'Indiana','IA'=>'Iowa','KS'=>'Kansas','KY'=>'Kentucky','LA'=>'Louisiana','ME'=>'Maine','MD'=>'Maryland','MA'=>'Massachusetts','MI'=>'Michigan','MN'=>'Minnesota','MS'=>'Mississippi','MO'=>'Missouri','MT'=>'Montana','NE'=>'Nebraska','NV'=>'Nevada','NH'=>'New Hampshire','NJ'=>'New Jersey','NM'=>'New Mexico','NY'=>'New York','NC'=>'North Carolina','ND'=>'North Dakota','OH'=>'Ohio','OK'=>'Oklahoma','OR'=>'Oregon','PA'=>'Pennsylvania','RI'=>'Rhode Island','SC'=>'South Carolina','SD'=>'South Dakota','TN'=>'Tennessee','TX'=>'Texas','UT'=>'Utah','VT'=>'Vermont','VA'=>'Virginia','WA'=>'Washington','WV'=>'West Virginia','WI'=>'Wisconsin','WY'=>'Wyoming');
$output = '<span class="wpcf7-form-control-wrap '.sanitize_html_class( $tag->name ).'"><select name="state" id="state" '.$atts.'>';
$output .= "<option value=\"\"> - - Choose State - - </option>";
foreach ($states as $abbrev=>$state){
$selected = ($user_state == $abbrev) ? ' selected="selected"' : '';
$output .= '<option value="'.$abbrev.'"'. $selected .'>'.$state.'</option>';
}
$output .= "</select></span>";
$output .= $validation_error;
return $output;
}
I need to get the value of the selected item on the drop down selection populated from sql database. Then that value is needed in the sql statement to get the specific record.
I already populated the drop down selection. Code below
<select name="year" id="year">
<?php
$query = mysql_query("SELECT distinct Year(fromdate) FROM emp WHERE empcode='$emp' order by Year(fromdate) desc");
while ($row = mysql_fetch_array($query)){
$year = $row[0];
echo "<option value=\"".$year."\">".$year."</option>";
}
?>
</select>
This is the php code for me to get the record using the value from the drop down.
<?php
$sql = mysql_query("SELECT salary FROM emp WHERE empcode='$emp' and Year(fromdate) = '$year'");
$row = mysql_fetch_array($sql);
$salary=$row[0];
?>
Then after that I need to pass the result to a textbox
<input id="salary" name="salary" value="<?php echo $salary; ?>">
What is the code needed for me to pass the selected item value from drop down "year" to PHP variable $year for sql statement? I already looked here in Stack Overflow for the answers but there is no question that look like mine.
What is wrong with people it needs sql why vote down
Do an ajax call to your php file, listening to your select onchange event, like so:
$('#year').on('change', function() {
$.post( "path/file.php", {
year: $(this).val()
})
.done(function( data, status ) {
console.log('data: '+data+' status: '+status);
if(status == 'success'){
//pass to your input ?
//data is what your php file will echo/output
$('#salary').val(data);
}else{
//how do you want to handle http error ?
}
});
});
If you want to get select box value without refreshing page then you need to do code with AJAX.
http://api.jquery.com/jquery.ajax/
On change please pass the year value to AJAX and then in AJAX file write down query for salary getting and after success full result put this value in salary filed using jQuery function
I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns on index.php:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Collector Name'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
Code that runs each time the dropdown is changed in script tags on index.php:
function showUser(str) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('billing_table');
sorttable.makeSortable(newTableObject);
}
}
// ---- Gets value of collector dropdown selection -----
var e = document.getElementById("collector").value;
$.ajax({
type: 'GET',
url: 'index.php',
data: e,
success: function(response) {
console.log(e);
}
});
// ---- Gets value of the current selection in any of the dropdowns ----
xmlhttp.open("GET","dropdown-display.php?q="+str,true);
xmlhttp.send();
document.getElementById('billing_table').style.display = 'none';
}
$(document).ready(function(){
var $select1 = $( '#collector' ),
$select2 = $( '#date' ),
$options = $select2.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $options.filter( '[value="' + this.value + '"]' ) );
}).trigger( 'change' );
});
Query on my index.php page:
$collector = "SELECT [Collector Name]
FROM [vSpecial_Billing]
Group By [Collector Name]";
$billdate = "SELECT [Collector Name], [Date]
FROM [vSpecial_Billing]
Group By [Collector Name], [Date]";
I don't want to send the value to my dropdown-display.php page since my queries that populate the dropdowns are on my index.php page. However, if I put the value variable in the query, then it runs that query on load before a collector selection can be made and my bill date dropdown will then not be populated.
EDIT:
I changed the value in the options for the date dropdown to Collector Name instead of Date
I also added the $(document).ready(function() at the end of the middle block of code
I updated the queries that I am using
It filters correctly now, however, on page load, the bill date is unable to selected. It is not populated with any rows. How can I change this?
Also, when I filter it, it defaults to the last date on the list. How can I get it to default to a hardcoded value such as "Date" and then the user can select from the filtered values?
I wrote up a test case, using some example data, and made sure this works. Its a rough example, but I believe its doing what you need. With a lot less cruft in the works. I'm sorry, but I used full jquery, because I cannot be bothered to do long-hand javascript anymore haha (plus I couldn't really follow what you had going on in there).
There will need to be two files: index.php and index-ajax.php (for clarity)
index.php brief:
// note: these do not need to be in prepared statements (theres no variables inside)
$collect = $db->query("SELECT DISTINCT [Collector Name] FROM [vSpecial_Billing]");
$names = $collect->fetchAll();
$billdate = $db->query("SELECT DISTINCT [Date] FROM [vSpecial_Billing]");
$dates = $billdate->fetchAll();
?>
<form id="testForm" action="">
<select id="collector">
<option value="" selected="selected" disabled="disabled">Collector Name</option>
<?php foreach($names as $name) { ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date">
<option value="" selected="selected" disabled="disabled">Bill Date</option>
<?php foreach($dates as $date) { ?>
<option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
<input type="button" id="clearchoices" name="clearchoices" value="Clear Choices" />
</form>
Some things to note in the above:
You only need to select by DISTINCT. No need to do GROUP BY to get all unique names, or all unique dates.
I put the results of fetchAll into variables, out of habit, but you can move them into the foreach if you wish.
I removed the class defines you had, because a class with spaces in it (in the case of a Collector Name) can be buggy.
The Clear Choices button is just an example of how to reset those selects after they get filtered and filtered beyond what you can select.
This is the javascript portion (it goes in index.php before or after your form, or in the head):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#collector").change(function(e){
$.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
$("#date .choice").hide();
$.each(data, function(key,row) {
// $("#date option[value='"+ row.item +"']").show();
$("#date option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#date").change(function(e){
$.post('index-ajax.php',{filter:'Date',by:$(this).val()},function(data){
$("#collector .choice").hide();
$.each(data, function(key,row) {
// $("#collector option[value='"+ row.item +"']").show();
$("#collector option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#clearchoices").click(function(e){ e.preventDefault();
$("#collector .choice").show(); $("#collector").val('');
$("#date .choice").show(); $("#date").val('');
});
});
</script>
That block needs a lot of explaining, because I took all your long-hand javascript and packed it into jquery.
Each select has its own handler event for when it changes.
Each select does its own post ajax, with a different variable define to filter on.
After the ajax returns, it hides all options in the OTHER select. Then enables all options which are returned by the json data of the ajax call. This could be handled differently, but I wanted to present one way of doing it.
A key thing is setting "JSON" for the return handler of the .post() methods. You'll see why in index-ajax.php.
And now the index-ajax.php:
if (isset($_POST['filter']) and isset($_POST['by'])) {// sanity check
$results = array();
if (!empty($_POST['by'])) {
// these _DO_ need to be in prepared statements!!!
if ($_POST['filter'] == 'Name') { $sql = "SELECT DISTINCT [Date] as item FROM [vSpecial_Billing] WHERE [Collector Name] = ?"; }
if ($_POST['filter'] == 'Date') { $sql = "SELECT DISTINCT [Collector Name] as item FROM [vSpecial_Billing] WHERE [Date] = ?"; }
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['by']));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $results[] = $row; }
}
echo json_encode( $results );
exit;
}
This bit of code is actually pretty straightforward. All it does is determine which filter operation to do, prepares the sql, and then grabs distinct matching rows for output. The key thing though is it outputs as json, so the javascript that called this can handle the data easier!
Now... I had built all this in a test script, and my server hates "fetchAll", so your milage may vary on some of the DB code. I also left out all other form code and db setup handlers and all that. Figuring you have a handle on that.
I hope this helps you out, in some way or other.
EDIT 11/7
I made a slight change because I didn't realize the Collector Names in your db would have characters that would break all of this, oops. Two changes for odd character handling:
The select for collector has its option values wrapped in htmlspecialchars().
The jquery portion for where each select .change event filters, is now filtering by looking for a matching index, using the row.item as a direct variable. Before, it was using it in a value=' row.item ' match, which if the row.item had single quotes (or other bad chars), it would break the whole js event and fail!
Generally when I setup things like this, I use ID's and unique element id tags. That way I am only ever referencing by numbers, and wont run into odd character mash. An example of switching everything to ID's would be involved, and I think you have the gist of whats going on now.
I'm trying to make a grade distributions website, and I'm creating 4 dropdowns correlating subject (cs, math, etc.), class (data structures, AI, etc.), professor, and quarter the class was taken. After the quarter dropdown is selected, I want to display a bar graph with the data.
The problem I'm running into is that I can't populate the second dropdown with data Basically, I can successfully pull data from the database for the first dropdown, and if the user selects something then the second dropdown (that was originally hidden using jquery) becomes visible, but it isn't properly pulling data from the database and adding it as options to the second dropdown. An example would be that I can select Computer Science from the first dropdown, then the second dropdown is visible, but it doesn't contain 'intro to programming', 'data structures', etc. in it; instead, it's just blank.
FYI, I'm using these selectpickers: http://silviomoreto.github.io/bootstrap-select/
PHP (error is most likely somewhere in the getClasses function, quite possibly the $_POST section of the code):
<?php
function getSubjects()
{
/* Get mysql connect information from external file and connect*/
require_once 'database.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
/* Get the column containing the subjects from the table */
$query = 'SELECT DISTINCT Subject FROM gradelist ORDER BY Subject';
$result = $connection->query($query);
if(!$result) die ($connection_error);
/* Keep track of the number of rows in the column; necessary for iterating */
$rows = $result->num_rows;
/* selectBar keeps track of the html code for the select Bar*/
$selectBar = '';
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Subject'];
$selectBar .= '<option>' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
}
function getClasses()
{
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
if(isset($_POST['subject']))
{
$query = "SELECT DISTINCT Class FROM gradelist WHERE Subject = $subject";
$result = $connection->query($query);
if(!$result) die ($connection_error);
}
else
{
die($connection_error);
}
$rows = $result->num_rows;
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Class'];
$selectBar .= '<option value = "' . $value . '">' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
} ?>
HTML Portion of the code (again, the error might be with the $_POST part of the code) :
<form class="form-horizontal" method = "post" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "subject" id="subject" class="selectpicker show-tick form-control" data-live-search="true" title ="Subject">
<?php echo getSubjects(); ?>
</select>
</div>
</div>
</form>
<form class="form-horizontal" method = "get" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "class" id="class" class="selectpicker show-tick form-control" data-live-search="true" title ="Class">
<?php if(isset($_POST['subject'])) echo getClasses(); ?>
</select>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#class').selectpicker('hide');
$('#professor').selectpicker('hide');
$('#quarter').selectpicker('hide');
});
$('#subject').on('change', function(){
$('#class').selectpicker('refresh');
$('#class').selectpicker('show');
});
$('#class').on('change', function(){
$('#professor').selectpicker('show');
});
$('#professor').on('change', function(){
$('#quarter').selectpicker('show');
});
$('#quarter').on('change', function(){
showTable();
temp = $('#class').selectpicker('val') + " with " + $('#professor').selectpicker('val') + " during " + $('#quarter').selectpicker('val');
$('#displayName').text(temp);
});
Your PHP is executed with $_POST["subject"] not set, and you never POST the subject the user chose to the page; if you don't make an additional POST request, there's no way for the classes to populate.
One way to do it (without changing any of your files) is like so:
$('#subject').on('change', function(){
$.post({
data: { subject: $(this).val() },
success: function (data) {
var classes = $(data).find("#class");
$("#class").replaceWith(classes);
}
});
});
So when a change event is triggered on the subject selection, we'll POST the selected subject to the current page. The response should be the entire document generated with the class selection filled (since $_POST["subject"] is set).
We then replace the current page's #class select element with the version in the generated data (wrapped in $() to create DOM elements from the stringified HTML, so we can use find()).
Another way might be to have files, getSubjects.php, getClasses.php, and so on, and POST individually to them (you make the first request onload, and subsequent requests onchange). This way, you can just append the generated option elements to the select elements on the page.
ALSO: Please please please sanitize $_POST["subject"] before using it in a database query. A user could easily add a fake option to the select locally with a malicious string for value, and you'd unknowingly query the DB with that. You can use prepared statements for this (mysqli has the prepare() function to prepare a statement before querying). More on that and combating SQL injection here.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
UPDATED CODE I am trying to call a PHP scripts in my main PHP file where everything will be displayed. I just want to display the results from my PHP script with the SQL queries that are being run.
Id also like to include the possibility of showing the results dynamically/by not refreshing the page.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
$id = $(this).attr("data")
$("#station_info_"+$id).toggle();
$.ajax({
url:"display_stationinfo.php",
success:function(result){
$("#map_size").html(result);
}});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
echo $_GET['callback'] . '(' .json_encode($html) . ')';
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
You should find out what are the ways in which you can make jquery ajax calls
Other basic tutorial which will help you in ajax is below
http://api.jquery.com/jquery.ajax/
http://www.w3schools.com/jquery/ajax_ajax.asp
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
Since you have not explained clearly the question i am making genral assumption and going to give you two answer on how you can use ajax for your purpose
1.AJAX LOAD
Lets say your HTML structure is
HTML
<div id="map_size" align="center"></div>
MY JS FILE
$(document).ready(function(){
jQuery("#map_size").load("myphp.php", {}, function() { });
})
PHP
echo "<p>THIS IS TEST FOR DEMO AJAX LOAD</p>"
you can do much more if you are retrieving from db.
myphp.php
//get number of rows for X,Y coords in the table
while($row = mysqli_fetch_assoc($coord_result)){
//naming X,Y values
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div id='desk_box' style='style:absolute;
left: " . $x_pos. " px;
top: " . $y_pos. " px;'>box number</div>";
}
you can also do same thing on button click and load everything dynamically without refreshing page
2.Jquery Ajax [GET, POST] : Link
This also can be used
HTML
<div id="map_size" align="center"></div>
MY JS FILE
//http://api.jquery.com/jquery.ajax/
$(document).ready(function(){
$.ajax({url:"myphp.php",success:function(result){
$("#map_size").html(result);
}});
})
myphp.php
//get number of rows for X,Y coords in the table
while($row = mysqli_fetch_assoc($coord_result)){
//naming X,Y values
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
$html = "<div id='desk_box' style='style:absolute;
left: " . $x_pos. " px;
top: " . $y_pos. " px;'>box number</div>";
}
//create a JSON
echo $_GET['callback'] . '(' . json_encode($html ) . ')';