Using PHP variable in JavaScript for Google Maps V2 - php

i am currently on a Google Map Version 2 (sorry using the old version and please do not suggest me to use V3 instead because this is our requirement). Basically, this page should allow the user to add a place and select the type of that place (e.g. restaurant, bar, school, etc.). These information will be added in the database and will be used for toggling. Adding the place is working now and requires to be redirected to another php page (testmap.php) so that it will display the markers in the map. But toggling needs the information from the type selected in a dropdown list. My problem is that I do not know how to "associate" the type with each marker. I do not know how to transfer the data from the "type" dropdown list.
P.S.
The fourth to the last line is the code where the address data is transferred in my addNewMarker function onSubmit.
The PHP code above it is the dropdown list which contains the possible values of the "types" as explained above.
To conclude, I need actual codes on how to get the marker type from the dropdownlist and be transferred together with the addNewMarker function so that testmap.php can use the values in the database and can be easily toggled.
Thank you so much for those who will help me!
<script type="text/javascript">
if(GBrowserIsCompatible()) {
map_compatible = true;
}
/* Initialize the map this will be called when the document is loaded from: <body onLoad="initialize_map();"> */
function initialize_map() {
if( map_compatible ) {
}
function addNewMarker(newAddress){
var set;
var lat;
var longi;
if(set==null){
set=1;
geocoder = new GClientGeocoder();
geocoder.getLatLng(newAddress, function(point){
if(!point){
alert(address + " not found");
}else{
lat = point.y;
longi = point.x;
alert("The latitude of " + newAddress + " is " + lat + " and longitude is " + longi);
default_address.push([latitude,longitude]);
location.href="testmap.php?lat="+lat+"&longi="+longi+"&set="+set+"&newAdd="+newAddress;
}
});
}
}
function getType(type){
//markertype = type;
document.write("Hello");
}
</script>
</head>
<body onLoad="initialize_map();">
<div id="main-wrapper">
<div id="main-padding">
<div id="map_canvas"></div>
<form name="markertype_form" method = "POST" action = "addMarker.php" class="form">
<?php
#$submit = $_POST['view'];
$selectedtype = '';
if(isset($_GET)){
$connect = mysql_connect("localhost","root","abc123");
mysql_select_db("mapping");
$query="SELECT id,typename FROM markertypes ORDER BY typename";
$result = mysql_query ($query);
echo "<select name='types'>";
$types = strip_tags(#$_POST['types']);
echo "<option disabled>---------------------Select---------------------</option>";
while($nt=mysql_fetch_array($result)){
$selected = false;
// check if the current value equals the value submited
if($_POST['types'] == $nt['id']){
$selected = true;
$selectedtype = $nt['typename'];
}
// show selected attribute only if $selected is true
echo "<option value='{$nt['id']}' ". ($selected ? "selected" : "") .">{$nt['typename']}</option>";
}
echo '</select>';
echo "</select>";
echo "<input type='submit' name ='view' value='View Details'>";// Closing of list box
echo '<br>';
}
?>
</form>
<form name="direction_form" onSubmit="addNewMarker(this.new_address.value); return false;" class="form">
Add markers? Enter the address and we will mark it for you: <input type="text" name="new_address" class="form-field" /><br /><br />
<input type="submit" value=" Mark this place! " class="form-submit" />
</form>

If you put an id on the types select box in your php, then you could add some lines of code to your javascript above.
Below is assuming the "types" select element has an id of "marker-type":
function addNewMarker(newAddress){
var set;
var lat;
var longi;
var e = document.getElementById("marker-type");
var mtype = e.options[e.selectedIndex].value;
if(set==null){
set=1;
geocoder = new GClientGeocoder();
geocoder.getLatLng(newAddress, function(point){
if(!point){
alert(address + " not found");
}else{
lat = point.y;
longi = point.x;
alert("The latitude of " + newAddress + " is " + lat + " and longitude is " + longi);
default_address.push([latitude,longitude]);
location.href="testmap.php?lat="+lat+"&longi="+longi+"&set="+set+"&newAdd="+newAddress+"&type="+mtype;
}
});
}
}
Please note above, that in the AddMarker function I added a new variable for "mtype" which selects the select box and gets the current option value.
Then below, where the API calls testmap.php I added the type selector and gave it the value for the "mtype" var.
Later in your testmap.php code, you just follow on by getting using:
$_GET['type']

Related

Adding html form fields from user input

I have a form that asks a user to give a device type a name and say how many attributes they would like to assign to that device type. That form calls the below php files which uses a loop to create the desired number of attributes.
I have used the name="attribute".$i in order to be able to identify each attribute on the next php page to send the information to a database.
<?php echo $_POST['device-name']; ?>
<?php
$num=$_POST['number-of-attributes'];
$num=intval($num);
for($i=0; $i<$num; $i++) {
newAttribute($i);
}
function newAttribute($i) {
echo ("<div id=\"new-attribute\">");
echo ("<h3>New Attribute</h3>");
echo ("<label for=\"attribute".$i."\">Name</label>");
echo ("<input id=\"attribute\" type=\"text\" name=\"attribute".$i."\">");
echo ("</div>");
}
?>
However I also want the user to be able to click for example:
<div id="small-button">New Attribute</div>
and create another set of fields to define an attribute.
How would I do this?
Thanks in advance
Using javascript/jquery on the client-side:
var template = "<div class=\"new-attribute\">"
+ "<h3>New Attribute</h3>"
+ "<label for=\"attribute\">Name</label>"
+ "<input id=\"attribute\" type=\"text\" name=\"attribute\">"
+ "</div>";
$(document).ready(function() {
// The DOM has loaded
$("#small-button").on('click', function() {
// The user clicked your 'New Attribute' button
// Append a new attribute to the <body> with `template` we defined above:
$(body).append(template);
});
});
Note: I changed id="new-attribute" to class="new-attribute" since there will be more than 1.
You would need JavaScript for said job. In your HTML document, at the end of the body element add the following script element:
<script type="text/javascript">
var numberOfAttributes = 1;
function newAttributeFields(e) {
// Creates the div
var div = document.createElement('div');
div.id = 'new-attribute';
// Appends the fields
div.innerHtml = '<h3>New attribute</h3><label for="attribute' + numberOfAttributes + '">Name</label><input id="attribute" type="text" name="attribute' + numberOfAttributes + '">';
// Appends it to the body element
document.getElementsByTagName('body')[0].appendChild(div);
// Increments the number of attributes by one
numberOfAttributes = numberOfAttributes + 1;
}
var smallButton = document.getElementById('small-button');
// When the 'small button' is clicked, calls the newAttributeFields function
smallButton.addEventListener('click', newAttributeFields, false);
</script>

transfer value of textbox to php variable

Hi I am creating a wordpress plugin and i am a little bit stack here. there's text box number 1 which is the order number and number 2 which is the order name. This is what i want. If the customer enters a number in textbox number 1 which is order number, the value he or she entered will check into the database and get the corresponding order name of that order number. Its realtime. No need to submit before it appears. Everytime they input something it will immediate check to the database and display it in text box number 2(order name). I research this and try using ajax in wordpress but i dont know how to use. Thanks.
Here's some boilerplate code to get you started....
<script type="text/javascript" charset="utf-8">
var req;
function handler_orderNumberField_onchange(fld) {
var text = fld.value;
if (text.length == 8) {
queryForOrderName(text);
}
}
function queryForOrderName(orderNumber) {
document.getElementById('orderNameField').value = "Please wait..."
req = new XMLHttpRequest();
var url = "http://www.mydomain.com/getordername.php?ordernumber=" + orderNumber;
req.onreadystatechange = function() {
var field = document.getElementById('orderNameField');
var rs = this.readyState;
var status = this.status;
if (rs == 4 && status == 200) {
field.value = req.responseText;
}
};
req.ontimeout = function() {
document.getElementById('orderNameField').value = 'Timeout.';
}
req.timeout = 10000;
req.open("GET", url, true);
req.send();
}
</script>
<p>Order Number: <input type="text" name="orderNumber" value="" id="orderNumberField" onchange="handler_orderNumberField_onchange(this)"></p>
<p>Order Name: <input type="text" name="orderName" value="" id="orderNameField"></p>
Note that you need to implement a getordername.php script yourself; example:
<?php
$ordernr = (int) $_GET["ordernumber"];
$result = sprintf("Testorder - Order Number %d", $ordernr);
header("Content-type: text/plain; charset=UTF-8");
echo $result;
exit;
?>

php with jquery html pop up

this is actually a part of huge project so i didnt include the css but im willing to post it here if actually necessary.
Ok i have this code
<html>
<head>
<script src="js/jquery.js"></script>
<script type="text/javascript">
var q = "0";
function rr()
{
var q = "1";
var ddxz = document.getElementById('inputbox').value;
if (ddxz === "")
{
alert ('Search box is empty, please fill before you hit the go button.');
}
else
{
$.post('search.php', { name : $('#inputbox').val()}, function(output) {
$('#searchpage').html(output).show();
});
var t=setTimeout("alertMsg()",500);
}
}
function alertMsg()
{
$('#de').hide();
$('#searchpage').show();
}
// searchbox functions ( clear & unclear )
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (q === "0"){
if (thisfield.value == "") {
thisfield.value = defaulttext;
}}
else
{
}
}
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var q = "0";
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#pxpxx').html(output).show();
});
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
</script>
</head>
<body>
<input name="searchinput" value="search item here..." type="text" id="inputbox" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><button id="submit" onclick="rr()"></button>
<div id="searchpage"></div>
<div id="backgroundPopup"></div>
<div id="popup" class="popup_block">
<div id="pxpxx"></div>
</div>
</body>
</html>
Ok here is the php file(search.php) where the jquery function"function rr()" will pass the data from the input field(#inputbox) once the user click the button(#submit) and then the php file(search.php) will process the data and check if theres a record on the mysql that was match on the data that the jquery has pass and so if there is then the search.php will pass data back to the jquery function and then that jquery function will output the data into the specified div(#searchpage).
<?
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='http://".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
}
else
{
echo "Yay! There's an error occured upon checking your request";
}
?>
and here is the php file(tt.php) where the jquery a.poplight click function will pass the data and then as like the function of the first php file(search.php) it will look for data's match on the mysql and then pass it back to the jquery and then the jquery will output the file to the specified div(#popup) and once it was outputted to the specified div(#popup), then the div(#popup) will show like a popup box (this is absolutely a popup box actually).
<?
//session_start(); start up your PHP session!//
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
while($row = mysql_fetch_array($result))
{
$ss = "<table border='0' align='left' cellpadding='3' cellspacing='1'><tr><td>";
$ss .= '<img class="ddx" src="Images/media/'.$row['name'].'" />'."</td>";
$ss .= "<td>"."<table><tr><td style='color:#666; padding-right:15px;'>Name</td><td style='color:#0068AE'>".$row['title']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Description</td> <td>".$row['description']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Link</td><td><a href='".$row['link']."'>".$row['link']."</a></td></tr>";
$ss .= "</td></tr></table>";
}
echo $ss;
mysql_close($con);
}
?>
here is the problem, the popup box(.popup_block) is not showing and so the data from the php file(tt.php) that the jquery has been outputted to that div(.popup_block) (will if ever it was successfully pass from the php file into the jquery and outputted by the jquery).
Some of my codes that rely on this is actually working and that pop up box is actually showing, just this part, its not showing and theres no data from the php file which was the jquery function should output it to that div(.popup_block)
hope someone could help, thanks in advance, anyway im open for any suggestions and recommendation.
JULIVER
First thought, the script is being called before the page is loaded. To solve this, use:
$(document).ready(function()
{
$(window).load(function()
{
//type here your jQuery
});
});
This will cause the script to wait for the whole page to load, including all content and images
if you're using ajax to exchange data into a php file. then check your ajax function if its actually receive the return data from your php file.

