What I am trying to do is use php to pull a variable number of records from a database. I want to let the user to be able to click on the text and it will switch the text out for an input box and will update the database on submit.
I am aware of how to do this with the onclick attribute, and passing the javascript function the id number that corresponds to the row in the mySQL database. I am trying to determine how I could do this using Unobstrusive Javascript techniques.
Here is the portion of the code that creates the divs, when the user clicks on the zone, account_number, dv or address fields it will switch out the text for the input box as I said above.
while($row = mysql_fetch_array($query)) {
$business_name = $row['business_name'];
$resource_id = $row['resource_id'];
$totaldv += $row['dv'];
if(!in_array($row['zone'], $zoneArray)) {
$zones .= $row['zone'] . " ";
array_push($zoneArray, $row['zone']);
}
$account_numbers .= "
<div>". $row['zone'] . "</div>
<div>" . $row['account_number'] . "</div>
<div>" . number_format($row['dv']) . " kW</div>
<div>" . $row['street_address'] . " " . $row['city'] . ", " . $row['state'] . "</div>
";
}
The problem I am encountering lies in that a customer could have 1 account, or 83 accounts and I need to be able to switch out the correct text for an input box and pass the id of the row from the database to the form. I was thinking of maybe using applying a class to the certain fields?
I have done something like this before, but it was always a static # of inputs, so I was able to hide the text and show the input box which was generated when the page was loaded. Something along the lines of this (granted it was not Unobtrusive)
$content .= "
<tr>
<td width=35><IMG SRC=images/$i.png height=20></td>
<td width=35 id=rank".$i.">$rankImages</td>
<td width=380>
<span id=text".$i." style=\"cursor:pointer;\" onclick=\"editItem($i);\">".$itemArray[$i]."</span>
<span id=$i"."input>
<input id=$i type=text value=".$itemArray[$i].">
<IMG SRC=images/save.png style=\"cursor:pointer;\" onclick=\"saveItem($i);\">
<IMG SRC=images/cancel.png style=\"cursor:pointer;\" onclick=\"cancelEdit($i);\">
</span>
</td>
</tr>";
function editItem(line_num) {
$("#text" + line_num).hide();
$("#" + line_num + "input").show();
}
The way I would go about it would be to use data-* attributes and then access that data using jQuery's .data() function. A shorter, but similar-looking, example of how your HTML might look:
<div class="editable-row" data-row-id="1">
<span class="uneditable">row one</span>
<input type="text" value="row one" />
</div>
<div class="editable-row" data-row-id="2">
<span class="uneditable">row two</span>
<input type="text" value="row two" />
</div>
<div class="editable-row" data-row-id="3">
<span class="uneditable">row three</span>
<input type="text" value="row three" />
</div>
<div class="editable-row" data-row-id="4">
<span class="uneditable">row four</span>
<input type="text" value="row four" />
</div>
And your JavaScript would look like this:
$(document).ready(function () {
$(".editable-row").on("click", function () {
var $this = $(this),
rowId = parseInt($this.data("rowId"), 10);
$this.find("input").show();
$this.find(".uneditable").hide();
// do something with rowId
});
});
Related
Im building a simple element to show search results. I'm using a php function, so I can while-loop the results and display them.
The function is named search_results and looks like this:
<?php
function search_results($u_country, $user_name, $business_user, $brand_name, $product_name, $up_condition, $up_commentary, $up_price, $up_shipping, $up_amount, $up_id) {
$element = "
<div>
<form action='search.php' method='post'>
<div class='search_body'>
<span class='country'>$u_country</span>
<span class='username'>$user_name</span>
<span class='business_user'>$business_user</span>
<span class='product_name'>$product_name</span>
<span class='up_condition'>$up_condition</span>
<span class='commentary'>$up_commentary</span>
<span class='price'>$up_price</span>
<span class='amount'>$up_amount</span>
<span>
<input type='number' name='up_amount' min='1' max='$up_amount' placeholder='1'>
</span>
<span>
<input type='hidden' name='product_id' value='$up_id'>
</span>
<span>
<button type='submit' name='add_cart' disabled='".if(!isset($_SESSION['username']))."'>Warenkorb</button>
</span>
</div>
</form>
</div>
";
echo $element;
};
But I want to implement some php in some of the attributes. For example I want to disable the "add_cart" button if the user is not logged in. But if i use some php inside the html form it always crushes.
if I put the form in single quotes and every attribute in double quotes it won't translate the variables.
my understanding is that i have to end a html string with " and use a . to separate it from the php part, but I can't make it work.
Is there something I'm missing? is it not possible to mix in php into a html form while inside a function?
couldn't find a solution for this and looked through the other threads but couldn't find anything relative.
Sorry if this is a dumb question I'm still learning to code.
if I put the form in single quotes and every attribute in double quotes it won't translate the variables.
I want to further use php inside the attributes of the form to make the results more interactive. For example i want the displayed name of the product to be a link to the product page so it will need to use a variable for that.
Break you code up into bits that do works and use $element .= .... to concatenate the working bits into the variable
For example
function search_results($u_country, $user_name, $business_user, $brand_name,
$product_name, $up_condition, $up_commentary, $up_price,
$up_shipping, $up_amount, $up_id)
{
$element = "<div>
<form action='search.php' method='post'>
<div class='search_body'>";
$element .= "<span class='country'>$u_country</span>
<span class='username'>$user_name</span>
<span class='business_user'>$business_user</span>
<span class='product_name'>$product_name</span>
<span class='up_condition'>$up_condition</span>
<span class='commentary'>$up_commentary</span>
<span class='price'>$up_price</span>
<span class='amount'>$up_amount</span>
<span>
<input type='number' name='up_amount' min='1' max='$up_amount' placeholder='1'>
</span>
<span>
<input type='hidden' name='product_id' value='$up_id'>
</span>
<span>";
$t = ''; // default to not disabled
if(!isset($_SESSION['username'])){
$t = " disabled='disabled' ";
}
$element .= "<button type='submit' name='add_cart' $t>Warenkorb</button>
</span>
</div>
</form>
</div>";
echo $element;
}
step 1: run the code (the button will be disabled)
step 2 refresh the page then the button is not anymore disabled(f5 key,..)
step 3 delete cookies so the button will be disabled again and proceed with the step 2
this is an "environment" to prove you the function can work.
if you really need echo $element; part then drop the return ... and replace it ..
good luck
<?php
function search_results($u_country, $user_name, $business_user, $brand_name, $product_name, $up_condition, $up_commentary, $up_price, $up_shipping, $up_amount, $up_id,$onoff) {
$onoffanswer=($onoff?'disabled':'');
return <<<stuff
<div>
<form action='search.php' method='post'>
<div class='search_body'>
<span class='country'>$u_country</span>
<span class='username'>$user_name</span>
<span class='business_user'>$business_user</span>
<span class='product_name'>$product_name</span>
<span class='up_condition'>$up_condition</span>
<span class='commentary'>$up_commentary</span>
<span class='price'>$up_price</span>
<span class='amount'>$up_amount</span>
<span>
<input type='number' name='up_amount' min='1' max='$up_amount' placeholder='1'>
</span>
<span>
<input type='hidden' name='product_id' value='$up_id'>
</span>
<span>
<button type='submit' name='add_cart' {$onoffanswer}>Warenkorb</button>
</span>
</div>
</form>
</div>
stuff;
};
session_start();
echo search_results(
'country'
,'username'
,'businessuser'
,'brandname'
,'productname'
,'upcondition'
,'commentary'
,'upprice'
,'upshipping'
,'upamount'
,'1111'
,!isset($_SESSION['username'])
);
print_r ($_SESSION);//phpinfo();
$_SESSION['username']='eeee';
?>
I'm really struggling with an RSVP form I'm trying to set-up and any help would be great!
I have this form so far http://adrianandemma.com/ which I am trying to get to send me a simple email once submitted.
The form has a 'Name' field and a radio button for 'Attending - Yes/No'.
I then have some JS whereby you can clone these fields to RSVP for more than one guest at a time.
The 'Name' fields are passing through fine as an array and coming through by email, as I can just set the name attribute of the input to name="name[]", but I'm having trouble with the radio buttons.
I can't leave the 'name' attribute the same for the cloned radio buttons, because if I do I can only select yes/no for one cloned row, as all the cloned radios have the same name, so I have added a bit of JS to try to amend the name of any cloned radios to 'coming[1], coming[2], etc'.
I can't quite get this to work though, as every time I submit the form the radio button values appear to come through blank.
Can anybody advise the best approach to setting up radio buttons as an array and to carry them through via $_POST and ultimately an email script?
Here's my HTML form:
<?php
if(#$_REQUEST['submit'] == '1') {
include('assets/forms/rsvp.php');
}
?>
<form action="?" method="post">
<?php if(#$errors) :?>
<p class="errors"><?php echo $errors; ?></p>
<?php endif; ?>
<input type="hidden" name="submit" value="1" />
<div class="form-row">
<div class="field-l">
<p>Name</p>
</div>
<div class="field-r">
<p>Attending?</p>
</div>
</div>
<div class="form-row guest">
<div class="field-l">
<input type="text" name="name[]" id="name" value="<?php echo htmlspecialchars(#$_REQUEST['name']); ?>" tabindex="1" />
</div>
<div class="field-r">
<input type="radio" name="coming" id="coming-yes" class="coming-yes" value="Yes"><label for="coming-yes">Yes</label><input type="radio" name="coming" id="coming-no" class="coming-no" value="No"><label for="coming-no">No</label>
</div>
</div>
<a class="addguest" href="#">Add further guest</a>
<div class="form-row">
<button type="submit" id="rsvp-submit" tabindex="2">Submit RSVP</button>
</div>
</form>
Hers My Form Process code:
<?php
$name = $_POST['name'];
$coming = $_POST['coming'];
$errors = "";
if(!#$_POST['name']) { $errors .= "Please enter your name.<br/>\n"; }
if(!#$_POST['coming']) { $errors .= "Please enter yes or no for attending.<br/>\n"; }
if(#$_POST['emailaddress'] != '') { $spam = '1'; }
if (!$errors && #$spam != '1')
{
$to = "xxx#example.com";
$subject = "Wedding RSVP";
$headers = "From: noreply#adrianandemma.com";
$body = "The following RSVP has been sent via the website.\n\n";
for($i=0; $i < count($_POST['name']); $i++) {
$body .= "
Name ".($i+1)." : " . $_POST['name'][$i] . "\n
Coming ".($i+1)." : " . $_POST['coming'][$i] ."\n\n";
}
$body .= "\n\nDate Received: " . date("j F Y, g:i a") . "\n";
mail($to,$subject,$body,$headers);
}
?>
Here's my JS:
$(document).ready(function() {
$('.addguest').on('click', function(e) {
e.preventDefault();
//
// get the current number of ele and increment it
//
var i = $('.guest').length + 1;
$('.guest').first().clone().find("input").attr('id', function(idx, attrVal) {
return attrVal + i; // change the id
});
$('.guest').first().clone().find("input[type=radio]").attr('id', function(idx, attrVal) {
return attrVal + i; // change the id
}).attr('name', function(idx, attrVal) {
return attrVal+'['+i+']'; // change the name
}).val('').end().find('label').attr('for', function(idx, attrVal) {
return attrVal + i; // change the for
}).end().insertBefore(this);
});
});
Here's an example of what I'm receiving by email currently, names come through fine, but radio values for 'Coming Yes/No" are all blank:
The following RSVP has been sent via the website.
Name 1 : John Doe
Coming 1 :
Name 2 : Ann Doe
Coming 2 :
Name 3 : Fred Doe
Coming 3 :
Date Received: 19 April 2017, 1:04 am
Honestly, my best guess is that in the original row, the names of your radio inputs are simply "coming", without the brackets. I think that because there are no brackets on that name, it is clobbering the other ones of the same name that should behave as an array. In other words, PHP is getting two conflicting types for an input of the same name, and taking the string over the array.
Hard to say without testing it directly, and the fact that the input is referenced as an array in your PHP form handler and doesn't throw an error would tend to suggest to me I'm not quite right, but it may be worth a try.
Here's the change to the HTML I would try:
<div class="field-l">
<input type="text" name="name[0]" id="name" value="<?php echo htmlspecialchars(#$_REQUEST['name']); ?>" tabindex="1" />
</div>
<div class="field-r">
<input type="radio" name="coming[0]" id="coming-yes" class="coming-yes" value="Yes">
<label for="coming-yes">Yes</label>
<input type="radio" name="coming[0]" id="coming-no" class="coming-no" value="No">
<label for="coming-no">No</label>
</div>
Notice I specifically marked the first row as row zero, as PHP uses zero-indexed arrays.
This would then require some changes to your javascript. I've found it was easier to create an actual template for your row HTML and use that than to try and clone the first row each time and reset all the inputs and adjust the names. The way this works is you define your template HTML inside a script tag with an ID and a type that is non-standard. The browser ignores it, but JavaScript can access it just like any other element and we can pull the content out with jQuery's html() method.
Here's what I've come up with (including a fix of your indexing):
<!-- A script with a non-standard type is ignored by the browser -->
<!-- We can reference it by ID in our JS though, and pull out the HTML -->
<script id="guest-row-template" type="text/template">
<div class="form-row guest">
<div class="field-l">
<input type="text" name="" id="name" class="name-ipt" />
</div>
<div class="field-r">
<input type="radio" name="" id="" class="coming-yes coming-yes-ipt" value="Yes" />
<label for="" class="coming-yes coming-yes-label">Yes</label>
<input type="radio" name="" id="" class="coming-no coming-no-ipt" value="No" />
<label for="" class="coming-no coming-no-label">No</label>
</div>
</div>
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.addguest').on('click', function(e) {
e.preventDefault();
//Get the number of rows we have already - this is the index of the *next* row
//If we have 1 row, the first row's index is 0 and so our next row's index should be
//1, which is also our length, no need to increment
var i = $('.guest').length;
//Get HTML template content for a single row
var row = $('#guest-row-template').html();
//Update the name attribute of the name input
row.find('.name-ipt').attr('name', 'name[' + i + ']');
//Update the name and id attributes of the yes radio button
row.find('.coming-yes-ipt').attr('name', 'coming[' + i + ']');
row.find('.coming-yes-ipt').attr('id', 'coming-yes-' + i);
//Update the name and id attributes of the no radio button
row.find('.coming-no-ipt').attr('name', 'coming[' + i + ']');
row.find('.coming-no-ipt').attr('id', 'coming-no-' + i);
//Update the for attribute of the yes label
row.find('.coming-yes-label').attr('for', 'coming-yes-' + i);
//Update the for attribute of the no label
row.find('.coming-no-label').attr('for', 'coming-no-' + i);
row.insertBefore(this);
});
});
</script>
Please note this is untested code. Of course I've gone through a few times to make sure I caught all my obvious bugs, but others may persist. Since I can't actively test it, I can't say it's entirely bug free. But, hopefully as pseudo-code it helps you resolve the issue.
EDIT 1
Just to clarify, you don't ordinarily have to manually provide the index values within the brackets of input names for PHP to interpret the input as an array and to automatically index the input in the appropriate order. I specifically set the first inputs to have use [0] because all the inputs after them will also need to specify index values in order for your radio buttons to work (I personally appreciate consistency), and because we need to be absolutely sure that the correct names are matched to the correct RSVP value (just trying to be thorough).
So what I am wanting to do have a instant search feed that displays a list of the members in my mysql DB, when the user clicks on an anchor tag what is associated with a row (li) I want to change a varible in another script to be the id of the row which was click. I will provide my scripts below
Index.php
<script>
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
console.log(searchTxt);
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
}
$("#userResults").on("click", "a.employee", function(e) {
e.preventDefault();
$("#editId").val($(this).data("id"));
});
</script>
<h1 class="editUser">Edit User</h1>
<form action="index.php" method="post">
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Name" onkeyup="searchUserQ();" />
<submit type="submit" />
</form>
<div id="userResults">
</div>
<form class="editUser" action="includes/uploadEmployee.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="editId" id="editId">
</form>
This file creates an instant list of search results to my index page and is where the anchor tags are built I want to have change the vars
includes/search.php
<?php
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-id='$id'>Select Employee</a></li>";
echo $output;
This Files is to update the databases when everything is done, right now it only updates row 42
includes/uploadEmployee.php
$selectedId = $_POST['editId'];
$sql = "UPDATE employees SET firstName = '$_POST[editUserFirstName]', lastName = '$_POST[editUserLastName]', password = '$_POST[editUserPW]', permission = '$permission', address = '$_POST[editUserAddress]', email = '$_POST[editUserEmail]', phone = '$_POST[editUserPhone]' WHERE id = $selectedId";
Add
<input type="hidden" name="editId" id="editId">
to the form. When you click on the anchor, it should store the ID into this input field. Then the update script can use $_POST['editId'] to get the ID of the row that should be updated.
Your anchor can be written like this:
echo "<a href='#' class='employee' data-id='$id'>Select Employee</a>";
You can set the hidden field with:
$(document).ready(function() {
$("#userResults").on("click", "a.employee", function(e) {
e.preventDefault();
$("#editId").val($(this).data("id"));
});
});
I'm currently learning AJAX and I've run into this error in which results from MySQL query is not being displayed.
The following snippet is of the javascript :
<script type="text/javascript">
function showCustomers()
{
var zip = document.getElementById('zipcode').value;
var st = document.getElementById('stname').value;
if ((zip=="")&&(st=="")){
document.getElementById("showCustResults").innerHTML="";
return;
}
mlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("showCustResults").innerHTML=xmlhttp.responseText;
}
}
var querystring = "?zip" + zip + "&st" + st ;
xmlhttp.open("POST","findCustomers.php" + querystring, true);
xmlhttp.send();
}
The following is the form in which the information is being pulled from :
<form id="search_customers" class="appnitro" method="post" action="">
<ul>
<li id="li_2" >
<label class="description" for="zipcode">Zip Code </label>
<div><input id="zipcode" name="zip_code" class="element text small" type="text" maxlength="10" value=""/> </div>
<p class="guidelines" id="guide_2"><small>Please enter a Zip Code</small></p>
</li>
<li id="li_1" >
<label class="description" for="stname">Street Name </label>
<div><input id="stname" name="st_name" class="element text medium" type="text" maxlength="50" value=""/></div>
<p class="guidelines" id="guide_1"><small>Please Enter the Street Name</small></p>
</li>
<li class="buttons">
<input id="findCust" class="button_text" onclick="showCustomers()" type="submit" name="find"/>
</li>
</ul>
</form>
<div id="showCustResults"><!-- Eventually search results will appear here --></div>
And the PHP that is pulling the cod is the following:
<?php
include 'functions.php'; #Library that holds all the functions
#Sanitizing strings for SQL entry
$zip = mysqli_real_escape_string($db, $_POST['zip']);
$st = mysqli_real_escape_string($db, $_POST['st']);
$db = db_connect(); #Connecting to the database
#Querying the database to find any matches
#ALSO: We might need to add another column to
$sql = "SELECT CustomerName, ServiceAddress, BillingAddress FROM enrollment_users WHERE UserName = '$username' AND Password = '$password'";
$res = mysqli_query($db, $sql);
#Creating the table to shoot out the information
#First the header...
echo "<table border='1'>";
echo " <tr>";
echo " <th>Customer</th>";
echo " <th>Address 1</th>";
echo " <th>Address 2</th>";
echo " <th>Status</th>";
echo " </tr>";
#Now the actualy information
while($row = mysqli_fetch_assoc($res)){
echo " <tr>";
echo " <td>" . $row['CustomerName'] . "</td>";
echo " <td>" . $row['ServiceAddress'] . "</td>";
echo " <td>" . $row['BillingAddress'] . "</td>";
echo " <td></td>";
}
echo"</table>";
db_close($db); #Closing the database
?>
I've been trying to figure this out for the past day with no avail. Hopefully someone can see what I cannot.
Thanks ahead.
To send post data you have to put it in the send method not the url, they have to be in key=value pairs and you should also encode them with encodeURIComponent, also you have to set the content type to application/x-www-form-urlencoded
var querystring = "zip=" + encodeURIComponent(zip) + "&st=" + encodeURIComponent(phone) ;
xmlhttp.open("POST","findCustomers.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(querystring);
mlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
I did not attempt to run your code but at first glance it looks like you have a typo declaring your xmlhttp variable.
var querystring = "?zip" + zip + "&st" + phone ;
I also see that it would seem your query string is incorrect. AJAX stands for asynchronous javascript and xml (now most commonly replaced with JSON)
you should format your query string with a : between the key and value pairs.
http://www.json.org/
I cannot be sure that these will fix your issue as I have not tried the code but I will give a couple of pointers.
If this is in fact the problem, that would tell me a couple of things.
1. you do not use your browsers developer tools because if you did you would see that an httprequest is never fired if that variable is incorrect.
2. you are developing in a text editor and not an IDE. (this is preferential I am only saying this as an observation not a recommendation necessarily)
I do not know what the purpose of this work is but im assuming you are not allowed to use jquery because the $.ajax method will allow you to clean this code up quite a bit and accomplish what you want in many fewer lines.
I want to change the value of an html text box using javascript. i tried the .value but it doesn't work. then i change the id with no underscore id and change the value and changed the id back to original one value is same as original value no change.
<input id="_item1govt_id" class=" required-entry input-text required-entry input-text required-entry" type="text" value="1" name="address[1][govt_id]" style="display: none;">
echo "<script> function setFunc".$rs['entity_id']."(obj)
{
var e = document.getElementById('_item".$rs['entity_id']."govt_id');
e.id = 'ape".$rs['entity_id']."';
e.value = obj.value;
alert(e.value);
e.id = '_item".$rs['entity_id']."govt_id';
}
</script> "
You can do it using document.getElementById("ID").value = "new value";
It will work even if your id contains _ or number.
Please check if your id in html amd id you used in javascript matches.
If you want to change the html of your text box, then it can be done as follow by using javascript
document.getElementById('textbox_id').innerHTML="New text";
For more info, juct check the basic here.
I think it will help you.
Running your code like below worked fine, have you actually called the function anywhere?
<input id="_item2govt_id" class=" required-entry input-text required-entry input-text required-entry" type="text" value="1" name="address[1][govt_id]" style="display: none;">
<?php
$rs = array('entity_id' => 2);
echo "<script> function setFunc" . $rs['entity_id'] . "(obj)
{
var e = document.getElementById('_item" . $rs['entity_id'] . "govt_id');
e.id = 'ape" . $rs['entity_id'] . "';
e.value = obj.value;
alert(e.value);
e.id = '_item" . $rs['entity_id'] . "govt_id';
}
setFunc" . $rs['entity_id'] . "({value:\"test\"});
</script>";
Note at the bottom I call the setFunc2() method.
Edit
See here for php fiddle working example: http://phpfiddle.org/main/code/7em-jwq
$("#yourTextBoxIdName").val('newValue');