Display php using javascript - php

<p>Todays Date: <? echo $date; ?></p>
<p>Are you applying for a day, evening, or weekend class?
<select name='date' id='wclass'>
<option value ='day'> Day</option>
<option value ='evening'>Evening</option>
<option value ='weekend'>Weekend</option>
</select>
Program Start Date:
<div id='dates'></div>
<script language="javascript">
$(document).ready(function() {
{ setInterval(function () {
if ($("#wclass").val()=='day')
{ $('#dates').html("<? echo <select name='date'>
<option value ='date1'> $start1 </option>
<option value ='date2'>$start2</option>
<option value ='date3'>$start3</option>
<option value ='date4'>$start4</option>
<option value ='date5'>$start5</option>
<option value ='date6'>$start6</option>
<option value ='date7'>$start7</option>
</select> }?>");}
}, 1000);
});
My issue is that i am not sure how to display php using javascript. The variables are all correct, the issue is to get the php to display as html would in my .html. All i want to do is display the php variables which i fetched in the beginning. So the variables have been defined in php now i want to turn them into a html list based on my javascript. You may notice that the echo is missing quotes, thats because i dont know how to put quotes, i cant use " or ' because they both interup quotes that are already there.

Your javascript does not have access to your PHP variables, unless you request them via AJAX.
However, you don't have to use AJAX. You could use your PHP code to build the Javascript code before it is sent to the browser!!
Here's one way of doing it:
<?php
$start1 = '01/01/2010';
$start2 = '11/11/2010';
$start3 = '03/12/2010';
// and so on...
?>
<p>Today's Date: <?php echo $date; ?></p>
<p>Are you applying for a day, evening, or weekend class?</p>
<select name="date" id="wclass">
<option value="day">Day</option>
<option value="evening">Evening</option>
<option value="weekend">Weekend</option>
</select>
Program Start Date:
<div id="dates"></div>
<script language="javascript">
$(document).ready(function() {
{
$("#wclass").change(function ()
{
if( $(this).val() == 'day' )
{
$('#dates').html('<select name="date">\
<option value="date1"><?php echo $start1; ?></option>\
<option value="date2"><?php echo $start2; ?></option>\
<option value="date3"><?php echo $start3; ?></option>\
<option value="date4"><?php echo $start4; ?></option>\
<option value="date5"><?php echo $start5; ?></option>\
<option value="date6"><?php echo $start6; ?></option>\
<option value="date7"><?php echo $start7; ?></option>\
</select>');
}
});
});
</script>
An even better option would be to just create the second select outright, and then show/hide it when needed:
<?php
$start1 = '01/01/2010';
$start2 = '11/11/2010';
$start3 = '03/12/2010';
// and so on...
?>
<p>Today's Date: <?php echo $date; ?></p>
<p>Are you applying for a day, evening, or weekend class?</p>
<select name="date" id="wclass">
<option value="day" selected="selected">Day</option>
<option value="evening">Evening</option>
<option value="weekend">Weekend</option>
</select>
Program Start Date:
<select id="dates" name="date">
<option value="date1"><?php echo $start1; ?></option>
<option value="date2"><?php echo $start2; ?></option>
<option value="date3"><?php echo $start3; ?></option>
<option value="date4"><?php echo $start4; ?></option>
<option value="date5"><?php echo $start5; ?></option>
<option value="date6"><?php echo $start6; ?></option>
<option value="date7"><?php echo $start7; ?></option>
</select>
<script language="javascript">
$(document).ready(function() {
{
$("#wclass").change(function ()
{
$(this).val() == 'day' ? $('#dates').show() : $('#dates').hide()
});
});
</script>

PHP is a server-side language. PHP is executed by the server, and the result (usually some HTML) is sent to the client for display. If you're trying to display PHP code literally, then it's definitely possible. I get the feeling, however, that you're trying to execute the PHP code in Javascript. You can't do that, because Javascript is executed client-side -- that is, after the page has already been sent to the client's browser from the server.

Do you understand completely, the difference between running scripts on server vs running HTML/JavaScript on web-client ?
PHP is executed on server. It renders HTML and JS. Then HTML/JS goes to a viewer (web-client) and is executed on client's machine... You can't "run PHP inside JS" the way you want.
If you need some data from PHP injected to your JS code you may try running AJAX.

Checklist of simple, simple things that we don't want to overlook:
You saved the file with a .php extension.
Short tags are enabled.
That should work. Make sure it's saved as a .php file, and you should be good. Oh, and preferably you'd use <?php .. ?> instead of <? ?> since shorttags are advised against for compatibility reasons.
Note If your PHP was actually executing, you'd be getting syntax errors thrown into your page because your echo doesn't have the string in quotes, among other things.

Related

PHP to show div info based on selected option in form

I want to use PHP to change a div's information based on what option is selected. Below is my HTML & PHP. I don't think I'm using the right operator or syntax in the if statement. I basically want to pull information from a table in my database based on the option selected. Right now I do not have that in my code because it is irrelevant at this point. Any help is appreciated.
<select id=\"numberofstaff\">
<option class=\"staffselection\" value=\"\">--Select--</option>
<option class=\"staffselection\" value=\"smalljobsite\">1-3 staff</option>
<option class=\"staffselection\" value=\"mediumjobsite\">4-7 staff</option>
<option class=\"staffselection\" value=\"largejobsite\">8+ staff</option>
</select>
<?php
$selectOption = $_POST['numberofstaff'];
echo "<div id='jobsite_price'><p>";
if ($selectOption == 'smalljobsite'){
echo "smalljobsite";
};
if ($selectOption == 'mediumjobsite'){
echo "mediumjobsite";
};
if ($selectOption == 'largejobsite'){
echo "largejobsite";
};
echo "</p></div>";
?>
You need form tags and a POST method, while giving the select a name attribute. You can't rely on an id alone, not without JS/Ajax anyway.
Sidenote: I removed the \ from the escaped quotes, since they're not in an echo statement/PHP in your posted code. This would throw an error/warning such as "unquoted attribute". If you are using it inside an echo'd statement, then you'll need to add those back in.
FYI: Escaping quotes \" is only done when inside an echo/PHP.
Additional note:
If you want to run seperate SQL statements, it's rather simple. Where the echos are and where I have in a comment form // RUN SQL HERE, you can simply include a file in there with your SQL query. I do it myself and it cuts down on a lot of code and is more manageable that way.
HTML/PHP:
<form method="post" action="">
<select id="numberofstaff" name="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
$selectOption = $_POST['numberofstaff'];
echo "<div id='jobsite_price'><p>";
if ($selectOption == 'smalljobsite'){
// RUN SQL HERE
echo "smalljobsite";
}
if ($selectOption == 'mediumjobsite'){
// RUN SQL HERE
echo "mediumjobsite";
}
if ($selectOption == 'largejobsite'){
// RUN SQL HERE
echo "largejobsite";
}
echo "</p></div>";
} // brace for if(isset($_POST['submit']))
?>
Foonotes:
To include files, you can use include():
// Include your SQL query
include('query_file.php');
where you see // RUN SQL HERE in commented code.
Another option is to use Ajax.
Here are a few links:
http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php
http://www.tutorialspoint.com/php/php_and_ajax.htm
How to use AJAX to perform a MYSQLI query (prepared statement)
If you're just using php to check the selected value, you can use jquery for that, i.e.:
$("select").on('change', function() {
$("#jobsite_price").html("<p>"+$(this).val()+"</p>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="numberofstaff">
<option class="staffselection" value="">--Select--</option>
<option class="staffselection" value="smalljobsite">1-3 staff</option>
<option class="staffselection" value="mediumjobsite">4-7 staff</option>
<option class="staffselection" value="largejobsite">8+ staff</option>
</select>
<div id='jobsite_price'></div>
You can use pure javascript to do this.
window.addEventListener('load', function(){
var el = document.querySelector("#numberofstaff");
el.addEventListener('change', function(){
var data = { numberofstaff : el.value };
var request = new XMLHttpRequest();
request.open('POST', 'YourUrl.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
request.onload = function(result){
document.querySelector("#jobsite_price").innerHTML = result.responseText;
}
});
});

How to add a 'selected' in a select dropdown wp/php

I have a problem which I'm not sure how to approach, I have a WP plugin which has a form, in the form I have a with result that could have varied amount of data (depending on what the user submits).
How can I add 'selected' to the selected item so when the user returns he can edit/view the item he selected?
<select name="supplier">
<option value="Supplier 1">Supplier 1</option>
<option value="Supplier 2">Supplier 2</option>
<option value="Supplier 3">Supplier 3</option>
<option value="Supplier 4">Supplier 4</option>
</select>
A loop comes to mind, shall I assign a number to each option? There may be 100 suppliers so it would need to count right?
I would use a loop like...
$theirChosenSupplier = $supplierVarFromDatabaseOrWherever;
?>
<select name="supplier">
foreach($allSuppliers as $individualSupplier) {
if($individualSupplier == $theirChosenSupplier) {
$selected = "selected";
} else {
$selected = "";
}
?><option value="<?php echo $individualSupplier; ?>" <?php echo $selected; ?>>
<?php echo $individualSupplier; ?>
</option>
<?php } ?>
</select>
This code isn't tested but should give you an idea. Apologies if I've misunderstood the question.
adding an id is always a good thing. Assuming this is wordpress generated and you don't have a loop already there is always the option of using javascript and maybe an onchange event.
I dont know if the form is submitted first or you do some other stuff but maybe:
<select id="foo">
<option id="provider_1">Provider 1</option>
<option id="provider_2">Provider 2</option>
</select>
<script type="text/javascript">
window.onload = function() {
var selectedValue = '<?php echo someEscapeFunction($_SESSION['id_provider']); // or _GET, _POST ?>';
document.getElementById('foo').selectedIndex = document.getElementById(selectedValue).index;
}
</script>

How to update data when input is drop down?

I am so new in html, php, javascript, mysql. i created a drop down menu using java script that contains a list of 2011 to 2510. During update i can not display the stored value that is generated using java script. I searched but found nothing. A portion of code.....
<select name="eca">
<option id="eca" required="required" class="ecadetail" value="NSS" <?php if ($eca == 'NSS') echo 'selected="selected"';?>">NSS</option>
<option id="eca" required="required" class="ecadetail" value="NCC" <?php if ($eca == 'NCC') echo 'selected="selected"';?>">NCC</option>
<option id="eca" required="required" class="ecadetail" value="Cultural" <?php if ($eca == 'Cultural') echo 'selected="selected"';?>">Cultural</option>
</select>
</div>
<div class="label">Year</div>
<div class="inputyear">
<select name="years" >
<script language="JavaScript">
// loop to create the list
var year = 2010
for (var i=1; i <=500; i++)
{
year++;
document.write("<option>" + year + "</option>");
}
// end JS code hide -->
<option value="<?php if ($year == 'year') echo 'selected="selected"';?>"></script>
</script>
</select>
</div>
</div> <!-- end of 7th row -->
the value for eca is working fine. The value year is stored in $year.
help please...
This loop can purely done in php then why involving the javascript
<select name="years" >
<?php
$matchyear = 2010;
for ($i=2010; $i <=2510; $i++)
{ ?>
<option value="<?php echo $i;?>" <?php if ($i== $matchyear) echo 'selected="selected"';?>><?php echo $i;?> </option>
<?php }
?>
</select>
Make things easier for you not a complex programming so that other person can understand easily and call you by good names

How to get VALUE from FORM without Submitting it?

I would like to get value from Form without submitting it, because the client have to choose the right type of house model to get the right form that fits the selected house model, without submitting, just selecting the house model and it for example continues the rest of form after that.
I have so far tried with this:
<form method="GET" action="foo.php">
<select name="house_model">
<option value="">------</option>
<option value="<?php echo $model1;?>">Model 1</option>
<option value="<?php echo $model2;?>">Model 2</option>
<option value="<?php echo $model3;?>">Model 3</option>
</select>
</form>
<?php
$a = $_GET["housemodel"];
if($a<>'')
{
if($a == $model1)
{
echo "<input type=\"text\" name=\"a\" value=\"something model1\">";
}
else if($a == $model2)
{
echo "<input type=\"text\" name=\"b\" value=\"something model2\">";
}
else if($a == $model3)
{
echo "<input type=\"text\" name=\"c\" value=\"something model3\">";
}
}
?>
I think, if you dont want page to be refreshed when user selects value from your drop down list, then you can use ajax. AJAX is used for this purpose. if you google, then you will find lots of tutorials related to AJAX.
If you don't want to submit the form, use JavaScript to get the element. Or you can also use jquery to access the value. Make sure you put id = "something" and retrieve it using $('#something').val();
if you want to use JavaScript,
<select name="house_model" id="model">
<option value="">------</option>
<option value="<?php echo $model1;?>">Model 1</option>
<option value="<?php echo $model2;?>">Model 2</option>
<option value="<?php echo $model3;?>">Model 3</option>
</select>
<script type="text/javascript">
var model= document.getElementById('model');
alert("You entered: " + model);
</script>
AJAX codes here
$("#model").live("change", function () {
alert("You choose " + $('#model').val());
});
IF you don't want to submit your form, you can get element using AJAX/jQuery.
<form method="GET" action="foo.php" onChange="getHouseModel">
<select name="house_model" id="house_model">
<option value="">------</option>
<option value="<?php echo $model1;?>">Model 1</option>
<option value="<?php echo $model2;?>">Model 2</option>
<option value="<?php echo $model3;?>">Model 3</option>
</select>
</form>
<script type='text/javascript'>
function getHouseModel(){
var model=$('#house_model').val();
alert(model);
}
</script>
or you can write jquery like this. so you dont have to call function in tag
<script type="text/javascript">
$('#house_model').select(function() {
var model=$('#house_model').val();
alert(model);
});
</script>
There is no way of getting data from a form before submitting in in PHP! This is because before submitting the form the PHP script simply is not called.
If you want to do some validation before sending data you must use javascript which is run on the client browser. Have a look at the jQuery library which makes this very easy: http://docs.jquery.com/Plugins/Validation/validate
If you want to use PHP only then you will need to separate the form into two pages.
You have to use ajax for achiving this.For example
<form method="GET" action="foo.php">
<select name="house_model" id="house_model">
<option value="">------</option>
<option value="<?php echo $model1;?>">Model 1</option>
<option value="<?php echo $model2;?>">Model 2</option>
<option value="<?php echo $model3;?>">Model 3</option>
</select>
</form>
$("#house_model").live("change", function () {
//Write the ajax and post the value to server side
});

Get value from select with JavaScript for use in PHP

I have this select:
<select id="mymenu" name="id" onchange="getID()">
<option></option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I want to get the value from mymenu to use it in another select in the same form. I searched the 'net and found that I should use onchange.
<select name="uid">
<option></option>
<?
$sql = mysql_query("Select * from $table WHERE id = '$ch_id'");
while ($row = mysql_fetch_array($sql)) {
?>
<option value="<? echo $row['unit_id']; ?>"><? echo $row['unit_name'];?></option>
<?
}
?>
</select>
This is the getID() function:
<script type="text/javascript">
function getChapterID(){ //run some code when "onchange" event fires
var selectmenu=document.getElementById("mymenu")
<?$ch_id?> = this.options[this.selectedIndex].value
}
</script>
You can't redefine a PHP value thru JS, it would be very unsafe. I suggest you to use kind of form that when you change it, it submits, posts into a php self and redefines it. I won't write that code for you, but this is what you need.
Good luck
google "ajax php select menu", the first example here: http://www.w3schools.com/php/php_ajax_database.asp
explains the process...
Beware the w3 demo though, it does not sanitize $_GET[] variable, and is wide open to a sql injection.

Categories