I would like Javascript to alert the whole employee name (first and last names) but with this code, it only shows the first name for some reason. Any Ideas on how to fix this problem?
Here's my code:
if ( $even1 % 2)
echo "<option value=". $employee_firstname . " " . $employee_lastname . ">". $employee_firstname . " " . $employee_lastname . "</option>";
else
echo "<option value=". $employee_firstname . " " . $employee_lastname . ">". $employee_firstname . " " . $employee_lastname . "</option>";
The javascript:
var List = document.getElementById('slcEmp');
var x = 0;
for (x = 0; x < List.length; x++) {
if (List[x].selected) {
alert(List[x].value);
}
}
You need to put the attribute value in quotes, since it contains a space:
echo "<option value='". htmlentities($employee_firstname) . " " . htmlentities($employee_lastname) . "'>". $employee_firstname . " " . $employee_lastname . "</option>";
^ ^
You should also use htmlentities() in case the name contains special characters (e.g. O'Leary).
Related
I have a table associated with a database mysql, All I want is to add a search box by date.
Although I have tried many methods, but unfortunately all of them did not work for me as I should This is my code:
<form action="" method="GET"">
<input type="date" name="search" class="form-control" placeholder="Start" >
<button type="submit" class="btn btn-primary">Search</button>
</form>
function getRecords($params)
{
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) {
$page = $params['current'];
} else {
$page = 1;
}
$start_from = ($page - 1) * $rp;
$sql = $sqlRec = $sqlTot = $where = '';
if (!empty($params['searchPhrase'])) {
$where .= " WHERE ";
$where .= " ( fullname LIKE '" . $params['searchPhrase'] . "%' ";
$where .= " OR email LIKE '" . $params['searchPhrase'] . "%' ";
$where .= " OR phone LIKE '" . $params['searchPhrase'] . "%' )";
}
if (!empty($params['sort'])) {
$where .= " ORDER By " . key($params['sort']) . ' ' . current($params['sort']) . " ";
}
// getting total number records without any search
$sql = "SELECT * FROM `api` where DATE_FORMAT(created_at, '%Y-%m-%d') = DATE_SUB(CURRENT_DATE(),INTERVAL 1 DAY)";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if (isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp != -1)
$sqlRec .= " LIMIT " . $start_from . "," . $rp;
}
<script>
$(document).ready(function(){
$("#btn-tambah-form").click(function(){
var jumlah = parseInt($("#jumlah-form").val());
var nextform = jumlah + 1;
$("#insert-form").append(
"<div class='row mb-10 p-10'>" +
" <div class='input-group col-md-2'>" +
" <?php $result = mysqli_query($conn, 'SELECT * FROM produk');?>" +
" <?php $jsArray = 'var idproduk = new Array();\n';?>" +
" <select class='form-control select2' id=\'idproduk"+nextform+"\' name=\'idproduk[]\' onchange=\'changeProduk"+nextform+"(this.value),sum();\' required>" +
" <option></option>" +
" <?php while ($row = mysqli_fetch_array($result)) {?>" +
" <?php echo '<option value=\'' . $row['idproduk'] . '\'>' . $row['produk_nama'] . '</option>';?>" +
" <?php$jsArray .= 'idproduk[\'' . $row['idproduk'] . '\'] = {harga_beli:\'' . addslashes($row['harga_beli']) . '\',produk_satuan:\'' . addslashes($row['produk_satuan']) . '\'};\n';?>" +
" <?php }?>" +
" </select>" +
" </div>" +
"</div>");
$("#jumlah-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#jumlah-form").val("1");
});
});
</script>
can someone help me. why my select2 not active when i put them on javascript.
when i put them outside java they can run correct.
please help me how to solve this code.
There is problem with backslashed quotes, remove them. It should be all.
<select class='form-control select2' id='idproduk"+nextform+"' name='idproduk[]' onchange='changeProduk"+nextform+"(this.value),sum();' required>" +
the response comes back as "4" instead of just 4
I tried changing it to .done(function(data)) but still has the same result
$.ajax({
url: "../api/ajax/addToCart.php",
type: "post",
data: data
})
.done(function(response) {
// alert(response);
$('#cart_counter').html(response);
// console.log(JSON.parse(response));
getCart();
// console.log(response);
});
the ajax is taking the response from this page
addToCart.php
$sql1 = 'DELETE FROM temp_cart WHERE item_id = "' . $item_id . '" AND temp_id = "' . $temp_id . '"';
$result = $conn->query($sql1);
{
$sql2 = 'INSERT INTO temp_cart(temp_id, temp_name, temp_number, item_name, item_price, item_quantity, item_total, item_pic, item_id, date_expiry) VALUES ("' . $temp_id . '", "' . $temp_name . '", "' . $temp_number . '", "' . $item_name . '", "' . $item_price . '", "' . $item_quantity . '", "' . $total_row . '", "' . $item_pic . '", "' . $item_id . '", "' . $date_expiry . '" )';
$result = $conn->query($sql2);
{
$sql = "SELECT count(item_quantity) as count_quantity FROM temp_cart WHERE temp_id='$temp_id'";
$resultb = $conn->query($sql);
while($rowb = $resultb->fetch_assoc())
{
$cart_counter=$rowb['count_quantity'];
echo json_encode($cart_counter);
}
}
}
The data not really JSON format, but a number that is being stringified when you pass it back as JSON so it ends up a string. Just parse the string into a number as needed:
$('#cart_counter').html(parseInt(response));
let counter = 4;
let json = JSON.stringify(counter);
console.log(json, `is a ${typeof json}`);
console.log(`...now a ${typeof parseInt(json)}`);
document.querySelector('#target').innerHTML = parseInt(json);
<div id="target"></div>
I am using a date picker in PHP, but I experience a small problem.
When selecting a month, I automatically submit the form to change the amount of days:
<script>
function change()
{
document.getElementById("datepickerform").submit();
}
</script>
But, when I press submit, I also want to execute some extra code (querying a database for some info with the selected date.
Is there a way to make a difference when the OK button is pressed or when the form is "submitted" via the function above?
Hereunder is the entire code (not finished, leap year also not included yet) of my datepicker.php:
<script>
function change(){
document.getElementById("datepickerform").submit();
}
</script>
<?php
// Include global Definitions and variables
// http://stackoverflow.com/questions/18179067/select-from-drop-down-menu-and-reload-page
// Form
define("FORM_DAY", "theday");
define("FORM_MONTH", "themonth");
define("FORM_YEAR", "theyear");
// Date related
$days = array(31,28,31,30,31,30,31,31,30,31,30,31);
// Get result from FORM POST
$submittedday = $_POST[FORM_DAY];
$submittedmonth = $_POST[FORM_MONTH];
$submittedyear = $_POST[FORM_YEAR];
if ($submittedday != '')
{
$currentday = $submittedday;
$currentmonth = $submittedmonth;
$currentyear = $submittedyear;
}
else
{
$currentday = intval(date("d"));
$currentmonth = intval(date("m"));
$currentyear = intval(date("Y"));
}
//DEBUG ON
echo $submittedday."/".$submittedmonth."/".$submittedyear."<br>\r\n";
echo $currentday."/".$currentmonth."/".$currentyear."<br>\r\n";
// DEBUG OFF
echo '<form id="datepickerform" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo '<table border="1" cellpadding="2">';
echo '<tr><td>';
echo '<table border="0" cellpadding="2">';
echo '<tr><th>Day</th><th>Month</th><th>Year</th></tr>';
echo '<tr>';
echo '<td><select name=' . FORM_DAY . '>';
$i = 1;
for ($i==1; $i<=$days[$currentmonth-1]; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentday)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_MONTH . ' onchange="change()">';
$i = 1;
for ($i==1; $i<=12; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentmonth)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_YEAR . '>';
$i = 2015;
for ($i==2015; $i<=2020; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentyear)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '</tr>';
echo '</table>';
echo '</td></tr>';
echo '<tr><td align="middle">';
echo '<input type="submit" value="OK"></td>';
echo '</td></tr>';
echo '</table>';
echo '</form>';
?>
Could anybody help?
Most JS libraries that preform AJAX calls pass an extra header with the request, typically X_REQUESTED_WITH with a value of XMLHttpRequest. If you were using something like jQuery you can check for this using PHP, or you could just use a hidden field that your JS creates and fills in when it is submitted that way.
function change()
{
var form = document.getElementById('datepickerform'),
el = document.createElement('input');
el.type = 'hidden';
el.name = 'js';
el.value = '1';
form.appendChild(el);
form.submit();
}
And then when handling in PHP, use
if (isset($_POST['js'])) {
// ...
}
You can Keep a hidden field in form and if the form is beig submitted using js then change the value of hidden field before submitting the form.
You could change it so that there is an Ajax call when the month changes, and use a button that can be used to invoke processing prior to submit.
Thanks for the above tips, this solved my problem. Also Change value of input then submit form in javascript helped solving my problem.
<script>
function change(){
document.getElementById("datepickerform").submitform.value = '1';
document.getElementById("datepickerform").submit();
}
</script>
<?php
// Include global Definitions and variables
// https://stackoverflow.com/questions/18179067/select-from-drop-down-menu-and-reload-page
// Form
define("FORM_DAY", "theday");
define("FORM_MONTH", "themonth");
define("FORM_YEAR", "theyear");
// Date related
$days = array(31,28,31,30,31,30,31,31,30,31,30,31);
// Get result from FORM POST
$submitform = $_POST["submitform"];
$submittedday = $_POST[FORM_DAY];
$submittedmonth = $_POST[FORM_MONTH];
$submittedyear = $_POST[FORM_YEAR];
if ($submittedday != '')
{
$currentday = $submittedday;
$currentmonth = $submittedmonth;
$currentyear = $submittedyear;
}
else
{
$currentday = intval(date("d"));
$currentmonth = intval(date("m"));
$currentyear = intval(date("Y"));
}
//DEBUG ON
echo $submitform."<br>\r\n";
echo $submittedday."/".$submittedmonth."/".$submittedyear."<br>\r\n";
echo $currentday."/".$currentmonth."/".$currentyear."<br>\r\n";
if ($submitform == '0')
{
echo 'Button pressed.<br>';
}
else
{
echo 'Javascript executed.<br>';
}
// DEBUG OFF
echo '<form id="datepickerform" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo '<table border="1" cellpadding="2">';
echo '<tr><td>';
echo '<table border="0" cellpadding="2">';
echo '<tr><th>Day</th><th>Month</th><th>Year</th></tr>';
echo '<tr>';
echo '<td><select name=' . FORM_DAY . '>';
$i = 1;
for ($i==1; $i<=$days[$currentmonth-1]; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentday)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_MONTH . ' onchange="change()">';
$i = 1;
for ($i==1; $i<=12; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentmonth)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_YEAR . '>';
$i = 2015;
for ($i==2015; $i<=2020; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentyear)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '</tr>';
echo '</table>';
echo '</td></tr>';
echo '<tr><td align="middle">';
echo '<input type="hidden" name="submitform" value="0">';
echo '<input type="submit" value="OK"></td>';
echo '</td></tr>';
echo '</table>';
echo '</form>';
?>
I'm using PHP to pass variables into the onclick of an element, however when I do this I get an "Unterminated string literal" error of the string is too long. My PHP is as follows:
$query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ID FROM gallery ORDER BY ID desc");
$query->execute();
$query->bind_result($name, $img, $desc, $link, $price, $id);
while($query->fetch())
{
if(strlen($desc) > 100)
{
$sdesc = substr($desc, 0, 100) . '...';
}
$onclick = 'popup(\'' . $name . '\', \'' . $desc . '\', \'' . $price . '\', \'' . $img . '\', \'' . $link . '\', ' . $id . ')';
echo '<div class="gallery" onclick="' . $onclick . '">
<img src="' . $img . '" alt="' . $name . '" />
<div><p>' . $sdesc . '</p>
' . $price . '
</div></div>';
}
My jQuery is as follows
function popup(title, desc, price, img, link, id)
{
$(".popupbodyg").children().remove();
var HTML = '<input type="image" src="close.gif" id="close" /><div><div id="comments">' +
'<iframe src="comments.php?id=' + id + '"></iframe><br /><input type="image" id="share" src="Very-Basic-share-icon.png" /></div>' +
'<div id="desc"><p>' + desc + '</p><br />' +
'<a class="gallery" href="' + link + '" target="_blank">' + price + '</a></div>' +
'<div id="img"><img src="' + img + '" alt="' + title + '"/></div></div>';
$(".popupbodyg").append(HTML);
$("#popup").toggle();
$(".popupbodyg #img").css("width", $(".popupbodyg").width() - 230 + "px");
$(".popupbodyg #img").css("height", $(".popupbodyg").height() - ($("#desc").height - 5) + "px");
$("#close").click(function(){
$("#popup").hide();
});
$("#share").click(function(){
$("#sharepopup").show();
$("#sharepopup").find("#link").attr("value", "http://www.encantojewellerydesign.com/gallery/?g=" + id);
$("#sharepopup").find(".fb-share-button").attr("data-href", "http://www.encantojewellerydesign.com/gallery/?g=" + id);
$("#sclose").click(function(){
$("#sharepopup").hide();
});
});
}
The only way I can think of right now is by limiting the amount of characters in the description, which I would like to avoid.
Did you try any of the string replace methods that are found elsewhere on SO?
$desc=str_replace("\n","\\n",$desc); //I'm guessing that the newline would probably be in the description if anywhere in the data you're passing.
ALSO:
Another slightly different approach would be to just embed the data into your element and retrieve the data with a single click handler that passes it to your popup function.
In other word, you could change the div.gallery look like this:
<div class="gallery" data-name=".$name." data-img=".$img." data-desc=".$desc." data-link=".$link." data-price=".$price." data-id=".$id.">
Then add an click handler like this:
$('gallery').on('click', function() {
var name = $(this).data('name');
var img = $(this).data('img');
var desc = $(this).data('desc');
var link = $(this).data('link');
var price = $(this).data('price');
var id = $(this).data('id');
popup(title, desc, price, img, link, id);
});
I am assuming that it has to do with the extra html characters that $description and other variables are passing to yout js. Try may be something like this(for a better answer, post a dump of the variables you are passing):
<?php
$query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ID FROM gallery ORDER BY ID desc");
$query->execute();
$query->bind_result($name, $img, $desc, $link, $price, $id);
while($query->fetch())
{
if(strlen($desc) > 100)
{
$sdesc = substr($desc, 0, 100) . '...';
}
$onclick = 'popup(\'' .strip_everything( $name ). '\', \'' . strip_everything($desc ). '\', \'' .strip_everything $price) . '\', \'' . $img . '\', \'' . $link . '\', ' . $id . ')';
echo '<div class="gallery" onclick="' . $onclick . '">
<img src="' . $img . '" alt="' . $name . '" />
<div><p>' . $sdesc . '</p>
' . $price . '
</div></div>';
}
function strip_everything($str){
$str = strip_tags($str);
return str_replace("\n" , ' ' , $str);
}