I have an array in php which i am getting in Javascript.
Here is my php code
$query = "SELECT SeatNum FROM `$busNum` WHERE AB = 1";
$runQuery = mysqli_query($con, $query);
$i = 0;
foreach($runQuery as $row)
{
$availableSeats[$i++] = $row['SeatNum'];
}
And here i am getting this string in javascript
var getBookedSeats = <?php echo json_encode($availableSeats); ?>;
var bookedSeats =[];
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = getBookedSeats[i];
}
The array also saved in bookedSeats successfully. Now the problem is that when i used that array as a parameter to call function. Nothing goes in the parameter. Even there is no problem of scope. This is my function looks like:
var init = function (reservedSeat) {
//code
}
init(bookedSeats);
Implementation of init function is :
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], 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;
}
str.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(str.join(''));
};
Seems the problem is that you are trying to compare the array values as numbers and you currently have them as strings. To convert them to numbers, you can simply use:
bookedSeats = bookedSeats.map(Number) // iterate over each bookedSeats element and return its numeric value
Which is the same as:
bookedSeats = bookedSeats.map(function(value){
return Number(value);
})
From the comments it looks like your variable bookedSeats is being assigned with values. However, if your init() function is expecting integers, you'll want to build the bookedSeats array with integers like so:
for(var i =0 ; i <getBookedSeats.length ; i++){
bookedSeats[i] = parseInt( getBookedSeats[i], 10 );
}
I do not use php but I belive php's json_encode returns a JSON formatted string. Which results in your JavaScript code storing individual characters from the string into the bookSeats variable.
You need to parse the string returned from php. For example...
var getBookedSeats = JSON.parse(<?php echo json_encode($availableSeats); ?>);
Related
I have this javascript function here, the routeno variable will pass a Chinese value
routeno: 粤ZX123港
function getRouteLegNoList()
{
var data = "host="+lphost
+ "&user="+user
+ "&gateway="+gateway
+ "&routedate="+routedate.value
+ "&routeno="+routeno.value
+ "&action=GETROUTELEGNOLIST";
alert(lphost+'|'+user+'|'+gateway+'|'+routedate.value+'|'+routeno.value);
callAjax("../restartAndMoveDeclaration.cgi?"+data, "GET", "",
function(text) {
alert(text);
var html = "<select id=routelegno>";
var count = 0;
var lines = text.split("\n");
for(var i = 0; i < lines.length; i ++)
{
var line = lines[i];
var c;
if(line.indexOf("Data|") == 0) {
count += 1;
c = line.split("|");
html += "<option value=\"" + c[1]
+ "\"";
if(c[1]==origRouteLegNo) {
html += " selected ";
}
html += ">" + c[1] + "</option>";
}
}
html += "</select>";
dvroutelegno.innerHTML = html;
if(count==0){
alert('No Route Legs were found for [' +
gateway + '] [' +
routedate.value + '] [' +
routeno.value + ']');
} else {
if(count==1) {
trroutelegno.style.visibility = 'hidden';
} else {
// More than one, display the select box
trroutelegno.style.visibility = 'visible';
}
}
}
);
}
but when shell script captured the variable it does not read the Chinese character and replaced it as question mark
routeno: ?ZX123?
I've already tried to set different NLS_LANG but encountered the same output
NLS_LANG=AMERICAN_AMERICA.ZHS16GBK
NLS_LANG=AMERICAN_AMERICA.AL32UTF8
In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data
In the following:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
} // processResponse
if (weighInData[obj].user === selUser) { ... returns the following (using example Ron):
Object { user="Ron", date="2014-08-01", weight="192"}
Object { user="Ron", date="2014-08-02", weight="195"}
Object { user="Ron", date="2014-08-03", weight="198"} ... etc.
... so my problem presently is where this belongs:
var peakWeight = Math.max.apply(Math, weights);
console.log("peakWeight: " + peakWeight);
Since I'm only after the weight values for the matching user, I assumed it would have to run within the 'if (weighInData[obj].user === selUser) { ... ', but this (and numerous other attempts in and out of the loop, including a for loop within the selUser) fail to achieve the desired results. In fact, even when the math function wasn't running on each value in 'weights', (i.e., outside the loop) and only ran outside the loop, the result was an incorrect value.
Any insight is greatly appreciated,
svs
Here's a very simple example you can probably adjust to fit your purpose:
// create this array outside of for loop so it already exists
var arr = [];
// test data
var a = { user:"Ron", date:"2014-08-01", weight:"192"};
var b = { user:"Ron", date:"2014-08-02", weight:"195"};
var c = { user:"Ron", date:"2014-08-03", weight:"198"};
// within for loop, you should only need to push once (per loop)
arr.push( a.weight );
arr.push( b.weight );
arr.push( c.weight );
// after the loop ends, display loop, get max and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
http://jsfiddle.net/biz79/sb7zayze/
If i were to edit your code, something like this might work:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
// ADDED: create array
var arr = [];
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
// ADDED: add to array
arr.push(weights);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
// ADDED: after the loop ends, display loop, get max/min and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
} // processResponse
Basically, I'm using JavaScript to dynamically generate a form that allows from multiple entries within a single submission. Here's the code I'm using for that:
function addEvent()
{
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var divIdName = 'my' + num + 'Div';
var newdiv = document.createElement('div');
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<table id="style" style="background-color: #ffffff;"><tr><td colspan="2">Entry ' + num + '<hr \/><\/td><\/tr><tr><td><label>Item 1: <\/td><td><input name="item1_' + num + '" value="" type="text" id="item1" \/><\/label><\/td><\/tr><tr><td><label>Item 2: <\/td><td><input name="item2_' + num + '" type="text" id="item2" \/><\/label><\/td><\/tr><tr><td><label>Item 3: <\/td><td><input type="text" name="item3_' + num + '" id="item3" \/><\/label><\/td><\/tr><tr><td><label>Item 4: <\/td><td><select name="item4_' + num + '" id="item4"><option value="---">---<\/option><option value="opt_1">1<\/option><option value="opt_2">2<\/option><option value="opt_3">3<\/option><option value="opt_4">4<\/option><\/select><\/label><\/td><\/tr><\/table>';
ni.appendChild(newdiv);
}
This works just fine, generating the entries fields I need. Using console in-browser, I've even verified all the names are correct. The issue is that I need to then take the selections and generate output. I've tried several methods, but everything resulted in null values.
function generateVideo()
{
var entries = document.getElementById('theValue').value;
var item1 = {};
var item2 = {};
var item3 = {};
var item4 = {};
for(i = 1; i <= entries; i++)
{
item1[i - 1] = document.getElementById('item1_' + i);
item2[i - 1] = document.getElementById('item2_' + i);
item3[i - 1] = document.getElementById('item3_' + i);
item4[i - 1] = document.getElementById('item4_' + i);
}
var code = 'Copy code and paste it into Notepad<br \/>"Save as" filename.html<br \/><textarea name="" cols="45" rows="34">header template\n';
for(i = 0; i < entries; i++)
{
if(i != (entries - 1))
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"],\n';
}
else
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"]\n';
}
}
code = code + 'footer template<\/textarea>';
var result = document.getElementById("result");
result.innerHTML = code;
}
The output is as follows:
Copy code and paste it into Notepad<br />"Save as" CourseName_Unit_Chapter.html<br /><textarea name="" cols="45" rows="34">header template
["null", "null", "null", "null"]
footer template</textarea>
Now, certain fields can be null, that's fine (I'll do form validation after I get it working), but I'm getting null for every field regardless of what is entered.
I, originally, had the .value on the getElementByIds, but that only results in the script not running when the entries variable is greater than 0 (default), which is why I tried removing them.
function generateVideo()
{
var entries = document.getElementById('theValue').value;
var item1 = {};
var item2 = {};
var item3 = {};
var item4 = {};
for(i = 1; i <= entries; i++)
{
item1[i - 1] = document.getElementById('item1_' + i).value;
item2[i - 1] = document.getElementById('item2_' + i).value;
item3[i - 1] = document.getElementById('item3_' + i).value;
item4[i - 1] = document.getElementById('item4_' + i).value;
}
var code = 'Copy code and paste it into Notepad<br \/>"Save as" filename.html<br \/><textarea name="" cols="45" rows="34">header template\n';
for(i = 0; i < entries; i++)
{
if(i != (entries - 1))
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"],\n';
}
else
{
code = code + ' ["' + item1[i] + '", "' + item2[i] + '", "' + item3[i] + '", "' + item4[i] + '"]\n';
}
}
code = code + 'footer template<\/textarea>';
var result = document.getElementById("result");
result.innerHTML = code;
}
I've also tried variations of multidimensional arrays, instead of four arrays, but got the same results.
The output, as indicated by the removal of the .value on the getElementByIds, is good. Basically, there is something wrong with my attempts to populate the arrays using the dynamically generated forms.
I suspect that the issue with the declaration of the element ID, but I'm not sure how else to declare it. This style of scripting is not my norm. ^^'
Anyone have any ideas on how to fix the for loop to generate the array?
replace all occurences of
itemN[i]
with
itemN[i].value
if that doesnt work add
console.log( itemN[i] )
and see what it outputs
I want to assign an sql sting to a variable in Javascript. But I want to loop through an array to build par of the sql statement.
static sql:
var tag = [fun, beach, sun];
var sql = "SELECT * FROM myTable "
+"WHERE id > 5" //...
// loop through tag array and add to the sql
function tagQuery(tag) {
for (var i = 0; i < tag.length; i++) {
var tagQuery = "AND WHERE tags like %'"+tag[i]+"'%";
return tagQuery;
};
}
It is not clear to me how to get each result of the tagQuery function to be added to the sql sting?
EDIT: maybe a more clear way to ask the question is: How can I get each iteration of the tagQuery function to be joined with the sql variable?
var tag = [fun, beach, sun];
var sql = "SELECT * FROM myTable WHERE id > 5";
function tagQuery(tag) {
var str = '';
for (var i = 0; i < tag.length; i++) {
str += " AND tags like '%" + tag[i] + "%' "
}
return str;
}
sql += tagQuery(tag);
Fiddle: http://jsfiddle.net/7P4us/2/
EDIT:
I took out the tagQuery function altogether, after you commented:
sql += tagQuery(tag); ...will only return the last iteration of the tagQuery loop
var tag = ['fun', 'beach', 'sun'];
var sql = "SELECT * FROM myTable WHERE id > 5";
if (tag[0] != null) {
sql += " AND (tags like '%" + tag[0] + "%' ";
}
if (tag[1] != null) {
for (var i = 1; i < tag.length; i++) {
sql += " OR tags like '%" + tag[i] + "%' ";
}
}
if (tag[0] != null) {
sql += ")";
}
But note: the jsFiddle link that Rusty put in a comment, since, shows that the tagQuery function can return all iterations... so seeing only the last iteration was probably in your implementation.