problems with htmlrows javascript - javascript

I'm trying to make htmlRows to work. When I select productcode I want to trigger func Choise() and fill price and name.
<script>
// get Product Code
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
function fill_productCode($connect)
{
$output = '';
$query = "SELECT * FROM services";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output .= '<option value="' . $row["code"] . '">' . $row["code"] . '</option>';
}
return $output;
}
?>
var count = $(".itemRow").length;
$(document).on('click', '#addRows', function() {
count++;
var htmlRows = '';
htmlRows += '<tr>';
htmlRows += '<td><input class="itemRow" type="checkbox"></td>';
htmlRows += '<td><select id="selectUsers" onChange="Choice();" type="text" name="productCode[]" class="form-control" autocomplete="off"><option value="">Select</option><?php echo fill_productCode($connect); ?></select></td>';
// htmlRows += '<td><input type="text" id="serviceName" name="productName[]" class="form-control" autocomplete="off"></td>';
htmlRows += '<td><input type="text" id="productName_' + count + '" name="productName[]" class="form-control" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="quantity[]" id="quantity_' + count + '" class="form-control quantity" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="price[]" id="price_' + count + '" class="form-control price" autocomplete="off"></td>';
htmlRows += '<td><input type="number" name="total[]" id="total_' + count + '" class="form-control total" autocomplete="off"></td>';
htmlRows += '</tr>';
$('#invoiceItem').append(htmlRows);
});
var serviceName = new Array();
var price_1 = new Array();
var ful = new Array();
serviceName[0] = "";
price_1[0] = "";
ful[0] = "";
serviceName[1] = "Serverių instaliavimas";
price_1[1] = "544.99";
ful[1] = "Buddy Smith";
serviceName[2] = "Sąskaitų skaitmenizavimas";
price_1[2] = "111";
ful[2] = "Libbie Smith";
serviceName[3] = 4;
price_1[3] = "asmith";
ful[3] = "Andy Smith";
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
//x.value = y.options[y.selectedIndex].text;
document.getElementById("serviceName").value = serviceName[y.selectedIndex];
document.getElementById("price_1").value = price_1[y.selectedIndex];
document.getElementById("ful").value = ful[y.selectedIndex];
}
</script>

As mentioned in the comment, it is best to move PHP script to their own page.
PHP - getServices.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
$statement = $connect->prepare("SELECT * FROM services");
$statement->execute();
$result = $statement->fetchAll();
$output = "";
foreach ($result as $row) {
$output .= '<option value="' . $row["code"] . '">' . $row["code"] . '</option>' . "\r\n";
}
echo $output;
?>
You can then GET this via AJAX when needed.
$.get("getServices.php", function(h){
$("#selectUsers").html(h);
});
This would make a GET Request and the PHP would output the HTML back to the request.
It would be better to set this more like an API. Where a GET request can get JSON data back and then manipulate as needed with jQuery.
jQuery
$(function() {
function getData(page) {
var results;
$.getJSON(page, function(data) {
results = data;
});
return results;
}
function addRow(tObj) {
var c = $("tbody tr", tObj).length;
var newRow = $("<tr>");
$("<td>").appendTo(newRow); // 0
$("<input>", {
class: "itemRow",
type: "checkbox"
}).appendTo($("td", newRow));
$("<td>").appendTo(newRow); // 1
var sUser = $("<select>", {
id: "selectUsers",
name: "productCode[]",
class: "form-control",
autocomplete: "off"
}).appendTo($("td", newRow).eq(1));
$("<option>").html("Select User").appendTo(sUser);
// Populate User Options
$.each(getData("getUsers.php"), function(i, u) {
$("<option>", {
value: u.code
}).html(u.name).appendTo(sUser);
});
$("<td>").appendTo(newRow); // 2
$("<input>", {
type: "text",
id: "productName_" + (c + 1),
name: "productName[]",
class: "form-control",
autofill: "off"
}).appendTo($("td", newRow).eq(2));
$("<td>").appendTo(newRow); // 3
$("<input>", {
type: "number",
id: "quantity_" + (c + 1),
name: "quantity[]",
class: "form-control quantity",
autofill: "off"
}).appendTo($("td", newRow).eq(3));
$("<td>").appendTo(newRow); // 4
$("<input>", {
type: "number",
id: "price_" + (c + 1),
name: "price[]",
class: "form-control price",
autofill: "off"
}).appendTo($("td", newRow).eq(4));
$("<td>").appendTo(newRow); // 5
$("<input>", {
type: "number",
id: "total_" + (c + 1),
name: "total[]",
class: "form-control total",
autofill: "off"
}).appendTo($("td", newRow).eq(5));
tObj.append(newRow);
}
$(document).on('click', '#addRows', function() {
addRow($("#invoiceItem"));
});
});
This would be potential PHP code:
PHP - getUsers.php
<?php
$connect = new PDO("mysql:host=localhost;dbname=praktika", "root", "");
$statement = $connect->prepare("SELECT * FROM users");
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach ($result as $row) {
array_push($output, $row);
}
header('Content-Type: application/json');
echo json_encode($output);
$statement = null;
$connect = null;
?>

