fetch data from a dynamic page/table? - javascript

The dynamic page is created to display the data fetched from the database, the dynamic page also creates a table for the data to be presented in.
I then have a button (btnJoin) which is under every set of results, the button triggers a function that updates the table.
In order to update the table I need to fetch the specific event that the user joins, therefore is it possible to fetch the data from title (response.rows.item(i).Title) of the specific event the button was pressed on?
My SQL query for the update function should look something like:
tx.executeSql("Update soccerevents SET NoPeople = NoPeople +1 WHERE Title = '" + response.rows.item(i).Title + "'", [], successJoin,errorCB);
JavaScript (Dynamic Page/Table):
function fetchEvent() {
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2 * 1024 * 1024);
db.transaction(function(tx) {
var TitleT = document.getElementById("texttitle").value;
tx.executeSql("SELECT * FROM SoccerEvents WHERE Title LIKE '%" + TitleT + "%'", [], successCBValue, errorCB);
});
function successCBValue(tx, response, page_id) {
var formElements = "<table id='resulttable' data-role='table' data-mode='reflow' class='ui-responsive table-stroke table-stripe'><thead><tr><th>Title</th><th>Location</th><th>NoPeople</th><th>Date</th><th>Description</th></tr></thead><tbody>";
for (var i = 0; i < response.rows.length; i++) {
formElements += "<tr><td>"
+ response.rows.item(i).Title + "</td><td>"
+ response.rows.item(i).Location +"</td><td>"
+ response.rows.item(i).NoPeople + "</td><td>"
+ response.rows.item(i).Date +"</td><td>"
+ response.rows.item(i).Description + "<button data-rowtitle='" + response.rows[i].Title + "' data-mini='true' class='btnJoin'>Join</a></td></tr>";
}
formElements+="</tbody></table>";
alert("For better viewing of events, tilt phone landscape.");
$('#page_body').append('<div data-role="page" data-theme="d" id="' + page_id + '"><div data-role="content">' + formElements + 'Return</div></div>');
$.mobile.initializePage();
$.mobile.changePage("#" + page_id);
$(document).on("click", ".btnJoin", function(e){
var title = $(this).data("rowtitle");
alert(title);
});
}
}
function updateEvent() {
var title = document.getElementById("rowtitle");
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2 * 1024 * 1024);
db.transaction(function(tx) {
tx.executeSql("Update soccerevents SET NoPeople = NoPeople +1 WHERE Title = '" + title + "'", [], successJoin,errorCB);
});
function successJoin() {
navigator.notification.alert("You have joined the event!", null, "Information", "ok");
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#page4" );
}
}

You could add the title as a data attribute of the button
for (var i = 0; i < response.rows.length; i++) {
formElements += "<tr><td>" + response.rows[i].Title + "</td><td>" +
response.rows[i].Location +"</td><td>" +
response.rows[i].NoPeople + "</td><td>" +
response.rows[i].Date +"</td><td>" +
response.rows[i].Description +
"<button data-rowtitle='" + response.rows[i].Title + "' class='btnJoin' >Click me</button></td></tr>";
}
Then in the button click handler, retrieve the attribute using the jQuery data() method:
$(document).on("click", ".btnJoin", function(e){
var title = $(this).data("rowtitle");
alert(title);
});
DEMO

Related

Make a list with multiple pages in Jquery

