I am practicing a shopping cart list but I cannot populate the select I have tried several times but without success. Any guidance would be appreciated.
PHP:
$get_cart = mysqli_query($link,"SELECT cpro_id,cpro_name,cpro_price,cpro_qty FROM cart WHERE owner='$client'");
$rows = array();
while($r = mysqli_fetch_assoc($get_cart)) {
$rows[] = $r;
}
echo json_encode(array("status"=>"OK","data"=>$rows));
return true;
server response:
{"status":"OK","data":[
{"cpro_id":"9","cpro_name":"Product1","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"10","cpro_name":"Product2","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"11","cpro_name":"Product3","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"12","cpro_name":"Product4","cpro_price":"10.00","cpro_qty":"1"},
{"cpro_id":"13","cpro_name":"Product5","cpro_price":"10.00","cpro_qty":"1"}
]}
JS/HTML:
<select name="info" size="1" id="info" style="display:block;width: 100%;">
<option selected value="cpro_id">cpro_name</option>
</select>
<script>
$(document).ready(function() {
$.ajax({
method: "POST",
dataType: "JSON",
data: {
action: 'getcart'
},
url: "api.php"
})
.done(function(cart) {
//fill list
});
});
</script>
You can easily populate your json data with $.each like below example:
let obj = {
"status": "OK",
"data": [{
"cpro_id": "9",
"cpro_name": "Product1",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "10",
"cpro_name": "Product2",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "11",
"cpro_name": "Product3",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "12",
"cpro_name": "Product4",
"cpro_price": "10.00",
"cpro_qty": "1"
},
{
"cpro_id": "13",
"cpro_name": "Product5",
"cpro_price": "10.00",
"cpro_qty": "1"
}
]
};
$.each(obj.data, function(i, v) {
$('#info').append('<option value="' + v.cpro_id + '">' + v.cpro_name + '</option>')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="info" size="1" id="info" style="display:block;width: 100%;">
<option selected value="cpro_id">cpro_name</option>
</select>
In your code:
$.ajax({
method: "POST",
dataType: "JSON",
data: {
action: 'getcart'
},
url: "api.php"
})
.done(function(cart) {
$.each(cart.data, function(i, v) {
$('#info').append('<option value="' + v.cpro_id + '">' + v.cpro_name + '</option>')
});
});
Related
I have three dropdowns which are depend on each other. Based on the selection of Dropdown A will have a list of results in Dropdown B, and based on the selection of Dropdown B will have a list of results in Dropdown C.
I can populate the first two dropdowns without a problem. However the last dropdown does shows me incorrect options.
$(function() {
var platforms;
var tasktypes;
var compos;
var jsonData;
$('#addnew').click(function(){
$('#dataset').clone().appendTo($('#newfield'));
});
$.getJSON('tasks.json', function(result) {
jsonData = result;
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
$("#platform").change(function (){
var idx = $("#platform").prop('selectedIndex');
var platforms = jsonData[idx].task;
tasktypes = "";
for (i = 0; i < platforms.length; i++) {
tasktypes += "<option value='" +
platforms[i].taskname +
"'>" +
platforms[i].taskname +
"</option>";
};
$('#taskname').html(tasktypes);
});
$("#taskname").change(function (){
var idc = $("#taskname").prop('selectedIndex');
var tasktypes = jsonData[idc].task[0].component;
compos = "";
for (i = 0; i < tasktypes.length; i++) {
compos += "<option value='" +
tasktypes[i].componentname +
"'>" +
tasktypes[i].componentname +
"</option>";
};
$('#components').html(compos);
});
});
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<button id="addnew">Add new</button>
<div id="dataset">
Platform:
<select id="platform">
</select>
Task Type:
<select id="taskname">
</select>
Component:
<select id="components">
</select>
Units:
<input type="number" min="0" />
</div>
<div id="newfield"></div>
<button id="calculate">Calculate</button>
<button id="clear">Clear</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Json
[
{
"name": "Sitecore",
"value": "sitecore",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "A",
"time": "20"
},
{
"componentname": "B",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "C",
"time": "20"
},
{
"componentname": "D",
"time": "10"
}
]
}
]
},
{
"name": "Siab",
"value": "siab",
"task": [
{
"taskname": "promobox",
"component": [
{
"componentname": "E",
"time": "20"
},
{
"componentname": "F",
"time": "10"
}
]
},
{
"taskname": "newswire",
"component": [
{
"componentname": "G",
"time": "20"
},
{
"componentname": "H",
"time": "10"
}
]
},
{
"taskname": "video",
"component": [
{
"componentname": "I",
"time": "20"
},
{
"componentname": "J",
"time": "10"
}
]
}
]
}
]
First two dropdowns works fine. Once I select a platform from the first dropdown, second dropdown populates with the relevant tasknames. But once I select a taskname from the second dropdown, third dropdown does show irrelevant data. I can't figure out what's wrong I'm doing here.
I believe the major problem you have is jsonData = result during the ajax request. All ajax requests are asynchronous by default, hence, every data produced from it is mostly non-existent after the request completion. So your best bet will be to pass result to the HTML DOM object during the request.
$.getJSON('tasks.json', function(result) {
$('#platform').data('jsonData',result);//Assign Json data to data object of platform id
$.each(result, function(i, platform) {
platforms += "<option value='" +
platform.name +
"'>" +
platform.name +
"</option>";
});
$('#platform').html(platforms);
});
I'm trying to fill a dropdown list dynamically but it doesn't work. here is the code:
<form id="email-compose" class="form-email-compose" method="get" action="">
<div class="form-group">
<select id="input-to" class="input-transparent form-control">
</select>
</div>
<div class="form-group">
<input type="text" id="input-subject" placeholder="Subject" class="input-transparent form-control"
value="<%= subject %>">
</div>
<div class="form-group">
<textarea rows="10" class="form-control" id="wysiwyg" placeholder="Message"><%- body %></textarea>
</div>
<div class="clearfix">
<div class="btn-toolbar pull-xs-right">
<button type="reset" id="compose-discard-button" class="btn btn-gray">Annuler</button>
<button type="submit" id="compose-send-button" onClick="sendMail()" class="btn btn-danger"> Envoyer </button>
</div>
</div>
</form>
and the corresponding JS:
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function () {
var listItems = '<option selected="selected" value="0">- Select -</option>';
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
console.log(listItems);
$("#input-to").html(listItems);
});
If I insert manually the option tags, I can see them correctly in the select but not dynamically...
I also tried with .append method but still having an empty drop down list.
Any idea ?
EDIT 1:
I also tried to use .append like this:
$(document).ready(function () {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0,opt; opt= jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
but same thing, my dropdown remains empty...
No problem of syntax as if I add manually the options I can see the options available.
one additional thing, my form is surrounded by a script:
<script type="text/template" id="compose-view-template">
....<form>
</script>
with the following js
var ComposeView = Backbone.View.extend({
template: _.template($('#compose-view-template').html()),
attributes: {
id: 'compose-view',
class: 'compose-view'
},
events: {
"click #compose-save-button, #compose-send-button, #compose-discard-button": 'backToFolders'
},
render: function() {
$('#widget-email-header').html(
'<h5>Nouvel <span class="fw-semi-bold">Email</span></h5>'
);
$('#folder-stats').addClass('hide');
$('#back-btn').removeClass('hide');
this.$el.html(this.template(this.model.toJSON()));
this._initViewComponents();
return this;
},
backToFolders: function(){
App.showEmailsView();
},
_initViewComponents: function(){
this.$("textarea").wysihtml5({
html: true,
customTemplates: bs3Wysihtml5Templates,
stylesheets: []
});
}
});
may be the js function is called when the form is not completely created ? hence, there is no action (and no error) because the form is not completely created ?
Your making a small mistake in your code
See the commeted out code below:
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function () {
//
// Since your are adding the html to the element
// You dont need to recreate it!
//
// var listItems = '<option selected="selected" value="0">- Select -
// </option>';
var listItems="";
for (var i = 0; i < jsonData.Table.length; i++) {
listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
}
console.log(listItems);
$("#input-to").html(listItems);
});
Here is a fiddle of a working version
https://jsfiddle.net/40zz77ex/
Use .append instead of building HTML string. Something like this.
$(document).ready(function () {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0,opt; opt= jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
See working example
var jsonData = {
"Table": [{
"stateid": "2",
"statename": "Texas"
}, {
"stateid": "3",
"statename": "Louisiana"
}, {
"stateid": "4",
"statename": "California"
}, {
"stateid": "5",
"statename": "Nevada"
}, {
"stateid": "6",
"statename": "Massachusetts"
}]
};
$(document).ready(function() {
$('#input-to').append('<option selected="selected" value="0">- Select -</option>');
for (var i = 0, opt; opt = jsonData.Table[i]; ++i) {
$('#input-to').append('<option value="' + opt.stateid + '">' + opt.statename + '</option>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="input-to"></select>
But i get respnce in json, i.e alert(html)
<script>
function addcartAction(id){
var dataString='id='+id;
$.ajax({
type: "POST",
url:"<?php echo Yii::app()->request->baseUrl; ?>/testurl",
data: dataString,
success: function(html)
{
alert(html);
$("#cart-item").html(html);
}
});
}
</script>
{
"1": {
"ItemName": "Product1",
"id": "1",
"item_Image": "http://testurl.com/gallerythumb/test.JPG",
"price": "4.99",
"quantity": 1
},
"2": {
"ItemName": "Product2",
"id": "2",
"item_Image": "http://testurl.com/gallerythumb/test1.jpg",
"price": "7.99",
"quantity": 12
}
}
I have tried alot of different syntax but can't seem to figure this out.
Can any one point me in the right direction?, so can i solve this one.
Once you have your json string, use the parseJSON() function, which returns an object. Then you can access it's properties as shown in the docs.
Also you might refer to:
Converting JSON Object into Javascript array
Convert JSON string to Javascript array
You can use $.each to iterate JavaScript object
var data = {
"1": {
"ItemName": "Product1",
"id": "1",
"item_Image": "http://testurl.com/gallerythumb/test.JPG",
"price": "4.99",
"quantity": 1
},
"2": {
"ItemName": "Product2",
"id": "2",
"item_Image": "http://testurl.com/gallerythumb/test1.jpg",
"price": "7.99",
"quantity": 12
}
};
$.each(data,function(i, v) {
console.log(i);
$.each(v,function( ind , val) {
console.log( ind , val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You need to look at loading JSON data using an HTTP GET request (you can also use POST).
JSON jQuery Syntax:
jQuery.getJSON( url, [ data ], [ success(data, textStatus, jqXHR) ] );
url – A string containing the URL to which the request is sent.
data – A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR) – A callback function that is executed if the request succeeds.
Download Example
Code reference here.
Something like this!
var data={
"1": {
"ItemName": "Product1",
"id": "1",
"item_Image": "http://testurl.com/gallerythumb/test.JPG",
"price": "4.99",
"quantity": 1
},
"2": {
"ItemName": "Product2",
"id": "2",
"item_Image": "http://testurl.com/gallerythumb/test1.jpg",
"price": "7.99",
"quantity": 12
}
};
$.each(data,function(key,value){
var element='<div class="elem">Item No : '+key+
' <span>Item Name : '+value.ItemName+'</span> '+
' <span>Id : '+value.id+'</span> '+
' <img src="'+value.item_Image+'"/> '+
' <span>Price: '+value.price+'</span> '+
' <span>Quantity : '+value.quantity+'</span></div> ';
$('body').append(element);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Update
Say you have following ajax
$.ajax({
url:'someurl',
type:'POST',
dataType:'json',
success: function(data)
{
$.each(data,function(key,value){
var element='<div class="elem">Item No : '+key+
' <span>Item Name : '+value.ItemName+'</span> '+
' <span>Id : '+value.id+'</span> '+
' <img src="'+value.item_Image+'"/> '+
' <span>Price: '+value.price+'</span> '+
' <span>Quantity : '+value.quantity+'</span></div> ';
$('body').append(element); //append it to anywhere in DOM using selector
});
},
error:function(jqXHR,responseData,status){
//do something
}
});
Number of autocomplete search box is dynamic based an #AddButton. Autocomplete is working, but when I select the values, it doesnt rendered it properly. Please tell me where Am I missing.
Fiddle setup is at http://jsfiddle.net/jakenrush/kELm3/1/
Jquery code below
$(function() {
var projects = [
{
"label": "ajax",
"value": "1003",
"desc": "foriegn"
},
{
"label": "jquery",
"value": "1000",
"desc": "dd"
},
{
"label": "wordpress theme",
"value": "1000",
"desc": "h"
},
{
"label": "xml",
"value": "1000",
"desc": "j"
}];
$("#addButton");
var counter = 13;
$("#addButton").click(function() {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var roleInput = $('<input/>', {
type: 'text',
placeholder: 'Role',
name: 'Role' + counter,
id: 'project-description' + counter
});
var searchInput = $('<input/>', {
type: 'text',
placeholder: 'search',
name: 'search' + counter,
id: 'project' + counter
});
var hidd = $('<input/>', {
type: 'hidden',
name: 'searchhid' + counter,
id: 'project-id' + counter
});
newTextBoxDiv.append(roleInput).append(searchInput).append(hidd);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$("#project" + counter).autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project" + counter).val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project" + counter).val(ui.item.label);
$("#project-id" + counter).val(ui.item.value);
$("#project-description" + counter).val(ui.item.value);
$("#project-icon" + counter).attr("src", "images/" + ui.item.icon);
return false;
}
})
counter++;
});
});
html code :
<div id="project-label"></div>
<input type="hidden" id="project-id" />
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1" class="form-inline control-group">
</div>
</div>
<input type='button' value='Add' id='addButton' />
i have update your fiddle and it is working, the problem is with your counter variable which never been incremented, because you have place at end of script, but you have return statement above it.
your fiddle here http://jsfiddle.net/kELm3/6/
var counter = 0;
$("#addButton").click(function() {
counter++;
I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);