Related

I can't save specific selected value. it saved all data from database

i am inserting multiple data. what happen is when i select a project from drop down list. it save all data from selection. please check the image below first
function sample($con){
$select = "SELECT * FROM project_tbl";
$select_result = mysqli_query($con,$select);
if (mysqli_num_rows($select_result)> 0) {
while ($row = mysqli_fetch_assoc($select_result)) {
echo "<option value=".$row['project_name'].">" .$row['project_name']."</option>";
}
}
}
*html codes (i used drop down list to populate data from database)
<td class="pro">
<select class="pro">
<option value=""><?php sample($con); ?></option>
</select>
</td>
*ajax codes (adding, saving and removing)
$(document).ready(function(){
var count = 1;
$('#add').click(function(){
count = count + 1;
var html_code = "<tr id='row"+count+"'>";
html_code += "<td class='pro'><select class='pro'><option value=''><?php sample($con); ?></option></select></td>";
html_code += "<td contenteditable='true' class='desc'></td>";
html_code += "<td contenteditable='true' class='comp'></td>";
html_code += "<td contenteditable='true' class='entry'></td>";
html_code += "<td contenteditable='true' class='remarks'></td>";
html_code += "<td><button type='button' name='remove' data-row='row"+count+"' class='btn btn-outline-danger btn-xs remove' title='remove'><i class='fa fa-times' aria-hidden='true'></i></button></td>";
html_code += "</tr>";
$('#crud_table').append(html_code);
});
$(document).on('click', '.remove', function(){
var delete_row = $(this).data("row");
$('#' + delete_row).remove();
});
$('#save').click(function(){
var desc = [];
var pro = [];
var comp = [];
var entry = [];
var remarks = [];
$('.desc').each(function(){
desc.push($(this).text());
});
$('.pro').each(function(){
pro.push($(this).text());
});
$('.comp').each(function(){
comp.push($(this).text());
});
$('.entry').each(function(){
entry.push($(this).text());
});
$('.remarks').each(function(){
remarks.push($(this).text());
});
$.ajax({
url:"insert_inspection.php",
method:"POST",
data:{desc:desc, pro:pro, comp:comp, entry:entry, remarks:remarks},
success:function(data){
alert(data);
$("td[contentEditable='true']").text("");
$('select').prop('selectedIndex',0);
for(var i=2; i<= count; i++){
$('tr#'+i+'').remove();
}
}
});
});
});
Here is what happen when I save.
database
I am new in PHP.
insert_inspection.php
<?php
$con = mysqli_connect("localhost", "root", "", "pms");
if (isset($_POST["desc"])){
$desc = $_POST["desc"];
$pro = $_POST["pro"];
$comp = $_POST["comp"];
$entry = $_POST["entry"];
$remarks = $_POST["remarks"];
$query = '';
for($count = 0; $count<count($desc); $count++){
$desc_clean = mysqli_real_escape_string($con, $desc[$count]);
$pro_clean = mysqli_real_escape_string($con, $pro[$count]);
$comp_clean = mysqli_real_escape_string($con, $comp[$count]);
$entry_clean = mysqli_real_escape_string($con, $entry[$count]);
$remarks_clean = mysqli_real_escape_string($con, $remarks[$count]);
if($desc_clean != '' && $pro_clean != '' && $comp_clean != '' && $entry_clean != '' && $remarks_clean != ''){
$query .= 'INSERT INTO `inspection_tbl`(`description`, `project_name`, `completion`, `entry`, `remarks`) VALUES("'.$desc_clean.'", "'.$pro_clean.'", "'.$comp_clean.'", "'.$entry_clean.'", "'.$remarks_clean.'");
';
}
}
if($query != ''){
if(mysqli_multi_query($con, $query)){
echo 'Item Data Inserted';
}else{
echo 'Error';
}
}else{
echo 'All Fields are Required';
}
}
?>
it is saved as such because your select element only has one option value
modify it from:
<td class="pro"> <select class="pro"> <option value=""><?php sample($con); ?></option> </select> </td>
to:
<td class="pro">
<select class="pro">
<option value=""></option>
<?php sample($con); ?>
</select>
</td>
and modify your select element handler to push only your selected item
something like this:
$('.pro').each(function(){
if($(this).prop("selected")) {
pro.push($(this).text());
}
});
or modify this part to something like:
$(".pro > option:selected").each(function(){
pro.push($(this).text());
});

