Json result "undefined" when attempting to dynamically populate select list - php

I am attempting to add dynamic rows with a product and a price to an order form with Jquery. The issue is that I need the product dropdown to be dynamically filled from mysql. The rows are adding correctly. The only problem I am having how is that the dropdown menu only has one option and that option says "undefined".
EDIT 1 : I changed the PHP code. I think it is formatted correctly now but I am still getting "undefined" in my select list.
EDIT 2 : I tested the php and there were some errors. Now the php works perfectly on its own and returns the following json encoded array, but when I am attempting to pull it into my jquery script it is still returning an "undefined" result. :
[{"product":"wedding 4","price":"400.00","id":"9"},
{"product":"wedding 2 ","price":"400.00","id":"8"},
{"product":"Wedding 1","price":"4000.00","id":"1"},
{"product":"potato","price":"50.00","id":"6"},
{"product":"Event","price":"3000.00","id":"5"},
{"product":"alligator","price":"800.00","id":"7"}]
jQuery:
var count = 0;
$(document).ready(function(){
$('p#add_field').click(function(){
count += 1;
$('#addingContainer').append('<strong>Link #' + count + '</strong><br />' + '<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" >');
$.get('includes/productrow.php', function(data){
$('#product_' + count + '').append('<option value=' + data.product_id + ' data-price=' + data.price + '>' + data.product +'</option>');
});
$('#addingContainer').append('</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" >');
});
productrow.php
<?php
$productSql = "SELECT product_id, product, price FROM products WHERE compid = '$compid' ORDER BY product desc";
$productResult = mysql_query($productSql, $link);
while($productRow = mysql_fetch_array($productResult)){
$final_array[] = array("product" => $productRow['product'], "price" => $productRow['price'], "id" => $productRow['id']);
};
echo json_encode($final_array);
?>
** Disclaimer, I know I should be using PDO and as soon as this project is finished I will begin using it.

I always use jquerys $.get:
$.get('includes/productrow.php', function(resp){
$('#yourid').append(resp);
});
Try if you could implement this.
Use it like this:
$.get('includes/productrow.php', function(resp){
$('#addingContainer').append('<strong>Link #' + count + '</strong><br />' + '<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" /><option value=""></option>' + resp + '</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" >');
});
Hope this works!
I made the following files to test it:
<html>
<head>
<script type="text/javascript" src="../server/public/js/jquery.js"></script>
<script type="text/javascript">
$.get('productrow.php', function(resp){
$('body').append('<strong>Link #</strong><br />' + '<label>Product or Service</label><select id="product_" name="products[]'+ '" /><option value=""></option>' + resp + '</select> <label>Price</label><input type="text" id="price_" name="prices[]' + '" class="price" >');
});
</script>
</head>
<body>
</body>
</html>
productrow.php:
<?php
echo "test";
result:
Link #
Product or Servicetest Price
the test is there as expected. Could you send me your whole code or create a jsfiddle

The problem was in the JSON request. The corrected code is below. This code also allows a text field with the price of the product to be automatically populated using the data-price attribute:
Jquery:
var count = 0;
$(document).ready(function(){
$('p#add_field').click(function(){
count += 1;
$('#addingContainer').append('<strong>Link #' + count + '</strong><br />' + '<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" ><option value=""></option>');
$.getJSON('includes/productrow.php', function(data){
var select = $('#product_' + count + '');
$.each(data, function(key, val) {
$('<option/>').attr('value', val.product_id)
.attr('data-price', val.price)
.html(val.product)
.appendTo(select);
});
$('#addingContainer').append('</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" >');
});
productrow.php
$productSql = "SELECT product_id, product, price, compid FROM products WHERE compid = '$compid' ORDER BY product desc";
$productResult = mysql_query($productSql, $link);
while($productRow = mysql_fetch_array($productResult)){
$final_array[] = array("product" => $productRow['product'], "price" => $productRow['price'], "id" => $productRow['product_id']);
};
echo json_encode($final_array);

Related

Looping Issue - AJAX/jQuery

So i spent some time over night adding user pictures to a voting feature we have, and all is working nicely, however we notice that as users pictures show up as who voted, it repeats the results twice, instead of a row of pictures going across per item.
So per item, users picture (who voted on the poll ID) shows up but duplicates the row.
Does this have to do with $.each() ? How can I iterate the photos across each row (id column) without creating a copy of the answer and not show only 1 picture?
function fetchPollData() {
$(function(){});
$.ajax({
url: "ajax_pollresults.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
var scase = (item.votes > 1) ? 'votes' : 'vote';
html_to_append +=
'<div class="content poll-result"><div class="wrapper"><div class="poll-question"><p>' +
item.title +
' - <span style="font-weight:bold">' + item.votes + ' ' + scase + ' <img class="tooltip-polluser" title="' + item.username + ' - Voted: ' + item.title + '" href="/user/?id=' + item.user_id + '" style="width:25px;height:25px;border-radius:50%;margin-left:10px;vertical-align:middle" src="/' + item.avatar + '" /></span></p><div class="result-bar" style="width:' + roundVotes(item.votes) + '%"><b>' + item.votes + '</b> ' + scase + ' </div></div></div></div>';
});
$("#recent-poll").html(html_to_append);
$('.tooltip-polluser').tooltipster({
animation: 'grow',
delay: 200,
theme: 'tooltipster-punk'
});
}
});
}
fetchPollData();
setInterval(function () {
fetchPollData()
}, 10000);
The bug we cant figure out a fix for:
It seems it is only showing 1 user per voted item, and ignoring the rest of the row.
our SQL query:
SELECT
poll_answers.id AS id,
IFNULL(poll_users.user_id, '') AS user_id,
IFNULL(users.username, '') AS username,
poll_answers.poll_id,
poll_answers.title,
poll_answers.votes,
poll_users.added AS date,
IFNULL(users.avatar_thumb,
'images/poll_avatarfix.png') AS avatar
FROM
poll_answers
LEFT JOIN
poll_users ON poll_users.poll_id = poll_answers.poll_id
LEFT JOIN
users ON users.user_id = poll_users.user_id
And the database results:
I spent a fair bit of the evening writing this SQL query, so I'm not sure if this is the query not bringing all avatars out or if its jQuery.
Any help is greatly appreciated!
You will want to get each voter image in an inner loop. You can do something like the following...
Instead of using just the one record, call something like getVoteImages() and pass in the poll id you are looking for. This will get all of your images and append them to a string then return it. There may be faster, more elegant ways to do it, but this should work.
$.each(data, function (i, item) {
var scase = (item.votes > 1) ? 'votes' : 'vote';
html_to_append +=
'<div class="content poll-result"><div class="wrapper"><div class="poll-question"><p>' +
item.title +
' - <span style="font-weight:bold">' + item.votes + ' ' + scase + getVoteImages(data, item.poll_id) + "</span></p><div class="result-bar" style="width:' + roundVotes(item.votes) + '%"><b>' + item.votes + '</b> ' + scase + ' </div></div></div></div>';
});
function getVoteImages(data, poll_id) {
var images = "";
$.each(data, function (i, item) {
if (item.poll_id == poll_id) {
images += ' <img class="tooltip-polluser" title="' + item.username + ' - Voted: ' + item.title + '" href="/user/?id=' + item.user_id + '" style="width:25px;height:25px;border-radius:50%;margin-left:10px;vertical-align:middle" src="/' + item.avatar + '" />';
}
});
return images;
}

Input a value in a text box and increment the value in multiple textboxes generated using jquery in php

I have a textbox where I will insert a value , say 100. And when I click on the 'Add' button , list of students appear with a textbox field for each student , which is dynamically fetched from database.
Now in each textboxes appeared, I need to get incremented values based on the number given above,like, 101,102 etc. How it will be possible with jquery. Below is the code I used. Thanks in advance.
//input box for adding the number
<div class="form-group">
<div class="col-lg-2"><b>Start Number</b></div>
<div class="col-lg-5">
<input type="text" name="start_number" id="start_number">
Add
</div>
</div>
//jquery code for loading students with input box for each
var trHTML = '';
var j = 0;
$('#myTable').html('');
trHTML += '<tr></tr><td>' + '<b>id</b>' + '</td><td>' + '<b>Name</b>' + '</td><td>' + '<b>Register Number</b>' + '</td></tr>';
$.each(result, function (i, item) {
j = j + 1;
trHTML += '<tr><td>' + j + '</td><td>' + item.name + '</td><td><input type="text" name="regno" id="regno"></td></tr>';
});
$('#myTable').append(trHTML);
//myTable is the id of the table to which the rows are appended.
When I type 100 in input field, I need to get 101,102 etc in the textboxes appended.
Try this:
var k = 101;
$.each(result, function (i, item) {
j=j+1;
trHTML += '<tr><td>'+j+ '</td><td>'+item.name+'</td><td><input type="text" name="regno" value="'+ (k+i) +'"></td></tr>';
});
You can concatenate index value i + parseInt($('#start_number').val()) (as index is 0 based) in each function as value of input text.
also note that IDs should be unique. you can use same above index to concatenate with id value:
$.each(result, function (i, item) {
trHTML += '<tr><td>'+ (i+1) + '</td><td>'+item.name+'</td><td><input type="text" name="regno" id="regno'+i+'" value="'+ (i+parseInt($('#start_number').val())) +'"></td></tr>';
});

how to get value of input type from dynamic table using jquery

I am working on ecommerce website.
My table gets value from session.
It looks like :
On Checkout I want to get all the values of table.
I have used jquery for this.
Here is my code:
<script>
$('#chhk').on('click',function(e) {
e.preventDefault();
alert('click');
var table = $("#tbl tbody");
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
product = $tds.eq(2).text(),
price = $tds.eq(3).text(),
quantity = $tds.eq(4).attr('value'),
total = $tds.eq(5).text();
alert('Row ' + (i + 1) + ':\nProduct: ' + product
+ '\nPrice: ' + price
+ '\nQuantity: ' + quantity
+ '\nTotal: ' + total);
});
});
</script>
Here
'#chhk' is checkout button id
'#tbl' is my table id
I am getting blank value of quantity by this script as it is input field
Any help would be appreciated..
Try replace this:
quantity = $tds.eq(4).attr('value');
with:
quantity = $tds.eq(4).val();
As .attr('value') gives the value at the start, while .val() gives current property.
More info:
jQuery .val() vs .attr("value")
replace this:
quantity = $tds.eq(4).attr('value'),
with
quantity = $tds.eq(4).find("input").val(),
well I tried to do it separately and am getting expected result.
$('#chhk').on('click',function(e) {
e.preventDefault();
alert('click');
var table = $("#tbl tbody");
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
product = $tds.eq(2).text(),
price = $tds.eq(3).text(),
total = $tds.eq(5).text();
var qty = $(this).find('td input:first').val();
alert('Row ' + (i + 1) + ':\nProduct: ' + product
+ '\nPrice: ' + price
+ '\nTotal: ' + total
+'\n Qua:' + qty);
});
});
Have dealed quantity separately.

