Here is my code:
$.ajax({
type: "POST",
url: "localhost/api.php",
data: {id:user_id},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
if (obj.msg == "1")
{
$.each(obj.userList, function(i,value) {
var jArray = <?php echo json_encode($groupData ); ?>;
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + '>' + jArray[i].Group_Name + '</option>');
}
var html ="<tr>"+
"<td>"+value['id']+"</td>"+
"<td>"+value['groupID']+"</td>"+
"<td><select name='Group[]''>"+list+ "</select></td>";
$('table#List tbody').append(html);
});
}
},
alert('Error');
});
I'm dynamically constructing the html based on the ajax response.
In the code snippet >
var jArray = <?php echo json_encode($groupData ); ?>;
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + '>' + jArray[i].Group_Name + '</option>');
}
$groupData is a PHP array. So I'm converting it into a Javascript array and using this jArray to generate the "option" and push the resulting list array. I'm appending this list array into the html and this much is working perfectly. Now there are 6 groups and one of them is already set for a particular user in the database. So currently none of the "option" has selected attribute. I'm having trouble in comparing jArray[i].Group_Id with value['groupID']. What I want to achieve is I want to compare jArray[i].Group_Id with value['groupID'] and if they are equal then set a selected attribute to that particular . How do I write an if statement for the comparison inside the "option" ?
Here's some example code showing this working:
const jArray = [{Group_Id: 1, Group_Name: 'One'}, {Group_Id: 2, Group_Name: 'Two'}];
const userList = [{id: 'user1', groupID: 2}, {id: 'user2', groupID: 2}, {id: 'user3', groupID: 1}];
$.each(userList, function(x,value) {
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + (jArray[i].Group_Id == value.groupID ? ' selected ' : '') + '>' + jArray[i].Group_Name + '</option>');
}
var html ="<tr>"+
"<td>"+value.id+"</td>"+
"<td>"+value.groupID+"</td>"+
"<td><select name='Group[]''>"+list+ "</select></td>";
$('table#List tbody').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="List">
<tbody></tbody>
</table>
The important piece missing from your code being:
(jArray[i].Group_Id == value.groupID ? ' selected ' : '')
Related
I'm picking up a JSON object using a promise:
var x = get();
x.done(function(data) {
for(var i in data) {
}
});
which is returning this data when i do console.log(data);
[{…}]
0:
customer: "9028"
data:
active: "1"
customer: "9028"
description: ""
id: "13717"
inherited: "0"
name: "Out of Hours"
priority: "1"
shared: "0"
sound: ""
__proto__: Object
voip_seq: "4"
__proto__: Object
length: 1
__proto__: Array(0)
so that is working fine, but within my for loop, I want to add 2 items to data
I tried adding this into my .done
var obj = { name: "Light" };
data.push(obj);
But that didn't add to data
My for loop looks like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
If you want to add two more items to your select, you simply need to push new objects into your data array before your loop starts. The objects must contain the structure and properties ("name" and "id" within a "data" sub-property) matching the JSON coming from the Promise, so that your loop code can process them.
In the simplest case, it could be as straightforward as
x.done(function(data) {
data.push({ "data": { "name": "light", "id": 1234 } });
data.push({ "data": { "name": "dark", "id": 5678 } });
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if (data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
});
Demo: https://jsfiddle.net/a286b7fw/1/
In this case I think data is not an array so it hasn't .push() method. You can add property to object like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
// here it will add obj to data
var obj = {name: "Light"};
data = {
...data,
obj
}
}
I have a javascript file here.What it does is,when a user selects seats accordings to his preference in a theater layout,the selected seats are stored in an array named "seat".This code works fine until function where the selected seats are shown in a window alert.But from there onwards,the code doesn't seem to do anything.
After the above window alert, I've tried to serialize the above array and send it to the "confirm.php" file.But it does not show anything when echoed the seats.
Here is the js code.
<script type="text/javascript">
$(function () {
var settings = {
rows: 6,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 80,
seatHeight: 80,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
var jArray = <?= json_encode($seats) ?>;
init(jArray);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved!');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShowNew').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
});
$('#btnsubmit').click(function () {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
var seatar = JSON.stringify(seat);
$.ajax({
method: "POST",
url: "confirm.php",
data: {data: seatar}
});
});
});
});
</script>
Can somebody help me figure it out what's wrong in here?
Please Add content type as json.
$.ajax({
method: "POST",
url: "confirm.php",
contentType: "application/json"
data: {data: seatar}
});
For testing you can print file_get_contents('php://input') as this works regardless of content type.
Not sure how to even title this question but i tried my best to condense it.
I have a key / value array that i need to loop through and print out as options to a select field. My issue is that i need to match an ID with a value in the array and give that option a selected attribute.
** Cannot use ES6 syntax **
My array:
groups =
[
{ name:"eng1",
value: "12"
},
{ name: "eng2",
value: "247"
},
{ name: "eng23",
value: "112"
},
];
My loop:
var targetGroupId = 247;
for (i = 0; i < groups.length; i++) {
if (groups[i].Value = targetGroupId) {
html += "<option value'" + groups[i].Value + "' selected='selected'>" + groups[i].Name + "</option>";
} else {
html += "<option value='" + groups[i].Value + "'>" + groups[i].Name + "</option>";
}
}
I need to print out all three items in the array as options. However the item matching targetGroupId needs to have the selected attribute.
Any guidance is much appreciated!
You have three issues
Comparing values with = rather than === .
You're using capitalized keys.
Comparing string with numbers.
var groups = [{name: "eng1",value: "12"},{name: "eng2",value: "247"},{name: "eng23",value: "112"},],
html = '',
targetGroupId = 247;
for (var i = 0; i < groups.length; i++) {
if (/*Convert to number ->*/+groups[i].value === targetGroupId) {
html += "<option value'" + groups[i].value + "' selected='selected'>" + groups[i].name + "</option>";
} else {
html += "<option value='" + groups[i].value + "'>" + groups[i].name + "</option>";
}
}
console.log(html);
You have the following issues with your code:
You are using Value property instead of value. Replace Value with value everywhere in your code.
Second, you need to correct this statement
if (groups[i].Value = targetGroupId) {
to this:
if (groups[i].value == targetGroupId) {
I've used == to auto-coerce the values for the comparison because targetGroupId is a number whereas value in the object is a string.
The keys name is case sensitive.So Value & Name need to be match the case
Also the value is string but the targetGroupId is integer. So need to convert the string to number or vice versa.
Beside groups[i].Value = targetGroupId is not right , you need to do the quality check instead of assigning the value
var groups = [{
name: "eng1",
value: "12"
},
{
name: "eng2",
value: "247"
},
{
name: "eng23",
value: "112"
},
];
var html = '';
var targetGroupId = 247;
for (i = 0; i < groups.length; i++) {
if (+groups[i].value === targetGroupId) {
html += "<option value'" + groups[i].value + "' selected='selected'>" + groups[i].name + "</option>";
} else {
html += "<option value='" + groups[i].value + "'>" + groups[i].name + "</option>";
}
}
document.getElementById('test').innerHTML = html
<select id='test'></select>
$('#save').click(function() {
var loopvalue = "<?php echo $count; ?>"
var datajson = '[';
//alert(loopvalue + "length of array")
for (i = 1; i < loopvalue; i++) {
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
datajson = datajson + "{" + "maincode :" + $('#company').val() + ",acode : " + $(fetchid_code).text() +
" , Amount :" + $(fetchid).val() + ", periodfrom :" + $('#dFrom').val() +
", periodto : " + $('#dTo').val() + ", danounc : " + $('#dano').val() +
", period : " + $('#period').val() + ", fyear : " + $('#fyear').val() +
", frequency : " + $('#freq').val() + ", stype : " + $('#stype').val() +
", sseq : " + $('#sseq').val() + " }, "
}
datajson = datajson + ']'
//console.log(datajson);
$.ajax({
type: 'POST',
url: 'jsondecode.php',
data: {
datajson: JSON.stringify(datajson)
},
//data:postArray,
dataType: "json",
success: function(data) {
console.log("success:", data);
},
failure: function(errMsg) {
console.error("error:", errMsg);
}
});
});
first i remove last comma in json object and second when i am calling ajax page but it is displaying NULL value in jsonencode.php page how can I solve this problem any can suggest me this is my server site script now
<?php
header('Content-Type: application/json');
$data = json_decode($_POST["datajson"]);
// will echo the JSON.stringified - string:
echo $_POST["datajson"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach ($data as $Object) {
echo "maincode: " . $Object->maincode . ", Acode: " . $Object->acode . "<br/>";
}
?>
Or maybe you should use actual object instead of string-concatenation
Try this
var datajson = [];
for (i = 1; i < loopvalue ; i++)
{
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
var obj = {
maincode : $('#company').val(),
acode : $(fetchid_code).text(),
Amount : $(fetchid).val(),
periodfrom : $('#dFrom').val(),
periodto : $('#dTo').val(),
danounc : $('#dano').val(),
period : $('#period').val(),
fyear : $('#fyear').val(),
frequency : $('#freq').val(),
stype : $('#stype').val(),
sseq : $('#sseq').val()
}
datajson.push( obj );
}
datajson = JSON.stringify( datajson ); //converting to string here
Before you append ] to datajson, substring that value to remove last ,. That is.
datajson = datajson.toString().subString(0, datajson.toString().length - 1);
Then Append ]
It is not needed to use JSON.stringify(datajson) in data attribute of $.ajax because you are sending the json string. not json object.
Hope this helps
Write the single elements of your look into an array and then join the elements.
See here: javascript join
But of course building JSON yourself is not necessary. Use JSON.stringify for that.
Am looking to .get an array of MongoDB docs, build var from the array using object.foo, and then reBuild an array of the all the foobar, once ranked..
Have another function that handles some variable calculations for ranking.
Am trying to reBuild the JSON array, using a for loop to iterate over the elements, but:
..the array starts with a comma for some odd reason
..looping over the newly built array seems to loop over the characters instead of the values
The console logs this: [01:10:40.833] ", {title: "Title1", quantity: "2", _id: "530c12c66e6b0de318000001"}, {title: "Title2", quantity: "4", _id: "530c12cc6e6b0de318000002"}, {title: "Title3", quantity: "8", _id: "530c12d16e6b0de318000003"}"
Then the console logs this: [01:10:40.833] undefined 213
MongoDB via .get:
function getAll(res) {
db.collection('demo').find().sort( { value: 1 } ).toArray(function (err, docs) {
console.log("Got the Docs: " + utils.inspect(docs));
// each doc looks like: { _id: ObjectID, title: 'string', quantity: int}
res.json({docs: docs});
});
}
Docs looks like this in the console:
[ { _id: 530c12c66e6b0de318000001,
title: 'Sample1',
quantity: 2 },
{ action: 'Sample2',
quantity: 4,
_id: 530c12cc6e6b0de318000002 },
{ _id: 530c12d16e6b0de318000003,
action: 'Sample3',
quantity: 8 } ]
Javascript Function to ReBuild the Array:
function reBuild(returnValue)
{
console.log(returnValue);
var docs = returnValue;
var returnedValue = [];
var doc;
for (var i=0, length=docs.length; i < length; i++){
doc = docs[i];
if (returnedValue == [])
{
returnedValue = returnedValue + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
}
else
{
returnedValue = returnedValue + ", " + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
}
}
console.log(returnedValue);
var newDocs = returnedValue;
var newDoc;
for (var i=0, length=newDocs.length; i < length; i++){
newDoc = newDocs[i];
console.log(newDoc.title);
}
}
See you can't simply assign String value to a array type variable. JavaScript allows you do so because it is a loosely typed(or dynamically typed). But it you case it is the cause for your problem.
In your code:
function reBuild(returnValue)
{
console.log(returnValue);
var docs = returnValue;
//==> Initializes to a array type i.e. equivalent to var returnedValue = new Array();
var returnedValue = [];
var doc;
for (var i=0, length=docs.length; i < length; i++){
doc = docs[i];
//==>Its better to use === if you want equality without type coersion. i.e. the values must be equal in type as well.
if (returnedValue == []){
//==>Here you are changing the type of `returnedValue` variable from array to String
//So this condition start failing from next loop onwards.
returnedValue = returnedValue + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
}
else{
returnedValue = returnedValue + ", " + '{' + 'title: "' + doc.title + '", quantity: "' + doc.quantity + '", _id: "' + doc._id + '"}';
}
}
console.log(returnedValue);
var newDocs = returnedValue;
var newDoc;
for (var i=0, length=newDocs.length; i < length; i++){
newDoc = newDocs[i];
console.log(newDoc.title);
}
}
You are changing the type of your variable returnedValue in a loop and also you are checking condition if (returnedValue == []). It automatically becomes false since it changes in first iteration from any array to String type. So the way you can look into is something array function such as arrayObject.push('YourValue')
Try the following code:
for (var i=0; i < docs.length; i++){
//This builds JSON object out of your string and pushes into your array `returnedValue`
returnedValue.push(JSON.prarse('{' + 'title: "' + docs[i].title + '", quantity: "' + docs[i].quantity + '", _id: "' + docs[i]._id + '"}'));
}
And the correct operator to typed check is to use ===. So basically the answer to your question is too broad But I did a attempt to point few of the points which takes you near to solution for your problem.
Happy coding :)