Adding input dynamically, jquery become not working - javascript

I've been searching all over, and actually have found some of similar problem, but still can't manage to solve my problem. I'm still struggling learning jquery and still new.
Anywa, I'm trying to add dynamically an input on a table. So far, I've been able to show the adding of row with the new input text. The input text suppose to have autocomplete function. But the new dynamically added input never succeed to show the autocomplete options.
(To make it clear, I put down the code into JSFiddle, here's the link:
http://jsfiddle.net/yodann/6t74T/637/ )
Here is my code:
<?php
echo '<tr class="row_odd"><td class="ui-widget">';
echo form_input(array('id' => 'aff[]', 'name' => 'aff', 'value' => '',
'class' => 'form-control auto_form', 'placeholder' => 'Masukkan nama tempat',
'style' => 'width:100%'));
echo '</td><td><img src="'.getfrontendlink('images/del_button.png').
'" width="24px" height="auto"></td></tr>';
?>
function addRow() {
var count = $('#aff_table tr').length;
var tx = count % 2 == 0 ? 'row_even' : 'row_odd';
$('#aff_table tr:last').after('<tr class="' + tx + '">' +
'<td class="ui-widget">'+
'</td><td><img src="<?=getfrontendlink('images/del_button.png')?>" width="24px" height="auto"></td></tr>');
var dat = $('#aff_table tr:last').children('td.ui-widget');
$("input.auto_form:last").clone(true).appendTo(dat);
$("input.auto_form:last").val("");
}
<?php
if ($datas != '') {
$i = 0;
$php_array = array();
foreach ($datas->result_array() as $row):
$php_array[$i++] = ($row['pp_id'].'>>'.$row['pp_name'].', '.
(strlen($row['address']) > 25 ? substr($row['address'],0,25) : $row['address']).', '.
$row['city_name'].', '.$row['province_name']);
endforeach;
$js_array = json_encode($php_array);
echo "var availableTags = ". $js_array . ";\n";
}
?>
$( ".auto_form" ).autocomplete({
source: availableTags
});

If I properly understood the problem:
At the end of function addRow() you should init .autocomplete property again.
If you instantiate auto-complete once, then after adding dynamic input field jquery does not automatically add the needed property.
function addRow() {
var count = $('#aff_table tr').length;
var tx = count % 2 == 0 ? 'row_even' : 'row_odd';
$('#aff_table tr:last').after('<tr class="' + tx + '">' +
'<td class="ui-widget">'+
'</td><td><img src="<?=getfrontendlink('images/del_button.png')?>" width="24px" height="auto"></td></tr>');
var dat = $('#aff_table tr:last').children('td.ui-widget');
$("input.auto_form:last").clone(true).appendTo(dat);
$("input.auto_form:last").val("");
$(".auto_form").autocomplete({source: availableTags});
}
tried changing clone to simple append:
http://jsfiddle.net/rk27xbce/

Related

JS/PHP <--> embedded PHP HTML

I’m beginner to JS/PHP/MySQL development. I want to populate a select HTML element with table (nearly 4000 Records) from MySQL DB, relevant code is below.
<body onload="jsonload()">
<label>Beneficier Employee:</label>
<select item class = "BenEmpNo" name = "BenEmpNo" id = "BenEmpNo" onchange="jsEmpNoOnChg()" >
</select>
</body>
<script language="javascript" type="text/javascript">
function jsonload()
{
let jsSelBenEmpNo = document.getElementById("BenEmpNo");
let jsBenEmpNoDataAry;
jsSelBenEmpNo.innerHTML = "<option value='-select-'>-Select-</option>";
oReq = new XMLHttpRequest();
oReq.open('POST', "../php/oh-get_BenEmpNo.php", true);
oReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
oReq.onload = function () {
jsBenEmpNoAry = this.responseText.split('|');
for (let i = 1; i < jsBenEmpNoAry.length; i++)
{
jsBenEmpNoDataAry = jsBenEmpNoAry[i].split('~');
jsSelBenEmpNo.innerHTML += "<option value='" + jsBenEmpNoDataAry[0] +"'>" + "(" + jsBenEmpNoDataAry[0] + ")" + jsBenEmpNoDataAry[1] + "</option>";
}
}
oReq.send("parsparm=" + "|");
}
</script>
</html>
---- PHP ---
<?php
$sql = "select EmpNo, EngName from beneficiary";
$ResultSet = "";
require_once("oh-dbcon.php");
if ($result = mysqli_query($db_con, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$ResultSet = $ResultSet . "|" . $row[0] . "~" . $row[1];
};
$ResultSet = $ResultSet . "~OK";
}else
$ResultSet = "ERROR Result (" . mysqli_error($db_con) . ")-(" . $sql . ")";
mysqli_close($db_con);
echo $ResultSet;
?>***
When I used pure JS (XMLHttpRequest) it takes long time (around 50s) to populate the select, during which the page is froze.
But when using HTML embedded PHP code, it is almost instantly populating the select element (below code).
<label>Beneficier Employee:</label>
<select item class = "BenEmpNo" name = "BenEmpNo" id = "BenEmpNo" onchange="jsEmpNoOnChg()" >
<option value = "-Select-">-Select-</option>
<?php
include("ohdadbcon.php");
$sql_phrase_ben = "select EmpNo, EngName from beneficiary";
$qry_result_ben = #mysqli_query($db_con, $sql_phrase_ben);
while ($row_ben = mysqli_fetch_assoc($qry_result_ben))
{
?>
<option value = "<?php echo $row_ben['EmpNo']?>" >
<?php
echo $row_ben['EngName'] . " | " . $row_ben['EmpNo'] ;
?>
</option>
<?php
}
mysqli_free_result($qry_result_ben);
?>
</select>
I want to use JS request only. Is there any other way or workaround for the slowness to this request?, or I’m doing something wrong here?
2 options... Tweak to only modify the DOM once:
let options = '';
for (let i = 1; i < jsBenEmpNoAry.length; i++)
{
jsBenEmpNoDataAry = jsBenEmpNoAry[i].split('~');
options += "<option value='" + jsBenEmpNoDataAry[0] +"'>" + "(" + jsBenEmpNoDataAry[0] + ")" + jsBenEmpNoDataAry[1] + "</option>";
}
jsSelBenEmpNo.innerHTML = options;
OR
You could also potentially generate the select or options list with PHP, and have THAT returned via AJAX. Then all the JS has to do is add/replace a single element in the DOM. This will move the entire loop to the server instead of the browser.
Though as others have mentioned, 4K items in a drop-down is going to be slow (not to mention very hard to use) just due to the size of the list. I would expect machines with low resources to get a bit choppy when the select is opened.

jquery click event not firing after ajax event

I am having trouble getting my button to click after an ajax call. It works fine before the call. However, when i perform a search and return the data from php, the click event stops working.
I have tried the .on event but this just display the form and not the values. I would be grateful if someone could check my code and see where I am going wrong.
I am aware that the element needs to be in the page and I assumed that after he ajax call the dom would contain the element. Obvously i was wrong.
Many thanks
Order of clicks.
1) page load, .edit click works fine.
2) perform search from #btn-search. Pagintes the table but .edit click is no longer firing.
js code
Get inital values from row. works fine on first click. Not after ajax call to display search results
$(function() {
$('.edit').click(function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
service = currentRow.find("td:eq(1)").html();
activity = currentRow.find("td:eq(2)").html();
dept = currentRow.find("td:eq(3)").html();
company = currentRow.find("td:eq(4)").html();
address = currentRow.find("td:eq(5)").html();
user = currentRow.find("td:eq(6)").html();
item = currentRow.find("td:eq(7)").html();
date = currentRow.find("td:eq(8)").html();
var data = id + "\n" + service + "\n" + activity + "\n" + dept + "\n" + company + "\n" + address + "\n" + user + "\n" + item + "\n" + date;
$("#editForm").dialog("open");
$("#id").val(id);
$("#service").val(service);
$("#activity").val(activity);
$("#dept").val(dept);
$("#company").val(company);
$("#address").val(address);
$("#user").val(user);
$("#item").val(item);
$("#datetimepicker").val(date);
});
});
php backend
<?php
if ($_POST['search1'] == '') {
echo 'enter a search term';
exit;
} else {
$search = $_POST['search1'];
$sqlsrch = mysqli_query($conn, "select * from act where item like '%$search%'");
$numsrch = mysqli_num_rows($sqlsrch);
if ($numsrch == 0) {
// what to do if no results found
echo 'No Results Found';
} else {
while ($rowsrch = mysqli_fetch_array($sqlsrch)) {
$id = $rowsrch['id'];
$service = $rowsrch['service'];
$activity = $rowsrch['activity'];
$dept = $rowsrch['department'];
$company = $rowsrch['company'];
$address = $rowsrch['address'];
$user = $rowsrch['user'];
$box = $rowsrch['item'];
$date = $rowsrch['date'];
$date = date('d/m/Y h:i:s', strtotime($date));
$edit = "<button type='button' class='btn btn-primary edit'>Edit</button>";
$action = "<button type='button' class='btn btn-success action'>Action</button>";
$delete = "<button type='button' class='btn btn-danger delete'>Delete</button>";
// Now for each looped row
echo "<tr><td>" . $id . "</td><td>" . $service . "</td><td>" . $activity . "</td><td>" . $dept . "</td><td>" . $company . "</td><td>" . $address . "</td><td>" . $user . "</td><td>" . $box . "</td><td>" . $date . "</td><td>" . $edit . ' ' . $action . ' ' . $delete . "</td></tr>";
} // End our scale while loop
}
}
?>
jquery search click event
$(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
var search = $("#search").val();
$.ajax({
url: "tabletestajax.php",
method: 'POST',
data: {
search1: search
},
success: function(data) {
$("#search").val('');
$(".paginated tbody").empty();
var result = $.trim(data);
if (result === "enter a search term") {
$("input[name='search']").val(result).css({
'color': 'red'
});
return false;
} else if (result === "No Results Found") {
$(".paginated tbody").html('<div>' + result + '</div>');
return false;
} else {
$(".paginated tbody").html(result);
}
}
});
});
});
Probably you need event delegation
$(document).on('click', '.edit', function(e) {
e.preventDefault();
// code to read selected table row cell data (values).
var currentRow = $(this).closest("tr");
id = currentRow.find("td:eq(0)").html();
.
.
}
Resource
Event delegation .on()

How to convert an object from PHP to an Array in Javascript?

I'm trying to convert an object that I get from PHP into an array in Javascript but I don't know how to solve this, I try some solutions I read before do this question but it doesn't work, I got something like this in PHP
$data = explode(',', $articles);
$length = count($data);
for ($i = 0; $i < $length; $i++) {
$products = explode('-', $data[$i]);
$product_key = $products[0];
$quantity = $products[1];
$get_data_product = mysqli_query($connection, "SELECT * FROM articles WHERE id_article = '".$product_key."' AND id_user = '".$id_user."'") or die (mysqli_error($connection));
$get_data_product = mysqli_fetch_assoc($get_data_product);
$article_name = $get_data_product['name'];
$article_price = $get_data_product['price'];
$info[$i] = array('name' => $article_name, 'quantity' => $quantity, 'price' => $article_price);
}
echo json_encode($info);
And in Javascript
success: function(info) {
var data = JSON.stringify(info);
console.log(data);
}
Console log show this
[{"name":"prueba 2","quantity":"4","price":"100"}]
I tried to read them all with ths code but it is showing data, only when I use console log or alert
$.each(data, function(i) {
$('#content').append('<tr class="text-center">' +
'<td>' + data[i].quantity + '</td>' +
'<td>' + data[i].name + '</td>' +
'</tr>');
});
As prodigitalson notes in the comments - and is effectively the answer - you converted your data into a JSON object in PHP, but then convert it needlessly into a string, so you then can't manipulate it at all.
E.g: JSON.stringify([{test: 1}]) becomes "[{test: 1}]".
Removing that, you will then be able to loop on it in your original way, or you can loop on it using a standard javascript foreach where data is your response in your callback containing [{"name":"prueba 2","quantity":"4","price":"100"}]:
data.forEach(function (e) {
$('#content').append(
'<tr class="text-center">\n' +
'<td>' + e.quantity + '</td>\n' +
'<td>' + e.name + '</td>\n' +
'</tr>\n'
);
});
PHP End Sample Code:
<?php
for ($i = 0; $i < 3; $i++) {
$quantity=rand(5,10);
$price=rand(500,1000);
$info[$i] = array('name' =>'prueba'.$i, 'quantity' =>"$quantity", 'price' => "$price");
}
echo json_encode($info);
?>
JQuery End:
<!DOCTYPE html>
<html>
<head>
<title>Json</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({ type:"POST", url: "array.php", dataType: "json", success: function(result){
console.log(result);
for(i=0; i<result.length;i++)
{
console.log(result[i]);
console.log(result[i].name);
console.log(result[i].quantity);
console.log(result[i].price);
}
}});
});
</script>
</head>
<body>
</body>
</html>
Sample Response in the test:
[{"name":"prueba0","quantity":"8","price":"574"},{"name":"prueba1","quantity":"8","price":"555"},{"name"
:"prueba2","quantity":"7","price":"901"}]
Reference :
http://www.jsoneditoronline.org/?id=5e23cd942a949e86545fa320a65ff0e7
Hope this solves your problem. Thanks.
I think your code is fine, if you do this in javascript code:
success: function(info) {
var data = JSON.stringify(info);
alert(data[0].name);
}
That alert should show the expected value of name property of data object.
your console.log(data); show json arry that is
[{"name":"prueba 2","quantity":"4","price":"100"}]
try this
$dataobj = data1=json_decode(data);
$arry = (array) $dataobj;
try this code