I'm making a page with a list of products (which are loads using ajax) but i want to show only 6 products/page but i don't know how to do it and i don't find any examples that implements what i want. So for example if i have 20 products i want to show 6 in the first page, 6 in the second, .. etc to the last product in the last page (the page is always the same only the products change).
So in the end of the page i must have page 1-n
Can someone help me?
this is the js that load the products and show them one below the other:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "json/projects.json",
dataType: "json",
success: function (data) {
showInfo(data);
},
});
});
function showInfo(data) {
var htmlString = "";
if (data.length == 0) {
htmlString =
"<span id = " +
"message>" +
"Non รจ stato trovato alcun progetto" +
"</span>";
$("#list").append(htmlString);
} else {
//altrimenti stampo data
for (i = 0; i < data.length; i++) {
//scorro tutto il mio file json
htmlString =
"<div class = " + "project id = " + data[i].id + ">" +
"<div class =" + "row-list>" +
"<div class = " + "title>" + data[i].title + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/user.png>" + data[i].username + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/budget.png>" + data[i].budget + "</div>" +
"<div class = " + "info>" + "<img src = " + "img/data.png>" + data[i].data + "</div>" +
"<div class = " + "flag>" + data[i].flag + "</div>" +
"</div>";
// collego al div #list le informazioni
$("#list").append(htmlString);
}
// aggiungo l'handler per visualizzare i dettagli quando un progetto viene cliccato
$(".project").click(function () {
window.location.href = "details.php?id=" + $(this).attr("id");
});
}
}
If the page doesn't change, you can stay on the same page while simply changing the products shown.
Here's a simplified version to demonstrate how this could work:
// create 20 product names
let products = [];
for (let i=1; i<=20; i++) {
products.push(`This is Product Name ${i}`);
}
let firstShown = 0;
const display = document.getElementById('display');
// display up to 6 products on page
function addToDisplay(first) {
display.innerHTML = '';
let last = Math.min(first+5, products.length-1);
for (let i = first; i <= last; i++) {
let li = document.createElement('li');
li.innerHTML = products[i];
display.appendChild(li);
}
}
function forward () {
display.innerHTML = '';
firstShown += 5;
addToDisplay(firstShown);
}
function back () {
display.innerHTML = '';
firstShown = Math.max(firstShown-5, 0);
addToDisplay(firstShown);
}
// show initial 6 producs
addToDisplay(firstShown);
<p>Display multiple products 6 at a time<br/>
<button type="button" onclick="back();">Back</button>
<button type="button" onclick="forward();">Forward</button>
</p>
<ul id="display"></ul>

Update status while Drag and drop in sharepoint list

I have Using Nestable js to drag and drop my list items .and the drag and drop is working fine in UI .but what i need is ,I want to update the status of list items after the item is dropped..How can i achieve this using javascript..
for reference of Nestable js https://codepen.io/Mestika/pen/vNpvVw
Next am retrieving the list items like bellow code
var ListEnumerator = this.myItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
var status = currentItem.get_item('Status');
if (status == "Planned") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridprocess').append(templateString);
}
else if (status == "In Process") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridinprogress').append(templateString);
}
else if (status == "Completed") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridcomplete').append(templateString);
}
else if (status == "Hold") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridincomplete').append(templateString);
}
}
here the li tag is used under
<div class="dd">
<ol class="dd-list" id="gridprocess" >
</ol>
</div>
how can i update the status while drag and drop? please give the code to do it..
Finally I achieved the above question . with the following code...... first i have set on ID to the class name dd as ddprocess like bellow
<div class="dd" id="ddprocess">
<ol class="dd-list" id="gridprocess">
</ol>
</div>
And Next I have Write a function When the id ddprocess is on change i get the Each item id and pass the ID to the Update function
$('#ddprocess').on('change', function () {
// JSON To get the list item in Process
var $this = $(this);
var serializedData = window.JSON.stringify($($this).nestable('serialize'));
// console.log("sData:", serializedData)
// convert the JSON into Object
var obj = JSON.parse(serializedData);
obj.forEach(myFunction);
function myFunction(item, index) {
var eachid = item.id;
// console.log("Item-id", eachid);//you will get id
Updatetoprocess(eachid);
}
});
Next the update function is to Update the status to planned for each item in the ddprocess id .....
function Updatetoprocess(eachid) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var siteurl = "https://abb.sharepoint.com/sites/IAPI-SOP";
var context = new SP.ClientContext(siteurl);
var olistnew = context.get_web().get_lists().getByTitle("TaskList");
var listitem = olistnew.getItemById(eachid);
listitem.set_item('Status', 'Planned');
listitem.update();
context.load(listitem);
context.executeQueryAsync(function () {
alert("Items Updated successfully");
},
function () { console.log("failure") }
)
});
}
Thank you

Convert JSON number to stars

Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});

How to toggleClass with SignalR hub.server?

