PHP code inside javascript - php

I have no idea about how javascript works, but I was able to write the following code by copying from different sites.
My aim is to have 2 radio boxes (1 = India, 2 = Other than India) and if Other than India is selected, then a dropdown box is displayed which shows names of all countries.
The dropdown is selected from a database and it is achieved by a custom php function.
I am able to make the code display the dropdown based on my radio box selection.
What I am unable to do is as follows:
I am not able to select any values from the dropdown.
I'm not able to make the dropdown hide if I change the choice in the radio box
Here is the code of the form:
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<br />
<script type="text/javascript">
function onclickradio(entry){
if (entry === true) {
alert("YOU HAVE CHOSEN INDIA");
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '</br><?php dropdown('country');?>';
}
}
</script>
Country: </br>
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="INDIA" name="country" type="radio" checked="checked"/> INDIA
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="OTHER THAN INDIA" name="country" type="radio"/> OTHER THAN INDIA
<br /><br /><br />
State: <input type="text" name="State" maxlength="30"/><br />
Line1: <input type="text" name="Line1" maxlength="50" /><br />
Line2: <input type="text" name="Line2" maxlength="50" /><br />
City: <input type="text" name="City" maxlength="40" /><br />
PIN Code: <input type="text" name="PIN_Code" maxlength="8" /><br />
<input type="submit" name="submit_address" value="Submit Address" />
</fieldset>
</form>
Here is the code for the custom PHP dropdown function:
<?php
function dropdown($tablename) /*remember to add single quote around the input*/
{
$sql="SELECT * FROM ".$tablename;
$result=mysqli_query($GLOBALS["connection"], $sql)
or die('Error in running SELECT query');
$options=""; //initialising the variable, so that it can be concatenated later
while ($row=mysqli_fetch_array($result))
{
$x=0; /*$x is the index of the field in a row (it has to start with $x=0;
because the first index is 0 in php*/
$rowstr=" # "; /*initialising the variable,
so that it can be concatenated later*/
while ($x+1<=mysqli_num_fields($result)) /*mysqli_num_fields gives the actual number of fields, and not the index.
Since the index starts with 0, it is to be incremented by 1
before comparison with the mysqli_num_fields*/
{
$rowstr.= $row[$x]." # "; //concatenation operator
$x=$x+1;
}
$options.="<option value=".$rowstr.">".$rowstr."</option>"; //concatenation operator
}
Echo "<select>".$options."</select>";
}
?>

A few things that come to mind:
Don't put spaces in id values. I recommend that you use lower case as well, so you could have "india" and "not-india" instead.
Use Firefox/Firebug or similar to see if you have any JavaScript errors when you run this
Consider using jQuery or similar to catch change events - it is easy to use and uses the 'unobtrusive' method of adding JS functionality to your page.

Id field of an element can not have space. Just try removing spaces in "OTHER THAN INDIA" or replace to looks like OTHER_THAN_INDIA

Try this:
$(document).ready(function() {
// hide address inputs
$('#address').hide();
// show address inputs if the not india button is pressed
$('#not-india').click(function() {
$('#address').show();
});
// re-hide address inputs if india is selected
$('#india').click(function() {
$('#address').hide();
});
});
You will also have to include jQuery in your page.
Fiddle: http://jsfiddle.net/EN4jB/6/
Please note that I used the following markup - particular attention is due to the id of this div.
<input id="india" name="country" type="radio" checked="checked"/> India
<input id="not-india" name="country" type="radio" /> Not India
<br />
<div id="address">
<p><select>
<option>USA</option>
<option>UK</option>
<option>Ireland</option>
<option>etc...</option>
</select>
</p>
<p>State: <input type="text" name="State" maxlength="30"/></p>
<p>Line1: <input type="text" name="Line1" maxlength="50" /></p>
<p>Line2: <input type="text" name="Line2" maxlength="50" /></p>
<p>City: <input type="text" name="City" maxlength="40" /></p>
</div>