how to set forloop for function in jquery

I was getting values in due to for each it was repeating same values
----------------------------------------------
<script type="text/javascript">
$(document).ready(function(){
var i=0;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><select name='job_id"+i+"' class='form-control'><option value=''>Select the Job</option><?php
$mysql="select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id."'";
$result1 = mysql_query($mysql) or die(mysql_error());
while($roww = mysql_fetch_array($result1)){
$sql="select * from `ca_job_type` where `jtype_id`= '".$roww['job_type']."'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$row1['jtype_id'].' selected>'.$roww['job_id'].'-'.$row1['job_type_name'].'</option>';
} ?></select></td><td><input name='sac_hsc_code"+i+"' type='text' placeholder='description' class='form-control input-md' /> </td><td><input id='i"+i+"' type='text' placeholder='SAC/HSC Code' class='form-control input-md' ></td><td><select id='employee"+i+"' name='tax_id"+i+"' class='form-control'><option value=''>Please select</option><?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?></select></td><td class='appendData'></td><td><input name='amount"+i+"' type='text' class='form-control amt' id='amount"+i+"' class='form-control input-md' style='text-align: right;' ></td><td><input name='store"+i+"' type='hidden' id='store"+i+"' class='form-control input-md' style='text-align: right;' ></td>"
);
$("#employee"+i).change(function() {
var length = i;
var tax_id = $(this).find(":selected").val();
var dataString = 'tax_id='+ tax_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getEmployee.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
var employee = [employeeData];
----------I think I was getting the error because of this forEach ---------------------------
employeeData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.tax_type+'</td>';
data+= '<td align="right">'+item.tax_Percent+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
}
}
});
});
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
</script>
Same value was repeating in all places. I attached a screenshot for reference. Please help if anybody knows. Thanks in advance
try using following way using for loop
for(var i = 0 ;i <employeeData.length;i++){
$('.appendData').append('<tr><td colspan="4"></td><td align="right">'+employeeData[i].tax_type+'</td><td align="right">'+employeeData[i].tax_Percent+'</td></tr>')
}
If you are sure that your var employeeData has the good value, you can try this maybe :
// new empty data value
var data = "";
// you add one row each time you loop
$.each(employeeData, function(item) {
data += '<tr>';
data += '<td colspan="4"> </td>';
data += '<td align="right">'+item.tax_type+'</td>';
data += '<td align="right">'+item.tax_Percent+'</td>';
data +='</tr>';
});
// when it's over, you append your data where you want.
$('.appendData').append(data);
// An other idea could be to create a "container" div and do :
$('#mycontainer').html(data);
Is it what you are looking for?

Not getting a response from php in ajax handleResponse

