Im having problems passing PHP Strings to Javascript functions, I'v read a number of the post regarding this problem and tried several methods but none of them have worked for me.
basically I have two functions one written in PHP that pulls information from a database and the other written in Javascript designed to allow me to geocode an address for google maps and pass some info to be added to the info window, the two bits of code are shown below:
PHP
try {
$bubbleData = $dbConnection->getBubbleData();
} catch (Exception $e) {
echo "The following error occoured while attempting to get Google map info window data" .
" " . $e->getMessage() .
" " . "In file" .
" " . $e->getLine() .
" " . "on line" .
" " . $e->getLine();
}
if (mysql_num_rows($bubbleData) == 0) {
echo "No Placement data found to populate map";
} else {
while ($row = mysql_fetch_array($bubbleData)) {
$companyName = $row['Company_Name'];
$title = $row['Title'];
$address_1 = $row['Address_Line_1'];
$address_2 = $row['Address_Line_2'];
$address_3 = $row['Address_Line_3'];
$address_4 = $row['Address_Line_4'];
$post_Code = $row['Post_Code'];
$forename = $row['Forename'];
$surname = $row['Surname'];
$fullAddress = $address_1 . " " . $address_2 . " " . $address_3 . " " . $address_4 . " " . $post_Code;
$partAddress_1 = $address_1 . " " . $address_2;
$partAddress_2 = $address_3 . " " . $address_4;
$infoText = "<h4>" . $title . "</h4>" .
'<b>' . "Company name:" . '</b>' . " " . $companyName .
"</br>" .
"<b>" . "Employee name:" . '</b>' . " " . $forename . " " . $surname . '</br>' .
"<b>" . "Company address:" . "</b>" . " " . $partAddress_1 . '</br>' .
$partAddress_2 . '</br>' . $post_Code;
echo "<SCRIPT LANGUAGE='javascript'>
geocodeAddress(<?php echo json_encode($fullAddress);?>,<?php echo json_encode($infoText);?>);
</SCRIPT>'";
}
}
Javascript
function geocodeAddress (address,infoText) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loadMarker(results[0].geometry.location,infoText,address);
latlngArray.push(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " +" "+ status);
}
});
}re
Now I know that the two work fine individually but whenever I try to call the javascript in side the PHP and pass it the variables I ge the following error in firebug:
Invalid value for property address:
I've been trying to make this happen all day, Ive used regexs plane echos and the json_encode() function and nothings worked can anyone help?
Thanks in advance
You have nested <?php ?> inside PHP code, which will not be interpreted as PHP. Rather, it just prints into your output as a string.
// Instead of
echo "<SCRIPT LANGUAGE='javascript'>
geocodeAddress(<?php echo json_encode($fullAddress);?>,<?php echo json_encode($infoText);?>);
</SCRIPT>'";
// Change to
echo "<SCRIPT LANGUAGE='javascript'>
geocodeAddress(" . json_encode($fullAddress) . "," . json_encode($infoText) . ");
</SCRIPT>'";
At least in my case, I have noticed that
<?php ...foo... ?>
segments in the HTML body, get php-evaluated only if the file extension is .php.
That is, I had to rename:
mv foo.html foo.php
to have php-values passed into javascript variables.
Related
While writing my website I encountered the following Problem:
On the first page, you can enter some data like names, dates, addresses etc.
In addition, there are a few checkboxes with fixed data.
After filling out the form I want it to get sent to my e-mail, which is working for the most part.
<?php
//subject of the e-mail
$subject = "Test";
// the message
$msg = "Antragssteller: " . $_POST['ANachname'] . ", " . $_POST['AVorname'] . "<br>E-Mail: " . $_POST['AMail'] . "<br><br>" .
"Testperson: " . $_POST['MNachname'] . ", " . $_POST['MVorname'] . "<br>Adresse: " . $_POST['Adresse'] . "<br><br>";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
sendMailInt($subject, $msg);
?>
Now I want to add some input with checkboxes on my website, which also works up to a certain point.
<?php
//subject of the e-mail
$subject = "Test";
// the message
$msg = "Antragssteller: " . $_POST['ANachname'] . ", " . $_POST['AVorname'] . "<br>E-Mail: " . $_POST['AMail'] . "<br><br>" .
"Testperson: " . $_POST['MNachname'] . ", " . $_POST['MVorname'] . "<br>Adresse: " . $_POST['Adresse'] . "<br><br>" .
"checkbox1: " . $_POST['checkbox1'] . "<br>" .
"checkbox2: " . $_POST['checkbox2'] . "<br>" .
"checkbox3: " . $_POST['checkbox3'] . "<br>" .
"checkbox4: " . $_POST['checkbox4'] . "<br>" .
"checkbox5: " . $_POST['checkbox5'] . "<br>" .
"checkbox6: " . $_POST['checkbox6'] . "<br>" .
"checkbox7: " . $_POST['checkbox7'] . "<br>" .
"checkbox8: " . $_POST['checkbox8'] . "<br>" .
;
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
sendMailInt($subject, $msg);
?>
Specifically for the checkbox input, I want to have something like an if-statement to check if the box has been checked or not.
If a box is unchecked, the value is empty, which means I have an empty line in my e-mail. Since I have around 20 checkboxes, it can get a bit messy in the e-mail, if 10 boxes in a row are unchecked.
I tried writing the $msg = as HTML mail and adding PHP code into it, but then my website stopped working (went completely blank, an error I encountered a few times before, when using wrong code)
<?php
//subject of the e-mail
$subject = "Test";
// the message
$msg = "
<html>
<head>
<title>Test Mail</title>
<body>
<?php
echo "Antragssteller: " . $_POST['ANachname'] . ", " . $_POST['AVorname'] . "<br>E-Mail: " . $_POST['AMail'] . "<br><br>" .
"Testperson: " . $_POST['MNachname'] . ", " . $_POST['MVorname'] . "<br>Adresse: " . $_POST['Adresse'] . "<br><br>";
if ($_POST['checkbox1'] == true)
echo $_POST['checkbox1'] . "<br>";
else
echo "";
if ($_POST['checkbox2'] == true)
echo $_POST['checkbox2'] . "<br>";
else
echo "";
if ($_POST['checkbox3'] == true)
echo $_POST['checkbox3'] . "<br>";
else
echo "";
if ($_POST['checkbox4'] == true)
echo $_POST['checkbox4'] . "<br>";
else
echo "";
if ($_POST['checkbox5'] == true)
echo $_POST['checkbox5'] . "<br>";
else
echo "";
if ($_POST['checkbox6'] == true)
echo $_POST['checkbox6'] . "<br>";
else
echo "";
if ($_POST['checkbox7'] == true)
echo $_POST['checkbox7'] . "<br>";
else
echo "";
if ($_POST['checkbox8'] == true)
echo $_POST['checkbox8'] . "<br>";
else
echo "";
?>
</body>
</html>
";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
// send email
sendMailInt($subject, $msg);
?>
Is there any way to skip empty variables in the mailer variable, so that the mail that gets sent looks clean without holes?
Looking forward to hearing from you guys and thanks in advance.
First thing you can do is in the file you're working with to force errors to show on the page (only use this in development environments):
error_reporting(E_ALL);
ini_set('display_errors', 1);
Second, multiple form inputs of the same data type can be greatly simplified by putting them in an array. Here's what the syntax would look like:
<input name="checkbox[]" value="1" />
<input name="checkbox[]" value="2" />
<input name="checkbox[]" value="3" />
<input name="checkbox[]" value="4" />
<input name="checkbox[]" value="5" />
Then in PHP you could do something like this that will only print out the checkboxes that were selected:
foreach ($_POST['checkbox'] as $checkbox) {
echo $checkbox . "<br>";
}
I am trying to make a button on a page that prints out data from the database and then you can press 2 different buttons, one that deletes them from the database and the other one inserts it into another table in the database and deletes the data from the database, but it keeps inserting it twice into the new table and I have no clue why, this here prints out the data and session variables + buttons:
if(!isset($_POST['orderby'])) {
foreach ($requests as $row) {
echo "<div class='requests'>" . "<li class='refunds'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Hylkää</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Hyväksy</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
} else {
foreach ($pergele as $row) {
echo "<div class='requests'>" . "<li class='refunds2'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Hylkää</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Hyväksy</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
}
and this should insert it into the database once and delete the data from the old table:
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$custname = $_SESSION['custname'];
$prodname = $_SESSION['prodname'];
/* Query to do whatever here */
$wpdb->insert("wp_acceptedrequests", [
"customer_name" => "$custname",
"name_product" => "$prodname",
"date" => date("Y/m/d/G:i:sa") ,
]);
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
What makes them insert twice and how do I prevent it from doing that?
I just ran into a similar situation where $wpdb inserts where being duplicated.
In my case it was happening if I was authenticated and browser inspector was open.
I'm trying to pull a first name, last name, and email from a data base and trying to put into Firstname Lastname , with PHP. Every time I try to echo the data I only get Firstname Lastname. The email and <> doesn't show up? Anyone know how I can echo .
Here's the code:
while($row = mysqli_fetch_assoc($res)){
echo $row['firstname'] . " " . $row['lastname'] . " <" . $row['email'] . ">,";
}
Your code works fine, but < and > characters form a HTML tag, that is why you don't see the mail.
If you look at the source code of your echo, you will see the <mail> appearing.
You can also do this :
while($row = mysqli_fetch_assoc($res)){
echo htmlspecialchars($row['firstname'] . " " . $row['lastname'] . " <" . $row['email'] . ">,");
}
htmlspecialchars will transform < and > to their HTML code, so they will be visible even if you're not looking at the source.
A useful function to have is this one :
// Echoes the string in a HTML friendly way
function echoHTML($str)
{
echo htmlspecialchars($str);
}
while($row = mysqli_fetch_assoc($res)){
echoHTML($row['firstname'] . " " . $row['lastname'] . " <" . $row['email'] . ">,");
}
PS : be careful about the last comma if you want to concatenate email adresses, you will have a trailing , at the end of the list of mails. Here is how to avoid it :
$adresses = [];
while($row = mysqli_fetch_assoc($res))
{
// No more "," here
$adresses[] = $row['firstname'] . " " . $row['lastname'] . " <" . $row['email'] . ">";
}
echoHTML(implode(', ', $adresses));
So, I'll post the code below. Beneath the code is where I will pose my question.
if (!empty($_SESSION['username']) && !empty($_SESSION['password']))
{
$server=mysql_real_escape_string($_POST['server']);
$teamname=mysql_real_escape_string($_POST['teamname']);
$creator=$_SESSION['username'];
$verify = mysql_real_escape_string($_POST['verify']);
$date = date("F j, Y, g:i a");
if (!empty($teamname)) {
// if ($verify == "wookie" ||
// $verify == "Wookie" ||
// $verify == "WOOKIE")
// {
$sql="INSERT INTO rated_teams (server, name, creator, created, players, win, loss)
VALUES ('$server', '$teamname', '$creator','$date', '', '', '')";
if (mysql_query($sql,$con))
{
echo "<p>Added ". $teamname . " on " . $server . " by " . $creator . " on " . $date ." <br /><a href='myprofile.php'>Return to Profile</a></p>";
}
else
{
echo $sql . "<br />";
echo "<br /><h1>Error</h1>";
echo "<p><a href='myprofile.php'>Sorry, your team registration has failed. Please go back and try again.</a></p>
<br />" . $teamname . " on " . $server . " by " . $creator . " on " . $date;
}
//} else { echo "That isn't how you spell Wookie!"; }
} else { echo "Team Name is empty, <a href='myprofile.php'>go back and give yourself a Team Name</a>"; }
} else { echo "You must be <a href='login.php'>logged in</a>!"; }
This issue is that the line "if (mysql_query($sql,$con))" goes directly to the ELSE. I'm assuming the problem lies with my $sql but I can't pinpoint where it is. Another pair of eyes would really help. Thanks a bunch!
To trace errors with mysql_query() , you should use mysql_error(). Here's an example, inspired of one of the PHP mysql_error() doc
$sql="INSERT INTO rated_teams (server, name, creator, created, players, win, loss)
VALUES ('$server', '$teamname', '$creator','$date', '', '', '')";
mysql_query($sql,$con);
if (mysql_errno()) {
$error = "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$sql\n<br>";
// Your stuff
echo $sql . "<br />";
echo "<br /><h1>Error</h1>";
echo "<p><a href='myprofile.php'>Sorry, your team registration has failed. Please go back and try again.</a></p>
<br />" . $teamname . " on " . $server . " by " . $creator . " on " . $date;
}
else {
echo "<p>Added ". $teamname . " on " . $server . " by " . $creator . " on " . $date ." <br /><a href='myprofile.php'>Return to Profile</a></p>";
}
Also, you should use PDO or mysqli, since mysql_* are deprecated since PHP 5.x
I need help with a php page that shows information from a mysql database concerning buildings around a town square. I want it set up so that the addresses are the only thing displayed at first. Then when someone clicks on a certain address it shows them more information on that particular building.
I am new to PHP. There are two solutions I know will work but I don't want to go that route unless I must.
Those two solutions are
create a page for each building and link each address to the specific page and
Insert each database item into the page (instead of having a PHP loop) and hidden div that could be toggled for each address.
The code I have right now (and it works) is for displaying the address:
echo "<p><h3> " . stripslashes($rowBuildings[building_address]) . "</h3><br>\n";
But how do I display the rest of the building info if (and only if) they click on the building address? Sorry if this is a broad topic. I've read several forums but with no luck. My problem isn't getting the info from the database.
I found the fix to my dilemma . . .
I was using the Javascript to Toggle a div (that was fairly simple). My problem was toggling each separate div as they were added by the PHP script (according to the number of database entries). I couldn't figure out how to have incremental div id names for both the link and the div. Example:
<!--This was the link to toggle the div -->
<h3>Address</h3>
<!--This was the div to toggle -->
<div id="divid">Hello</div>
My PHP was inserting multiple divs and links though so when you would click on an address all the divs named "divid" would appear. To fix the problem I added a PHP variable to each div id such as:
$uniqueID = 0;
$PleaseWork = 0;
I then placed at the bottom of the php code:
$uniqueId++;
$PleaseWork++;
This allowed me to place variables in the link and the div id that would count consistently together. So altogether, here are the codes:
Java to toggle
> <script type="text/javascript">
>
> function toggleMe(a){ var e=document.getElementById(a); if(!e)return
> true; if(e.style.display=="none"){ e.style.display="block" } else{
> e.style.display="none" } return true } </script>
PHP CODE - THE LINK & Visible Items
<div class="building" align="left" style="margin-left:100px;">
<?
{
$uniqueID = 0;
$PleaseWork = &$uniqueID;
}
$selectAddress ="SELECT * FROM `buildings` order by building_address";
$resultAddress = mysql_query($selectAddress);
while($rowBuildings = mysql_fetch_array($resultAddress)){;
echo "<p><a id=\"displayText\" href=\"#\" onclick=toggleMe(\"divn$PleaseWork\");><h3> " . stripslashes($rowBuildings[building_address]) . "</a></h3><br>\n";
echo "<b>For Sale or Rent:</b> " . $rowBuildings[building_saleorrent] . "";
if(!empty($rowBuildings[building_permonth]))
echo "<b>Rent Per Month: </b>" . $rowBuildings[building_permonth] . "";
if(!empty($rowBuildings[building_saleprice]))
echo "<b>Sale Price: </b>" . $rowBuildings[building_saleprice] . "";
echo "<br>\n";
PHP CODE - The hidden DIV
echo "<div id=\"divn$uniqueID\" style=\"display:none\"><b>Is the Property Listed with a Realtor? </b> " . $rowBuildings[building_realtor] . "<br>\n";
if(!empty($rowBuildings[building_target]))
echo "<b>Best Suited for Building: </b>" . $rowBuildings[building_target] . "<br>\n";
echo "<b>Owner: </b>" . $rowBuildings[building_owner] . "";
if(!empty($rowBuildings[building_ownphone]))
echo "<b> Phone: </b>" . formatPhone($rowBuildings[building_ownphone]) . "";
if(!empty($rowBuildings[building_ownemail]))
echo "<b> Email: </b>" . $rowBuildings[building_ownemail] . "";
echo "<br>\n";
echo "<b> Is the building occupied? </b>" . $rowBuildings[building_isoccupant] . "<br>\n";
if(!empty($rowBuildings[building_occupant]))
echo "<b>Current Occupant:</b>" . $rowBuildings[building_occupant] . "<br>\n";
if(!empty($rowBuildings[building_occupantphone]))
echo "<b>Occupant Phone:</b>" . formatPhone($rowBuildings[building_occupantphone]) . "<br>\n";
echo "<b>Utilities: </b>" . $rowBuildings[building_utilities] . "<br>\n";
echo "<b>Stories: </b>" . $rowBuildings[building_stories] . "<br>\n";
echo "<b>Total Sq. Footage: </b>" . $rowBuildings[building_square] . "<br>\n";
echo "<b>Footage Breakdown:</b><br> ";
if(!empty($rowBuildings[building_residential]))
echo "<b>Residental: </b>" . $rowBuildings[building_residential] . " ";
if(!empty($rowBuildings[building_lightindustry]))
echo "<b>Light Industrial: </b>" . $rowBuildings[building_lightindustry] . " ";
if(!empty($rowBuildings[building_commercial]))
echo "<b>Residental: </b>" . $rowBuildings[building_commercial] . " ";
echo "<br>\n";
echo "<b>Storage: </b>" . $rowBuildings[building_storage] . " <b>Storage Sq. Footage: </b>" . $rowBuildings[building_storefoot] . "<br>\n";
echo "<b>Inside of Building: </b>" . $rowBuildings[building_inside] . "<br>\n";
echo "<b>Outside of Building: </b>" . $rowBuildings[building_outside] . "<br>\n";
echo "<b>Parking: </b>" . $rowBuildings[building_parking] . "<br>\n";
if(!empty($rowBuildings[building_issues]))
echo "<b>Issues With the Building: </b>" . $rowBuildings[building_issues] . "<br>\n";
if(!empty($rowBuildings[building_features]))
echo "<b>Main Features of the Building: </b>" . $rowBuildings[building_features] . "<br>\n";
if(!empty($rowBuildings[building_notes]))
echo "<b>Notes on the Building: </b>" . $rowBuildings[building_notes] . "<br>\n";
echo "</div></p>";
$uniqueId++;
$PleaseWork++;
}
?>
I used various sites to gather this information. Here are some:
http://www.dynamicdrive.com/forums/showthread.php?41829-Toggle-Div-in-PHP
http://php.net/manual/en/language.references.unset.php
Sorry if this is confusing. Thanks for all your help!