Jquery autocomplete text field with data attribute in dynamically added rows

The following jQuery works fine to add rows, and populate the select list from a php/mysql file. The issue I am having is that the price field is being auto-populated and changed on select change on each new row that is added... but if you go back and try to change one of the rows that has already been added, it does not work. For instance, if you add 4 blank rows and then try to go back and select products, it will only populate the price on the last row. Or if you add each row and select the products before you add a new row, then go back and attempt to change the product, the price previously selected will remain the same. Any ideas?
EDIT 1 Added html
EDIT 2 Changed jQuery change(function() to on()... still works exactly the same. The autocomplete only works on the last row added.
var count = 0;
$(document).ready(function(){
$('p#add_field').click(function(){
count += 1;
$('#addingContainer').append('<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" ><option value=""></option>');
$.getJSON('includes/productrow.php', function(data){
var select = $('#product_' + count + '');
$.each(data, function(key, val) {
$('<option/>').attr('value', val.product_id)
.attr('data-price', val.price)
.html(val.product)
.appendTo(select);
});
$('#addingContainer').append('</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" ><br>');
});
$('#addingContainer').on('change', 'select[id="product_' + count + '"]', function(){
$('#price_' + count +'').val($('select[id="product_' + count + '"] option:selected').data('price'));
});});});
HTML:
<div id="addingContainer" class="pure-control-group">
<p id="add_field"><span>Add Products</span></p>
</div>
edit Actually, I think the reason it isn't working is because of where you declared count. Something like this would work:
$(document).ready(function(){
$('p#add_field').click(function(){
var count = $('#addingContainer').data("count") || 0;
count += 1;
$('#addingContainer').data("count", count).append('<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" ><option value=""></option>');
$.getJSON('includes/productrow.php', function(data){
var select = $('#product_' + count + '');
$.each(data, function(key, val) {
$('<option/>').attr('value', val.product_id)
.attr('data-price', val.price)
.html(val.product)
.appendTo(select);
});
$('#addingContainer').append('</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" ><br>');
});
$('#addingContainer').on('change', 'select[id="product_' + count + '"]', function(){
$('#price_' + count +'').val($('select[id="product_' + count + '"] option:selected').data('price'));
});});});
Note I removed your initial declaration of count outside of the document.ready and the function closure; that allowed you to keep track of it (I handled that by setting it on a data attribute, there are other and better ways) but that was why your on('change' method was always using the highest count.
By declaring count inside the function, it is specific to that closure -- and so it won't increase for all of the functions you declared each time a new click event is fired.
Give this a try. I added a class "pselect" to the select box which makes it easier to work with. Then I modified the change function.
var count = 0;
$(document).ready(function(){
$('p#add_field').click(function(){
count += 1;
$('#addingContainer').append('<label>Product or Service</label><select id="product_' + count + '" name="products[]'+ '" class="pselect"><option value=""></option>');
$.getJSON('includes/productrow.php', function(data){
var select = $('#product_' + count + '');
$.each(data, function(key, val) {
$('<option/>').attr('value', val.product_id)
.attr('data-price', val.price)
.html(val.product)
.appendTo(select);
});
$('#addingContainer').append('</select> <label>Price</label><input type="text" id="price_' + count + '" name="prices[]' + '" class="price" ><br>');
});
$('#addingContainer').on("change",".pselect",function(){
$(this).next(".price").val($("option:selected", this).attr('data-price'));
});
});});

How to post the dynamically created text box values to next page in php?

I am a newbee in php,jquery and ajax. I have a code in jquery to add and remove the textboxes dynamically on button click. I want to post the values of dynamically created textbox values to next page and display those values in next page. Any help is much appreciated.Thanks in advance.
I have pasted the code below..
You can also check the link http://jsfiddle.net/NSePb/1/
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if(counter>7){
alert("Only 7 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Product #'+ counter + ' : </label>' +
'<input type="text" size="22" name="product' + counter +
'" id="product' + counter + '" value=""> \n\
<label>Quantity #'+ counter + ' : </label>' +
'<input type="text" size="1" name="qty' + counter +
'" id="qty' + counter + '" value=""> \n\
<label>Rate #'+ counter + ' : </label>' +
'<input type="text" size="2" name="rates' + counter +
'" id="rates' + counter + '" value="" > \n\
<label>Total #'+ counter + ' : </label>' +
'<input type="text" size="3" name="total' + counter +
'" id="total' + counter + '" value="" > ');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==0){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
When you are creating the text boxes dynamically, i assume your text box names to be dynamic which i can't see here. So, store the dynamic field names in an array as
$request = array(#field names#) // comma separated
$requestJson = json_encode($request);
Pass
$requestJson as an hidden field in the form and submit the form.
In the next page i.e. in the action page receive the hidden field and decode it
$requestArr = json_decode($_REQUEST['requestFields']);
Loop the array and receive the values as
for($i=0; $i < count($requestArr); $i++)
{
$value = $requestArr[$i]; // get the field name
$content = $_REQUEST[$value]; // get the input value
$fetchedResult = array($content); // Store the text field value
}
Now your $fetchedResult will have the values to your future usage.
UPDATED - AS PER THE LATEST QUESTION ON COMMENT
var queryArr = [];
newTextBoxDiv.appendTo("#TextBoxesGroup"); // after this line add
queryArr.push(product' + counter + '); // alert OR print in console to check the array values as and when the button is clicked.
$("#TextBoxDiv" + counter).remove(); //after this add
var removeItem = product' + counter + ' // #removed id#;
y = jQuery.grep(queryArr, function(value) {
return value != removeItem;
});
$('<input>').attr({
type: 'hidden',
id: 'foo',
name: 'bar',
value : queryArr
}).appendTo('form');
You need use the $_POST superglobal, and use the id of the HTML element.
Consider this:
<form action="foobar.php" method="post">
<input type="text" id="an_element" name="an_element" />
</form>
If you wanted to display this using PHP, you would go to the page where the action attribute is pointing (in our case, foobar.php), and use the $_POST superglobal.
So the PHP code would look like this:
<?php
echo $_POST['an_element'];
?>
So, using your rates textbox as an example, you might want to do this:
<?php
echo $_POST['rates'];
?>
Please note that if you set the action attribute to get, you will need to use $_GET instead of $_POST.
Also, just taking a look at your code, you are missing the form element in your HTML. Instead of using $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);, you might want to use this:
$(document.createElement('form'))
.attr({
id: 'TextBoxDiv' + counter,
action: 'foobar.php',
method: 'post'
});

Categories