I am trying to execute a search on database. My goal is to take a search form and use ajax to request PHP to return a result. Problem is, I am not getting a response in ajax handleRequest function. Also, how do I send back a xml response from php. Here is my code. Sorry for the clutter.
index.php
<!doctype>
<html lang="en">
<head>
<title>Test Form</title>
<script src="js/validate.js"></script>
</head>
<body onload="setfocus();">
<span id="error"></span>
<form id ="searchForm" method="POST" action="/php/validate.php"
onsubmit="event.preventDefault(); process();">
<input type="text" placeholder="Eg. Canada" name="country" id="country_id"
onblur="validate(this.id, this.value);" required/>
<br />
<input type="text" placeholder="Eg. Toronto" name="city" id="city_id"
onblur="validate(this.id, this.value);" required/>
<br />
<label for="featues">Features</label>
WiFi<input type="checkbox" name="wifi" value="wifi" />
TV<input type="checkbox" name="tv" value="tv" />
Breakfast<input type="checkbox" name="breakfast" value="breakfast" />
<br />
<label>Room Type</label>
<select name="roomtype">
<option name="mastersuite" value="mastersuite">Master Suite</option>
<option name="suite" value="suite">Suite</option>
<option name="largeroom" value="largeroom">Large Room</option>
<option name="smallroom" name="smallroom">Small Room</option>
</select>
<br />
<label>Price Range</label>
<input type="text" name="minrange" id="price_min_range_id"
onblur="validate(this.id, this.value);" />
<input type="text" name="maxrange" id="price_max_range_id"
onblur="validate(this.id, this.value);" />
<br />
<label>Stay date</label>
<br />
<label>Arrival Date</label>
<input type="date" name="arrival" id="arrival" placeholder="MM/DD/YYYY"
onblur="validate(this.id, this.value);" required/>
<label>departure Date</label>
<input type="date" name="departure" id="departure" placeholder="MM/DD/YYYY"
onblur="validate(this.id, this.value);" />
<br />
<input type="submit" name="search" value="search">
</form>
<div id="responseDiv"></div>
</body>
</html>
validate.js
var xmlHttp;
//var serverAddr;
//var error;
var response;
function createHttpRequestObject(){
var responseObj;
//for IE
if(window.ActiveX){
var vers = new Array("MSXML2.XML.Http.6.0",
"MSXML2.XML.Http.5.0",
"MSXML2.XML.Http.4.0",
"MSXML2.XML.Http.3.0",
"MSXML2.XML.Http.2.0",
"Microsoft.XMLHttp");
for(var i=0; i<vers.length && !responseObj; i++){
try{
responseObj = new ActiveXObject(vers[i]);
}catch(e){
responseObj = false;
}
}
}
else{ //for all other browser
try{
responseObj = new XMLHttpRequest();
}catch(e){
responseObj = false;
}
}
if(!responseObj || responseObj === false){
alert("Failed to create response object");
}
else{
return responseObj;
}
}
function process(){
xmlHttp = createHttpRequestObject();
if(xmlHttp){
var firstname = encodeURIComponent(
document.getElementById("firstname").value);
var roomtype = encodeURIComponent(
document.getElementById("roomtype").options[
document.getElementById("roomtype").selectedIndex].value);
var minrange = encodeURIComponent(
document.getElementById("price_min_range_id").firstChild.value);
var maxrange = encodeURIComponent(
document.getElementById("price_max_range_id").firstChild.value);
var city = encodeURIComponent(document.getElementById("city_id").firstChild.value);
var country = encodeURIComponent(
document.getElementById("country_id").firsChild.value);
var arrivalDate = encodeURIComponent(
document.getElementById("arrivalDate").value);
var departureDate = encodeURIComponent(
document.getElementById("departureDate").value);
var amenity_breakfast = encodeURIComponent(
document.getElementByName("Breakfast").checked);
var amenity_tv = encodeURIComponent(
document.getElementByName("TV").checked);
var amenity_wifi = encodeURIComponent(
document.getElementByName("wifi").checked);
//get other filed values
xmlHttp.open("POST", "php/validate.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = handleResponse;
xmlHttp.send("firstname=" + firstname + "&roomtype="+ roomtype + "&country="+ country + "&city=" + city + "&minrange=" + minrange + "&maxrange=" + maxrange + "&arrivalDate="+arrivalDate + "&departureDate="+ departureDate + "&breakfast="+
amenity_breakfast + "&tv="+amenity_tv + "&wifi="+ amenity_wifi);
}
else{
alert("Error connecting to server");
}
}
function handleResponse(){
var docdiv = document.getElementById("responsediv");
var table = "";
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//the search info as xml
//var response = xmlHttp.responseXML;
response = xmlHttp.responseXml;
if(!response || response.documentElement){//catching errors with IE, Opera
alert('Invalide Xml Structure:\n'+ response.responseText);
}
var rootNodeName = response.documentElement.nodeName;
if(rootNodeName=="parseerror"){//catching error with firefox
alert('Invalid Xml Structure:\n');
}
var docroot = response.documentElement;
var responseroot = docroot.getElementByTagName("response");
//extracting all hotel values from search
var hotels = new Array(responseroot.getElementByTagName("hotels"));
table = "<table border='1px solid' margin='2px' padding='5px'>";
//docdiv.appendChild(table);
for(var i=0; i<hotels.legnth; i++){
var hotelroot = hotels[i].getElementTagName("name");
var hotelname = hotelroot.firstChild.data;
var hoteladd = hotels[i].getElementByTagName("hoteladd").firstChild.data;
var reqRoomNum = hotels[i].getElementTagName("reqroom").firsChild.data;
table +="<tr>";
//row = table.append(row);
//name column
table += "<td>";
table += hotelname + "</td>";
//address column
table += "<td>";
table += hoteladd + "</td>";
//desired roomttype
table += "<td>";
table += reqRoomNum + "</td>";
//docdiv.createElement("</tr>");
table += "</tr>";
}
table += "</table>";
}
docdiv.innerHTML= table;
}
}
function validate(fieldId, value){
//var error = 0;
//var errortext = '';
switch(fieldId){
/*case 'name':
var chk_name_regex = /^[A-Za-z ]{3,30}$/;
if(value.length<4 &&!chk_name_regex.test(value)){
print_error('Name format wrong',fiedlId);
}
break;*/
case 'country_id':
var chk_country_regex = /^[A-Za-z- ]{4,50}$/;
if(value.length<4 && !chk_country_regex.test(value)){
print_error('Country name format wrong',fieldId);
}
break;
case 'city_id':
var chk_city_regex = /^[A-Za-z- ]{4,50}$/;
if(value.length<4 && !chk_city_regex.test(value)){
print_error('City name format wrong',fieldId);
}
break;
case 'price_min_range_id':
var r = value;
if(r<0){
print_error('Min range must be zero atleast',fieldId);
}
break;
case 'price_max_range_id':
r = value;
if(!(r>=0 && r>=document.getElementById('price_min_range_id').firstChild.value)){
print_error('Max index must be atleast zero or greater than min',fieldId);
}
break;
case 'arrival':
var arrival = value;
var datecomp = arrival.explode("/");
var monthOk = parseInt(datecomp[0])>=1 && parseInt(datecomp[0])<=12;
var getleapday = parseInt(datecomp[2]) % 4===0 &&
parseInt(datecomp[2])%100===0 && parseInt(datecomp[2])%400===0;
var dayOk = parseInt(datecomp[1])>=1 && parseInt(datecomp[2])<=31;
var yearOk = parseInt(datecomp[2])>2015;
if(monthOk && dayOk && yearOk){
print_error('Date format is wrong',fieldId);
}
break;
}
}
function print_error(msg, fieldId){
var errorSpan = document.getElementById('error');
errorSpan.innerHTML = "<p text-color='red'>" + msg + "</p>";
document.getElementById(fieldId).focus();
}
function setfocus(){
document.getElementById('country_id').focus();
}
validate.php
<?php
function just_check(){
print_r($_POST);
}
just_check();
//config script
require_once('config.php');
//vars for all the fileds
$country = $city = $wifi = $tv = $breakfast = $minrange = $maxrange
= $arrival = $departure = $roomtype = '';
//server side input validation
if($_SERVER['REQUEST_METHOD']=='POST'){
$country = inputValidation($_POST['country']);
$city = inputValidation($_POST['city']);
$minrange = inputValidation($_POST['minrange']);
$maxrange = inputValidation($_POST['maxrange']);
$arrival = inputValidation($_POST['arrivalDate']);
$departure = inputValidation($_POST['departureDate']);
$roomtype = $_POST['roomtype'];
if(isset($_POST['wifi'])){
$wifi = true;
}
if(isset($_POST['tv'])){
$tv = true;
}
if(isset($_POST['breakfast'])){
$breakfast = true;
}
}
//echo $country . " " . $city . '<br >';
//connect to mysql
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME)
or die('Could not connect to db');
//query the database matching fields;
$query = "SELECT hotel_id, hotel_name FROM allhotels WHERE ";
//echo $query . '<br />';
if(isset($country)){
$query .= "(hotel_country='$country') AND";
}
//echo $query . '<br />';
if(isset($city)){
$query .= " (hotel_city='$city') AND";
}
$query = substr($query,0, -4);
// echo $query . '<br />';
$res = $db->query($query);
//echo $query . '<br />';
if(!$res){
echo $db->errno . '->' . $db->error;
}
//setting header to XML
header('ContentType: text/xml');
//creating XML response string"
$dom = new DOMDocument();
$response = $dom->createElement("response");
$dom->appendChild($response);
while($row = $res->fetch_array(MYSQLI_ASSOC)){
//matching room field value for query
$roomfield='';
if($roomtype == 'mastersuite'){
$roomfield = 'hotel_master_suites';
}
else if($roomtype == 'suite'){
$roomfield = 'hotel_suite';
}
else if($roomtype == 'largeroom'){
$roomfield = 'hotel_large_rooms';
}
else{
$roomfield = 'hotel_small_rooms';
}
//query with the roomfield and hotel_id value
$htl_id = $row['hotel_id'];
$subquery = "SELECT hotel_add, $roomfield FROM spechotel WHERE ".
"(hotel_id = $htl_id) AND ($roomfield > 0) AND";
if(isset($wifi)){
$subquery .= " (wifi=1) AND";
}
//echo $subquery . '<br />';
if(isset($tv)){
$query .= " (tv=1) AND";
}
//echo $query . '<br />';
if(isset($breakfast)){
$query .= " (breakfast=1) AND";
}
//echo $query . '<br />';
$subquery = substr($subquery,0, -4);
// echo $query . '<br />';
//echo $subquery . '<br />';
$subrow = $db->query($subquery);
$subrow = $subrow->fetch_array(MYSQLI_ASSOC);
$hotel_header = $dom->createElement("hotels");
$hotel_name = $dom->createElement("name");
$hotel_name->appendChild($dom->createTextNode($row['hotel_name']));
$hotel_add = $dom->createElement("hoteladd");
$hotel_add->appendChild($dom->createTextNode($subrow['hotel_add']));
//$hotel_postal = $hotel_header->apppendChild("hotelpostal");
//$hotel_postal->createTextNode($subrow['']);
$hotel_req_room = $dom->createElement("reqroom");
$hotel_req_room->appendChild($dom->createTextNode($subrow[$roomfield]));
$hotel_header->appendChild($hotel_name);
$hotel_header->appendChild($hotel_add);
$hotel_header->appendChild($hotel_req_room);
}
$xmlString = $dom->saveXML();
//print table
$db->close();
//close connection
//return search
function print_search_result(){
global $xmlString;
echo $xmlString;
}
print_search_result();
function inputValidation($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

After insert id in textbox click enter fill data in html table using ajax php sql

I need to fill all matching records in a table after inserting id in textbox. But currently I am getting only one record.
php
<?php
$id=$_POST['userID'];
$db_host = 'jo\SQL2005';
$db_username = 'jo';
$db_password = '123321';
$db_name = 'db_test2';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
$query=mssql_query("select * from address where user_id='$id'");
$result=mssql_fetch_assoc($query);
$json= array('id'=>$result['id'],'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],'Phone_number'=>$result['Phone_number']);
echo json_encode($json);
exit;
?>
javaScript
function getname()
{
var id=$("#userID").val(); // get the id from textbox
$.ajax({
type:"post",
dataType:"json",
data:"userID="+id,
url:"address_json_data.php",
success:function(json)
{
$("table.imagetable").
append("<tr><td>" + json.user_id + "</td><td>" +
json.street + "</td></tr>");
}
});
}
html
<input name="userID" id="userID" onChange="getname()" type="text" />
<table border='1'class="imagetable">
<tr><th>id</th><th>email</th></tr>
</table>
Any Help Very Thanks
replace this code:
$query=mssql_query("select * from address where user_id='$id'");
$result=mssql_fetch_assoc($query);
$json= array('id'=>$result['id'],'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],'Phone_number'=>$result['Phone_number']);
with this:
$query=mssql_query("select * from address where user_id='$id'");
while($result=mssql_fetch_assoc($query))
{
$json[]= array(
'id'=>$result['id'],
'user_id'=>$result['user_id'],
'street'=>$result['street'],
'quarter'=>$result['quarter'],
'Phone_number'=>$result['Phone_number']
);
}
And in your javascript:
success:function(json)
{
var str = '';
for(var x in json)
{
str += "<tr>";
str += "<td>" + json[x].user_id + "</td>";
str += "<td>" +json[x].street + "</td></tr>";
}
$("table.imagetable").append(str);
}

nested categories dropdown in magento

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:
Helper area:
public function getCategoriesDropdown() {
$categoriesArray = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'))
->load()
->toArray();
foreach ($categoriesArray as $categoryId => $category) {
if (isset($category['name'])) {
$categories[] = array(
'label' => $category['name'],
'level' =>$category['level'],
'value' => $categoryId
);
}
}
return $categories;
}
PHTML File:
<select id="category-changer" name="category-changer" style="width:150px;">
<option value="">--Select Categories--</option>
<?php
$_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
foreach($_CategoryHelper as $value){
foreach($value as $key => $val){
if($key=='label'){
$catNameIs = $val;
}
if($key=='value'){
$catIdIs = $val;
}
if($key=='level'){
$catLevelIs = $val;
$b ='';
for($i=1;$i<$catLevelIs;$i++){
$b = $b."-";
}
}
}
?>
<option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
<?php
}
?>
</select>
this code generates a dropdown with categories and subcategories. like this one:
my main idea is to create n level nested chained dropdowns for subcategories like this example:
or this layout would be better:
any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated
brgds!
Here is my way:
In helper class, add method:
public function getCategoriesDropdown() {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('name')
->addAttributeToSort('path', 'asc')
->addFieldToFilter('is_active', array('eq'=>'1'));
$first = array();
$children = array();
foreach ($categories->getItems() as $cat) {
if ($cat->getLevel() == 2) {
$first[$cat->getId()] = $cat;
} else if ($cat->getParentId()) {
$children[$cat->getParentId()][] = $cat->getData();
}
}
return array('first' => $first, 'children' => $children);
}
In PHTML File:
<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
var children = $H(<?php echo json_encode($tree['children']) ?>);
function showCat(obj, level) {
var catId = obj.value;
level += 1;
if ($('cat_container_' + level)) {
$('cat_container_' + level).remove();
}
if (children.get(catId)) {
var options = children.get(catId);
var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
for (var i = 0; i < options.length; i++) {
html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
}
html += '</select>';
html = '<div id="cat_container_' + level + '">' + html + '</div>';
$('sub_cat').insert(html);
}
}
</script>
<select id="first_cat" onchange="showCat(this, 2)">
<?php foreach ($tree['first'] as $cat): ?>
<option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
<?php endforeach ?>
</select>
<div id="sub_cat"></div>
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
$html .= getChildrenCategoryOptions($_category->getId());
}
return $html;
}
else {
return '';
}
}
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);
function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();
if( $_categoryCollection->count() > 0 ) {
foreach($_categoryCollection as $_category) {
$array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
$array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
}
return $array;
}
else {
return array();
}
}

Categories

Resources