Ajax Live Search - Get 2 Fields instead of 1

I have a small problem, I want to a live search that returns me a POST_TITLE and a POST_ID. the title is for the people to see but my main reason is that I want the POST_ID to work with it.
Can someone help me, I posted the code below...
<script>
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = escape(document.getElementById('txtSearch').value);
searchReq.open("GET", '/wp-content/themes/twentyten/livesearch.php?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var sx = document.getElementById('restaurantid')
sx.innerHTML = '';
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
ss
}
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('restaurantid').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
</script>
<form id="frmSearch" action="">
<input type="text" id="restaurantid" name="restaurantid" style="display: none;" />
<input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
<input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" />
<div id="search_suggest"></div>
</form>
</code>
livesearch.php - THE AJAX PAGE
<code>
<?php
$con = mysql_connect('x', 'x', 'x);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx", $con);
if (isset($_GET['search']) && $_GET['search'] != '') {
//Add slashes to any quotes to avoid SQL problems.
$search = addslashes($_GET['search']);
//Get every page title for the site.
$suggest_query = mysql_query('SELECT * FROM `mrr_posts` WHERE `post_title` LIKE \'%'.$search.'%\' AND `post_status` LIKE \'publish\' LIMIT 0, 30') or trigger_error("Query: $suggest_query\n<br />MySQL Error: " .mysql_error());
while ($suggest = mysql_fetch_array($suggest_query, MYSQL_ASSOC)) {
//while($suggest = db_fetch_array($suggest_query)) {
//Return each page title seperated by a newline.
echo $suggest['post_title'] . "\n";
}
}
mysql_close($con);
?>
I noticed in the discussion above you're returning JSON now, and parsing it from the client side. And I noticed you tagged your question with jQuery, so I guess you're using that. This isn't an answer to your question, but here are some tips for javascript coding with jQuery that will help simplify your code a ton.
instead of doing your ajax calls using the XMLHttpRequest object directly, just use $.get(url, successFunction)
instead of using getElementById('some-id'), use $('#some-id'), then to do things like empty out the inner html, you can do $('#some-id').html(''). Using the jQuery element instead of HTMLElement, you can also manipulate the DOM in a cross-browser compatible way: http://api.jquery.com/category/manipulation/
instead of building your javascript into your HTML (all those onmouseover and onmouseout handlers), use $('div.suggest_link') to select all divs on the page that have a class of "suggest_link". Then, attach a live event handler which will work on dynamically generated html, like this: $('div.suggest_link').live('mouseover', handleMouseOverForSuggestLink). You can read more about this on jQuery's page: http://api.jquery.com/live/
All these suggestions will work in modern browsers, and will help cut down a lot of code. Good luck!
You should return data from server in JSON (or XML, but JSON is easier), and then parse it in Javascript. Show titles to user, id keep for yourself.
In general xajax might simplify things quite much. Have a look at my answer here:
how to assign a javascript variable to a smarty variable

Passing PHP variable to Javascript dynammically added textbox

i have a javascript function like this:
function addfamily(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<input type="text" name="family[]" size="16">';
document.getElementById(divName).appendChild(newdiv);
}
which dynamically adds textbox to the form and a php script like this:
<?php
$result_family = mysql_query("SELECT * FROM family_member where login_id='$_SESSION[id]'");
$num_rows_family = mysql_num_rows($result_family);
if ($num_rows_family>0) {
while($row_family = mysql_fetch_assoc($result_family)){
echo "<script language=javascript>addfamily('family');</script>";
}
}
having this code the textboxes are added fine.
i just need to know how can i set a dynamic value as the textbox value by passing the php variable $row_family[name] to the function and the value of the textbox???
please help
Since you want to pass the name of the Div along with $row_family['name'] your javascript function should look like
function addfamily(divName,familyName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<input type='text' name='family[]' size='16' value=" + familyName + ">";
document.getElementById(divName).appendChild(newdiv);
}
and then the call from PHP should be like
echo "addfamily('family',$row_family['name']);";
HTH

Categories