I am currently learning SignalR with .Net MVC and following a tutorial to work on a simple app. Right now it is working alright, but I am having trouble understanding some part and also if possible, want to sort of enhance it.
Plane Seats Tutorial link
Right now the app is working as when a user clicks on a seat, it reserves it. And there is no going back. I want to implement like a toggle, where if the user wants to change seat, he gets to unreserve his selected seat, and then be free to reserve another one. I am not being able to do it with myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));. Whenever I click on a seat, it gives me this error in the Dev tools
Uncaught: Converting circular structure to JSON
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
$(function() {
//// Start the hub
window.hubReady = $.connection.hub.start();
});
$.connection.hub.start().done(function() {
// Call the server side function AFTER the connection has been started
myHub.server.createUser();
//invoke for the user data
myHub.server.populateSeatData();
});
// Seat selection
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('Sorry, this seat has been already reserved');
} else {
//$(this).toggleClass(settings.selectingSeatCss);
//myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));
myHub.server.selectSeat(userId, $(this)[0].innerText);
}
});
// Client method to broadcast the message
myHub.client.createUser = function(message) {
userId = message;
};
//get seats data
myHub.client.populateSeatData = function(message) {
var parsedSeatsData = JSON.parse(message);
$('li.seat').removeClass(settings.selectedSeatCss);
$.each(parsedSeatsData, function(index, value) {
$("a:contains('" + value.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
});
};
// Client method to broadcast the message as user selected the seat
myHub.client.selectSeat = function(message) {
var parsedSeatData = JSON.parse(message);
$("a:contains('" + parsedSeatData.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
};
And can anyone please briefly explain what is str.push doing in this block of code? What is it exactly pushing into the array?
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 2; 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(''));
};
I had to use a toggleSeat() function instead of just using toggleClass.
public void toggleSeat(int userId, int seatNumber)
{
PlaneSeatArrangment mySeat = allSeats.Where(s => s.SeatNumber == seatNumber).FirstOrDefault();
var retunData = JsonConvert.SerializeObject(mySeat);
if (mySeat != null && userId == mySeat.UserId)
..............
}

Adding a table from database with javascript

I am seeking help trying to add a new table in my third function called ingredients. I am not very familiar with javascript so I tried to duplicate code from newDosage which is similar to what I need to do. Unfortunately, right now all I see is 0, 1, or 2 and not the actual text from the ingredient table. If anyone can help me correctly call the table, it would be greatly appreciated. Thank you.
Below is my code. The first function pulls the database, the second function uses the results and the third function is where I have tried to add the ingredient table.
function listTreatmentDb(tx) {
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var addsymptom = getUrlVars().addsymptom;
tx.executeSql('SELECT * FROM `Main Database` WHERE Category="' + category +
'" AND Main_Symptom="' + mainsymptom + '" AND Add_Symptom="' + addsymptom + '"',[],txSuccessListTreatment);
}
function txSuccessListTreatment(tx,results) {
var tubeDest = "#products";
var len = results.rows.length;
var treat;
for (var i=0; i < len; i = i + 1) {
treat = results.rows.item(i);
$("#warning").append("<li class='treatment'>" + treat.Tips + "</li>");
$("#warning-text").text(treat.Tips);
$('#warning').listview('refresh');
//console.log("Specialty Product #1: " + treat.Specialty1);
if(treat.Specialty1){
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
}
if(treat.Specialty2){
$("#products").append(formatProductDisplay('specialty2', treat.Specialty2, treat.PurposeSpecialty2, treat.DosageSpecialty2, '0'));
}
}
}
function formatProductDisplay(type, productName, productPurpose, productDosage, Ingredients, aster){
var newDosage = productDosage.replace(/"\n"/g, "");
if(aster=='1'){ productHTML += "*" }
productHTML+= "</div>" +
"</div>" +
"<div class='productdose'><div class='label'>dosage:</div>" + newDosage + "</div>" +
"<div class='productdose'><div class='label'>ingredients:</div>" + Ingredients +
"</div></li>"
return productHTML;
}
You are missing an argument when you call formatProductDisplay(). You forgot to pass in treat.Ingredient.
Change:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
To:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, treat.Ingredients, '1'));
Also do the same thing to the similar 'Specialty2' line right below it.

Categories

Resources