onclick method to dynamically created button in javascript

I am using jquery-mobile package to develop web based mobile application. From a php script I read the button id's from MySQL and send id's to JavaScript method to create a button for it. However I want to add onclick listener also, ofcourse, but I could not manage it.
Any help please.
<div data-role="content2" >
<script type="text/javascript">
function createButton(n) {
$('[data-role="page"]').append('<button data-theme= "b" id="btnInit' + n + '" >' + n + '</button>');// here I want to add onclick listener
}
<?php
include './_fonksiyon.php';
$query = ("
SELECT
tbl_ustmenu.Id AS id,
tbl_ustmenu.AdiT AS adi
FROM tbl_ustmenu
WHERE tbl_ustmenu.Aktif=1
AND tbl_ustmenu.UstMenuId=0
ORDER BY tbl_ustmenu.Sira ASC
");
$result = mysql_query($query);
$count = 0;
while ($count < mysql_num_rows($result)) {
$i = (mysql_result($result,$count, ($id)));
$count++;
?>
createButton(<?php echo ($i) ; ?>);
<?php
}
?>
</script>
</div>
Replace your createButton with the snippet below, or create a separate function using the same snippet.
<script type="javascript">
var button = document.createElement("INPUT");
button.type = "button";
button.name = "button";
button.value = "Click me";
button.id = "<?php echo $i ?>";
button.onclick = function() {
// ...
// function body
};
// you may append it to any element you need
document.body.appendChild(button);
</script>
Save the button to a variable first, it's more readable
var btn = $('<button data-theme= "b" id="btnInit' + n + '" >' + n + '</button>');
btn.click(function() {
alert('here we go');
});
$('[data-role="page"]').append(btn);
add a class to your button and create a bind on click, like this:
$('[data-role="page"]').append('<button class="mybuttonclass" data-theme= "b" id="btnInit' + n + '" >' + n + '</button>');
$(".mybuttonclass").on("click",function(e){
//..
});

issues with ajax and javascript when trying to count marks

I am having an issue with my javascript. I am trying to count marks for each correct chosen answer which is determined from db. If incorrect answer then marks is '0', else mark is dependent on answer's mark in db.
But I am having issues with the javascript:
First of all where it says connect.php, this just simply navigates to page where it connects to db, but is this correct or am I suppose to link to page where it will run query looking up answer's marks?
Second it says I have undefined response in my code and I do not what this should be called.
My question is can I have clarification for the above 2. I am trying to use ajax and javascript and will appreciate if a strong programmer can tackle this issue I am having and be able to correctly set up the code so that it is able to count each correct answer marks.
I have a jsfiddle which I am trying to follow but if somebody can edit fiddle to have a dummy version working for counting marks and then be able to provide code snippet stating what the proper code should be, then this will help me very much.
At moment the jsfiddle determines if answers selected are correct or incorrect and fiddle is here: http://jsfiddle.net/bWthd/3/
Actual code:
PHP/HTML:
$qandaquery = "SELECT q.QuestionId, Answer, AnswerMarks, OptionType
FROM Question q
INNER JOIN Answer an ON q.QuestionId = an.QuestionId
INNER JOIN Option_Table o ON q.OptionId = o.OptionId
WHERE SessionId = ?
GROUP BY q.QuestionId
ORDER BY RAND()";
...
$qandaqrystmt->bind_result($qandaQuestionId,$qandaAnswer,$qandaAnswerMarks,$OptionType);
$arrQuestionId = array();
while ($qandaqrystmt->fetch()) {
$arrQuestionId[ $qandaQuestionId ] = $qandaQuestionId;
}
foreach ($arrQuestionId as $key=>$question) {
?>
<div class="queWrap" data-q_id="<?php echo $key; ?>">
$options = explode('-', $arrOptionType[$key]);
if(count($options) > 1) {
$start = array_shift($options);
$end = array_shift($options);
do {
$options[] = $start;
}while(++$start <= $end);
}
else{
$options = explode(' or ', $option);
}
if($arrReplyType[$key] == 'Single'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="radio"
name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' .
$indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}else if($arrReplyType[$key] == 'Multiple'){
foreach($options as $indivOption) {
echo '<div class="ck-button"><label class="fixedLabelCheckbox"><input type="checkbox" name="options_<?php echo $key; ?>[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><span>' . $indivOption . '</span></label></div>';
}
}
<p><input type='text' class='questionIds' name='questionids' value='<?php echo htmlspecialchars($arrQuestionId[$key]); ?>' /></p>
}
JAVASCRIPT/AJAX:
$(function() {
$('.queWrap .ck-button').change(function() {
var $ch_box = $(this),
$qwrap=$ch_box.closest('.queWrap')
q_id = $qwrap.data('q_id'),
val = $ch_box.val();
var dataToServer = {
q_id: q_id,
valueSelected: val
}
$.post('connect.php', dataToServer,function(){
var status=response.status
$qwrap.find('.status').text( status).addClass(status);
if( status=='correct'){
updateScore( response.points)
}
})
})
function updateScore( newScore){
var score= $points.data('score')+newScore;
$points.data('score',score).text( 'Score: '+score)
}
});
UPDATE:
Current code:
function update() {
var score = 0;
$('.queWrap').each(function(element) {
var $qwrap = $(element),
q_id = $qwrap.data('q_id'),
val = $qwrap.find('input:checked').val();
var dataToServer = {
q_id: q_id,
valueSelected: val
}
$.post('connect.php', dataToServer,function(response){
var status = response.status
$qwrap.find('.status').text(status).addClass(status);
if (status == 'correct'){
score += response.points;
$points.data('score', score).text('Score: ' + score);
}
})
});
}
...
//HTML
<div class="status"> </div>
Ok there is no errors but there is no marks appearing and calculating. Is it because of the connect.php I included in the javascript function. Do I need to navigate to page which connects to db connect.php or navigate to a page where it runs a query on finding answer marks for each selected answer? I am running out of time so can you please implement the code for me asap because I have to get this finished. I want the following to happen:
Count marks for each answer selected, if incorrect answer selected then value is 0 for those answers, if correct answer then it's marks are determined from database. Howcan I get each correct answer button to contain it's own answerId?
To determine answerId we can use the questionId displayed in text input (See PHP/HTML code snippet at top) and then depending on values of each answer button, retrieve the answerid matching the answer values for each question.
Below is example database showing Answer Table
AnswerId (auto PK) QuestionId Answer AnswerMarks
1 72 A 2
2 72 C 1
3 73 B 2
4 73 C 2
5 73 E 1
Your updateScore function works wrong. You should store the points for each question in a data element, and in the updateScore() function you should add all these up, and put the sum into the $points element. Something like this:
$(function() {
$('.queWrap .ck-button').change(function() {
update();
});
function update() {
var score = 0;
$('.queWrap').each(function(element) {
var $qwrap = $(element);
var q_id = $qwrap.data('q_id');
var val = $qwrap.find('input:checked').val();
var dataToServer = {
q_id: q_id,
valueSelected: val
};
$.post('connect.php', dataToServer, function(response){
var status = response.status
$qwrap.find('.status').text(status).addClass(status);
if(status == 'correct'){
score += response.points;
$points.data('score', score).text('Score: ' + score);
}
});
});
}
}
And this function should be invoked on every change of the answers. (I am not sure this works just an example).

Categories

Resources