To clear the selection if India is chosen
function onclickradio(entry) {
if(entry===true) {
alert("YOU HAVE CHOSEN INDIA");
document.getElementById('OTHER THAN INDIA').innerHTML = '';
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '<br/><?php dropdown('country');?>';
}
}

Related

Placing data in MySQL database from form fields created on the fly

I have a form that allows members to click a (+) sign, and it will put another form field there. They can do this to basically without limit.
The problem I have is if they do it, let's say, 3 times and fill out all 3, when I get the data to save it, it's placing the first field in the database and not the others.
Here is my code:
Here is the JavaScript that makes the div show as they push the (+) sign.
<script type="text/javascript">
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
document.getElementById('newlink').appendChild(div1);
}
</script>
<style>
.feed {padding: 5px 0}
</style>
This is part of the form that does the above...
<td width="50%" valign="top">
<div id="newlink">
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
<hr>
<p id="addnew">
+ Click Here To Add Another Biz/Traffic/Tools Site
</p>
<div id="newlinktpl" style="display:none">
<hr>
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
This is the part of the PHP code that would save it...
$i=0;
$linkname = $_POST["recname"][0];
while($linkname != ""){
$linkname = $_POST["recname"][$i];
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
$linkname = $res->real_escape_string($linkname);
$linkurl = $res->real_escape_string($linkurl);
$linktype = $res->real_escape_string($linktype);
$result299 = mysqli_query($res, "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')");
$i++;
}
It's all working except that is does not store all the data in the database (only the first one saves). That's the part I need help with please.
Please explain what I have done wrong and how to get it to store all the fields in the database, no matter how many the user creates and fills out.
I tested your code and it works fine so far if I use it like this:
$i=0;
$linkname = $_POST[recname][0];
while($linkname != ""){
$linkname = $_POST[recname][$i];
$linkurl = $_POST[reclink][$i];
$linktype = $_POST[rectype][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
There's no information about the $res object you're calling real_escape_string() on, so I'll just skip that for now. There are a couple of weaknesses in the code though:
You are referencing the post keys with barenames instead of strings.
PHP will gracefully assume you meant it as a string, but it will trigger a notice like Use of undefined constant recname - assumed 'recname'. Enclose them in quotes to make it clean.
Your use of the loop will result in an empty element inserted in the database every time.
You set the new linkname AFTER checking if $linkname is empty, but the variable contains the name of the last iteration. Instead, do something like this:
$i=0;
while($linkname = $_POST["recname"][$i]){
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
Your code only allows for one radio button to be checked at a time
You cannot use rectype[] as a name for radio buttons, as an equal name forms a group of radio buttons out of all the elements. You need to name them like this:
<input type="radio" name="rectype[0]" value="1"> Business Opp<br />
<input type="radio" name="rectype[0]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[0]" value="3"> Tools Site<br />
<input type="radio" name="rectype[1]" value="1"> Business Opp<br />
<input type="radio" name="rectype[1]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[1]" value="3"> Tools Site<br />
and so on. You can do that programatically in your javascript code like this:
<script type="text/javascript">
var counter = 1;
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
var inputs = div1.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
if (inputs[i].type == "radio") {
inputs[i].name="rectype[" + counter + "]";
}
}
counter++;
document.getElementById('newlink').appendChild(div1);
}
</script>
That said, I don't see why it should only save one item, unless you have a key constraint hitting or something else we cannot assume from the piece of code you shared.

How do I use prop. to only be applied to the element clicked?

I am creating a payment form, part of which the user can select credit card or paypal. I am having issues with the display function. Should I be creating a new function for each element? This is what I have:
<p>Billing Infomation</p>
First Name: <input name="Billing_F_name" type="text" size="15"
value="Enter First Name"/> Last Name: <input name="Billing_L_name"
type="text" size="20" value="Enter Last Name"/><br />
Method of Payment:<br />
Credit Card <input name="payment" id="p1" type="radio" onclick="javascript:
payment()"/><br />
Paypal <input name="payment" id="p4" type="radio"
onclick="javascript:payment()"/><br />
<script language="javascript" >
function payment(click)
{
if(document.getElementById("p1"){
$('input:radio[name="payment1"][value="P_1"]').prop('checked=checked', true);
document.write('<? $P_Method = 'P_1'; ?>');
}
else if(document.getElementsById("p4")){
$('input:radio[name="payment4"][value="P_4"]').prop('checked=checked', true);}
document.write('<? $P_Method = 'P_4'; ?>');
}
</script>
BTW, just for your reference. The PHP set variables that are being set go to a php switch method, displaying their respective elements, which functions properly at the moment.
Pass the clicked element to the handler and use it.
javascript:payment(this)
..
function payment(el) {
$(el).doSomething()
}
for execute in php you need use AJAX
<script language="javascript">
function payment(dd)
{
if(dd.id=="p1")
document.write("<? $P_Method = 'P_1'; ?>");
else if(dd.id=="p4")
document.write("<? $P_Method = 'P_4'; ?>");
}
</script>
<p>Billing Infomation</p>
First Name: <input name="Billing_F_name" size="15" value="Enter First Name" type="text">
Last Name:
<input name="Billing_L_name" size="20" value="Enter Last Name" type="text"><br>
Method of Payment:<br>
Credit Card <input name="payment" id="p1" onclick="payment(this)" type="radio"><br>
Paypal <input name="payment" id="p4" onclick="payment(this)" type="radio"><br>

How do I determine which dynamically-generated submit button was clicked in my PHP form?

I want to edit a dynamically-generated form (meaning: I don't know how many rows will be generated). This content is generated within a while loop, and the HTML generated has creates buttons of input-type=submit, generating as many identically-named buttons as there are iterations in the loop.
Of the generated buttons, I want to know which submit button has been clicked, in order to provide the user the same form for which it has been clicked. Disregard the name of the database and password to connect it; the connectivity is fine.
Feel free to suggest any new method to achieve the desired functionality.
The code is as follows:
echo "you have reached your travel details page. your recent travelling details are as follows".'</br>';
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE emailid='{$_SESSION['username']}' ORDER BY dep_date DESC";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
?>
<h1>Your travel details are:-</h1>
<form name="showtraveldet" METHOD="POST" action="edittraveldet.php">
<table border="1">
<tr>
<th>Starting point</th><th>Ending point</th><th>No of passengers</th><th>Expected fare</th><th>Departure date</th>
<th>Departure time</th><th>Arrival Date</th><th>Arrival Time</th><th>Car Model</th><th>Car number</th>
<th>Who is driving</th><th>Driver's license number</th>
</tr>
<?php
while ($row=mysqli_fetch_array($result))
{
$tid=$row['travel_id'];
echo "the value of tid is '{$tid}'";
echo'<tr><td>'.$row['start_point'].'</td><td>'.$row['end_point'].'</td><td>'.$row['no_of_pass'].'</td><td>'.
$row['exp_fare'].'</td><td>'.$row['dep_date'].'</td><td>'.$row['dep_time'].'</td><td>'.$row['arr_date'].'</td><td>'.$row['arr_time'].'
</td><td>'.$row['car_model'].'</td><td>'.$row['car_no'].'</td><td>'.$row['who_is_driving'].'</td><td>'.$row['driver_license_no'].'</td>
<td><input type="submit" name="edit" value="Edit"></td></tr><input type="hidden" name="travelid" value="'.$row['travel_id'].' ;?>">';
}
edittraveldet.php :-
$travelid=$_POST['travelid'];
echo "the travel id in the variable is $travelid and got the value from '{$_POST['travelid']}'";
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE travel_id='{$travelid}'";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
mysqli_close($dbc);
$row=mysqli_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validatewheregoing()" name="wheregoing">
<h1> Enter your travelling details so that other travellers can join you</h1>
<fieldset>
<legend> Travelling details </legend>
Start Point: <input type="text" name="start" value="<?php echo $row['start_point']; ?>"/><br />
End point: <input type="text" name="end" value="<?php echo $row['end_point']; ?>"/><br />
Passengers allowed: <input type="number" name="noofpass" value="<?php echo $row['no_of_pass']; ?>"/><br />
Expected Fare per passengers in rupees:<input type="number" name="fare" value="<?php echo $row['exp_fare']; ?>"/><br />
Departure Date:<input type="date" name="depdate" value="<?php echo $row['dep_date']; ?>"/><br/>
Departure time:<input type="time" name="deptime" value="<?php echo $row['dep_time'] ;?>"/><br/>
Arrival Date:<input type="date" name="arrdate" value="<?php echo $row['arr_date']; ?>"/><br/>
Arrival time at destination:<input type="time" name="arrtime" value="<?php echo $row['arr_time']; ?>"/><br/>
Car Model and name:<input type="text" name="cardet" value="<?php echo $row['car_det']; ?>"/><br/> <!--make this as a dropdown box for better database matching-->
Car Number:<input type="text" name="carno" /><br/><input type="checkbox" name="taxi" value="check this box if pooling a taxi">
Is the car self driven or driven by driver?<input type="radio" name="drivedet" value="Selfdriven" checked=""/>Self Driven<input type="radio" name="drivedet" value="driverdriven" />Driver driven<br />
Driver's License number<input type="text" name="licence_no"/></br>
<input type="checkbox" name="taxi" value="check this box if pooling a taxi"></br>
<input type="hidden" name="travelid" value="<?php echo $travelid ;?>" />
<input type="submit" value="invite travellers" name="editwheregoing"/>
</fieldset>
</form>
If only you can change your code, I would suggest you put the form tag itself in the while loop, each having the same action pointing to the same url but submitting different information to the destination page. This way you don't have to worry about the button clicked
while($row=mysqli_fetch_array($result))
{
//<form action="sameactionurl.php" name="form_1">
//<input type="hidden" name="travelid" value="$row['travelid']" />
//</form>
}
Another solution, if you don't want to change your code is use JavaScript to set a common hidden field to the value of the current ID before submitting the form
Name your submit buttons in a standard fashion and append a 3-digit number to the end, "button_XXXX_###" where ### is the number and XXX was the original name of your button.
After submission, check your request parameters for all variables starting with name "button_XXXX", and split the actual name "button_XXXX_####" by '_' character, and the "###" suffix will reveal the number of the button pressed.
It might be easier to create a form for each row instead, though.

Dynamically Hide Form Fields

I have a form for a 'user profile' with the following fields:
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
However, what if I don't want "phone number" and "city" to be visible to a select set of users?
How can I dynamically hide these fields, depending on, say for example, which user is logged in? I am currently using PHP and MySQL. Would it be best to add the "field id's" to the database, and then query the database record to see which fields should be hidden and which fields should be visible? Or is there a better way to do this?
My apologies if this is a bit ambiguous. If it doesn't make sense, I can try to clarify.
Thanks very much.
EDIT: I'd like to clarify what I am trying to achieve. I am trying to dynamically show the fields based on which user logs in. Also, when I said "hidden", I actually should have said "removed." See my example below
E.g.,
If JoeUser logs in, he would see:
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
But, if JaneUser logs in, she would see (based on preferences set in the database):
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
</form>
My question is: What is the best way to achieve this? I'm assuming these preferences need to be database-driven. Any input would be great.
Depending on how you've built the site there are quite a few ways to do this but since you're new to PHP I'll assume that it's just an inline procedural script. In which case you need to check whether or not the user is set in the session and then show or hide depending on the output.
Something similar to the following
<?php if(isset($_SESSION['id'])) : ?>
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
<?php endif; ?>
The if statment checks if a session ID is set (this will likely change depending on how you're handling user sessions etc) and then shows the form.
Edit:
Just noticed that you've edited your original question. To do this you could so something similar to the following, this assumes once again that you're using sessions and that you have the users user type set in a session (not great, but as a beginner it's quick).
<?php if(isset($_SESSION['id'])) : ?>
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
</form>
<?php else if(isset($_SESSION['id']) && (isset($_SESSION['user_type']) && $_SESSION['user_type'] == 'phoneuser')) : ?>
<form>
First Name: <input id="first_name" />
Last Name: <input id="last_name" />
Phone Number: <input id="phone_number" />
City: <input id="city" />
</form>
<?php endif; ?>
You can hide dinamycally on the server side inside php file or try set variable via php for js and operate with fields on the client side via javascript.
Can you explain what you want do with these forms? I don't understood
1) You should use jQuery (don't forget to include this library to head section).
$('#hide_name').click(function() {
$('#first_name').hide('slow', function() {
});
});
First Name: <input type="text" id="first_name" /> <a href="#" id="hide_name" /> Hide name </a>
2) OR next way:
if ($_SESSION['login']) {
$visible = "visibility: visible;";
}
else {
$visible = "visibility: hidden;";
}
First Name: <input type="text" style=<?php echo $visible; ?> />
3) OR easiest way:
if ($_SESSION['login']) {
First Name: <input type="text" id="first_name" />
}
You'll need to store some kind of data that defines what the user sees, or what they don't. Pick whatever feels intuitive based on your data. Once you know the user is logged in, get the data on what to show them. You could make an array of boolean values based on this, let's call it form_fields[]. Then output the form with PHP, and decide what parts to show based on this data, possibly like so:
$form = "<form>\n";
if(form_fields['first_name'])
{
$form .= 'First Name: <input id="first_name" />';
}
if(form_fields['last_name'])
{
$form .= 'Last Name: <input id="last_name" />';
}
if(form_fields['phone'])
{
$form .= 'Phone Number: <input id="phone_number" />';
}
if(form_fields['city'])
{
$form .= 'City: <input id="city" />';
}
$form .= "</form>";
Keep in mind, validating your data gets more complex too - your form processing script will also need to know what fields it's lookling for.

jQuery: find id of of a form field

I am creating a dynamic form where the user will have the ability to add a set of inputs to the form. The html looks like this:
<form>
<input id="title1" class="title" name="title1" type="text" value="">
<input id="productionCompany1" name="productionCompany1" type="text" value="">
<input id="year1" name="year1" type="text" value="">
<input id="role1" name="role1" type="text" value="">
<div id="newCredit"> </div>
add another credit
</form>
When the user clicks the link with the id of "addCredit" the following jQuery script is called:
$(document).ready(function() {
var $ac = $('#addCredit');
$ac.click(function() {
/* the following two lines are where the problem lies? */
var $credInt = $(this).prev(".title");
$.get("addCredit.php", {num: $credInt},
function(data){
$('#newCredit').append(data);});
return false;
});
});
The jQuery function queries a php file called "addCredit.php", which looks like this:
<?php
$int = $_GET["num"];
$int = substr($int, -1);
$int++;
?>
<input id="title<?php echo $int;?>" class="title" name="title<?php echo $int;?>" type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">
My problem is getting the javascript variable $credInt set properly so that it can be sent to the addCredit.php page and update the form fields accordingly. I also need to be sure that every time the form is appended, the next value sent is the incremented value.
Any thoughts on how I might accomplish this? Thank you for your help.
This is the wrong way of doing it; PHP can handle array syntax in a variable name. This makes it much easier to handle. It is also unnecessary to call the server to clone the form. You should name your fields like this:
<form>
<div id="originalCredit">
<input name="title[]" type="text" value="">
<input name="productionCompany[]" type="text" value="">
<input name="year[]" type="text" value="">
<input name="role[]" type="text" value="">
</div>
add another credit
</form>
And then your Javascript can be like this:
$(function() {
$('#addCredit').click(function() {
var newCredit = $('#originalCredit').clone(); // create new set
newCredit.find('input').val(''); // empty input fields
$(this).before(newCredit); // append at the end
return false;
});
});
When the form is finally sent to the server, because the variables are in the format of name[] PHP will recognize they are an array and then you can do this:
<? foreach($_POST['title'] as $k => $v) { ?>
Title: <?=$_POST['title'][$k]?><br>
Company: <?=$_POST['productionCompany'][$k]?><br>
Year: <?=$_POST['year'][$k]?><br>
Role: <?=$_POST['role'][$k]?><br>
<? } ?>
Obviously this is just displaying it as an example, but you can then save/update/whatever with it.

Categories