how to pass id to another html page - javascript

Below is my javascript in nextPage.js. When I click on it, it must pass category_id to the reportlist.html page. Please help me.
var base_url = "http://dev.edfutura.com/nithin/jps/edfuturaMob/";
$(document).on("pageinit", "#catlist", function() {
var submitUrl = base_url+"categorylist/get_categorylist";
$.ajax({
url: submitUrl,
dataType: 'json',
type: 'POST',
success: function(response) {
var categoryList = $('#category');
var category;
for(var i = 0, len = response.length; i < len; i++) {
category = response[i];
var a = $('<a>').attr('href', 'reportlist.html').html(category.category_name);
categoryList.append($('<li>').attr('id', category.category_id).append(a));
}
},
error: function() {
alert("error");
}
});
My first page is nextPage.html and my category_names are stored in a list as links through JS.
<body id="category_id">
<div data-role="page" id="catlist">
<div id="loading"></div>
<div data-role="header" data-position="fixed" data-theme="b">
<h1>category</h1>
</div>
<div data-role="main" class="ui-content">
<form id="nextForm" >
<ul data-role="listview" data-inset="true" id="category">
<li id="catid"></li>
</ul>
</form>
</div>
</div>
</body>

If you want to pass some data when you change the page, you must use request parameters
When you want to pass data in href link, you should use GET request like this:
reportlist.html?category_id=12
Then you can read your data similarly to this https://stackoverflow.com/a/979995/4772988

Related

res.render() function rendering an ejs page doesn't refresh the UI, but the ejs page get called

I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:
resourcefilter.js:
router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});
});
The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.
resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.
<% layout('layout/layout') %>
<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>
<div class="container" style="margin-top: 2%;">
<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip">
<div class="frontside">
<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>
<br></br> </div>
</div>
<br></br>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
AJAX function to call to /filterresources:
function filter_resources(e) {
e.preventDefault();
var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];
//Form Handling with ajax
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
});
function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}
}
Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.
If you don't have any errors from your server you can do a workaround with the front end:
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
}).then(() => location.reload());
That will refresh your page when the request finishes.
location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:
filterresources.js
router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
var user = req.user._id;
console.log(user);
db.findAll(Resource,{category:category})
.then(function(data){
res.send({msg: data, success: true,user: user });
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});
});
AJAX function:
function filter_resources(e) {
e.preventDefault();
var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];
//Form Handling with ajax
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
success: function (response) {
if (!response.success) {
window.alert(response.msg);
}
if (response.success) {
var resource = response.msg;
var userInfo = response.user;
$('#resfilter').html(""); // reset the contents in the div
var html = `<div class="row">`;
for(var i=0;i<resource.length;i++) {
html += `<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip"> <div class="frontside"> <div class="card-custom">
<div class="card-body text-center">`;
html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
html += ``;
html += `Read More!`;
html += `<br>`;
html += `</br></div></div><br></br></div></div></div></div>`;
}
html += `</div></div></div></div>`;
}
document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
}
})
}

Using AJAX in Node js and displaying data using Handlebars

I am using AJAX and Handlebars to get data from my MongoDB without refreshing the page and represent it in an easier manner.
I have created a div with a search button where a user places his/her inputs. These inputs need to passed to my routes and then the results from my DB should be sent back from my routes, to the handlebar which will help me display the products.
index.hbs
<div id="search-form">
....
<input id="bhkInput" name="bmin" type="number">
<input id="priceMin" name="pf" type="number">
<input id="priceMax" name="pt" type="number">
<input type="submit" class="btn searchButton" id="submit" value="Search" onclick="showResults()">
</div>
<div class="row col-sm-12 searchResults" id="sr">
//Results need to be displayed here
</div>
<script id = "result-template" type="text/x-handlebars-template">
{{#each searchResults }}
<div class="row">
{{#each this }}
<div class="col-sm-6 col-md-4">
...
<img src="{{this.imagePath}}" alt="..." class=" card-img-top">
<div class="card-body">
<h4>Flat No: {{this.flatNo}}</h4>
...
<p class="description">
{{this.description}}
</p>
...
...
</div>
</div>
</div>
</div>
{{/each}}
</div>
{{/each}}
</script>
<script>
function showResults(){
let bmin = document.getElementById('bhkInput').value;
let pf = document.getElementById('priceMin').value;
let pt = document.getElementById('priceMax').value;
$.ajax({
type: 'GET',
data: {
bmin: bmin,
pf: pf,
pt: pt
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/results",
success: function(data){
let source = $('#result-template').html();
let template = Handlebars.compile(source);
let html = template(data);
$(".searchResults").innerHTML = html;
}
});
}
The issue that I am facing:
When I send back the results from my DB, I am unable to display it using Handlebars.
How do I handle the data after success function is called. I want the results to be appended in the 'searchResults' div. I went through this link, however I am yet not able to see the data of my results.
Update
I took dummy data from the Handlebars Docs and used it for my template and yet there is no data being appended in the html
The console.log(html) returns the template without the new data items
index.hbs
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
<script>
....
$.ajax({
....
success: function(data){
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var context = {title: "My New Post", body: "This is my first post!"};
var html = template(context);
console.log(html);
....
</script>
Output for console.log(html)
<div class="entry">
<h1></h1>
<div class="body">
</div>
</div>
For the first issue. Your method is GET so I think you can get it by req.query.productId.
For the second issue. You should append your data in ajax success callback function, because ajax is asynchronous. For example:
$.ajax({
type: 'GET',
data: encodeURIComponent(searchObject),
url: "/results",
success: function(data){
console.log(data);
let sr = document.getElementById('sr');
$(sr).append();
}
});
How to get "data" from JQuery Ajax requests

Bind Multi Line HTML content from JQuery Ajax response

This is the part of my html code that binds to the view using a Model object.
#if (Model.Comments != null)
{
#foreach (var thread in Model.Comments.Threads)
{
<div class="comment-wrap">
<div class="comment-head">
<div class="subsciber-user" style="background: #DDEFC5">#thread.UserName.Substring(0, 2).ToUpper()</div> #thread.UserName <span>#thread.PostedDate.ToString("dd MMM yyyy")</span>
<div class="edit-comment"><img class="comment-edit-img" src="~/images/edit-task.svg"></div>
</div>
<div class="clearfix"></div>
<div class="comment-content">
#thread.Content
</div>
#if (thread.Attachment != null)
{
<div class="comment-attachment">
<div class="ca-head">#thread.Attachment.Count() Attachments<i><img class="c-download" src="~/images/download.svg" alt="" /></i></div>
<div class="ca-tiles">
#foreach (var item in thread.Attachment)
{
<span><img src="#item.AttachmentUrl" alt="Smiley face"></span>
}
</div>
</div>
}
</div>
}
}
My requirement is I want to bind this HTML from a jquery Ajax Success. for that, I created an Ajax call.
var val1 = $('#TaskId').val();
#*$(document).ready(function () {
$.ajax({
url: '/Task/GetTaskComments',
data: { id: val1},
dataType: "json",
success: function (comments) {
// here i neeed to bind this Html block using each loop,
// here we are getting the same response that we are getting Model.Comments in the above code as json
}
});
});
I want to append the looped Html content from ajax success inside my
<div class="bindComments">
</div>

How to get a listview to refresh with new data from a Kendo datasource

How do I get my list view page to refresh when I load new data into my kendo.data.DataSource?
I'm working on a Hybrid Mobile app using Telerik AppBuilder.
I have a simple listview that is bound to a data source.
I use an ajax POST request to load some JSON,
then place it in the datasource.
I have two pages, home and list view.
The home has some anchors that lead to a single list view page,
but with different data id values to produce different lists.
The first time I the list view page it loads correctly.
After that, the list view does not refresh when I reload the datasource;
the contents of the first list always display no matter what data id value I send in.
Here is the source:
JavaScript
window.APP =
{
blamListSource: null,
home:
{
fetchBlam: function(event)
{
var argumentData = event.button.data();
var requestBody =
{
"requestVersionId": "1",
"blamId": argumentData.id.toString()
};
$.ajax(
{
url: getBlamURI,
type: "POST",
data: JSON.stringify(requestBody),
dataType: "json",
contentType: 'application/json',
success: function(requestData, textStatus, jqxhr)
{
APP.blamListSource = new kendo.data.DataSource(
{
data: requestData.userList,
});
APP.blamListSource.read();
app.navigate("views/blamlist.html");
},
error: function(jqxhr, textStatus, error)
{
alert("Error");
},
});
}
}
};
home.html
<div data-role="view" data-title="Home" data-layout="main"
data-model="APP.models.home" data-zoom="true">
<div id="form-blam" data-role="content">
<a id="commercial" data-role="button"
data-bind="click: fetchBlam" data-id="27">Something</a>
<a id="personal" data-role="button"
data-bind="click: fetchBlam" data-id="39">Something Else</a>
</div>
</div>
views/blamlist.html
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true">
<div data-role="navbar">
<a class="nav-button" data-align="left" data-role="backbutton">Back</a>
</div>
<ul id="blam-listview" data-style="inset" data-role="listview"
data-template="blamListTemplate" data-bind="source: blamListSource">
</ul>
<p id="no-contactlist-span" hidden="hidden" class="no-items-msg">
<b>No blam.</b>
</p>
</div>
<!-- Blam ListView Template -->
<script type="text/x-kendo-template" id="blamListTemplate">
<div>
<div>
<img id="blamPhoto" src="#: data.photoUri #"/>
</div>
<div>
<div id="name">#: data.name #</div>
<div>#: data.title #</div>
<div>
<div>
<a data-role="button" class="callimg"
data-phone="#: data.phone #" href="tel:#: data.phone #"
data-rel="external"></a>
</div>
<div>
<a data-role="button" class="emailimg"
href="mailto:#: data.email #"
data-rel="external"></a>
</div>
</div>
</div>
</div>
</script>
It appears to be fairly easy.
Add data-reload="true" to the view.
Old - does not refresh
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true">
New - refreshes
<div data-role="view" data-title="Blam List" data-layout="main"
data-model="APP" data-zoom="true" data-reload="true">
Edit I accidentally put "data-refresh", which is wrong. The correct value (edited to be correct) is "data-reload".

Submitting multiple dynamic forms

I'm trying to submit multiple forms at once when a single button is clicked. These forms are all generated automatically. They all have different action urls but the same id's. That's how the system (SaaS) works.
The problem is that I'm having issues getting the correct selectbox values and then send the forms. I'm not getting any error but I think it has something to do with identifiers. I'm working on this one for a few days now and I can't figure this one out.
So for every set/product there's some empty html, like so:
HTML
<div id="sets" class="clearfix">
// first set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// second set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// etc... can be as much as 10 sets
</div><!-- .#sets -->
Inside the above HTML .product there comes an automatically generated form. This form is generated like so:
Jquery
$('#sets .set').each( function(){
$(this).click(function(){
if($(this).hasClass('open')){
$('.close').click(function(){
$('#sets .product').fadeOut();
$('.products',this).animate({
width: 'toggle'},500, function() {
.......
});
});
} else {
.....
}
var url = $(this).data('handle')+'?format=json';
$.getJSON(url, function (data){
var product = data.product;
var $container = $('.products .product');
var productsHtml = [];
var fullurl = 'http://www.shop.com';
var variants = '';
$.each(product.related, function(index, rel){
var url = ''+fullurl+''+rel.url+'?format=json';
...... etc ...
var productHtml = '<div id="'+rel.id+'" class="p"><form method="post" id="product_configure_form" action="http://www.shop.com/cart/add/'+rel.vid+'/" name="formsub"><div class="foto"><img class="rollover" src="'+image+'" hover="'+image2+'" alt="'+rel.fulltitle+'"/></div><div class="prijs" data-price="'+rel.price.price_incl+'">€'+rel.price.price_incl+'</div><div class="varianten_'+rel.id+'">';
$.getJSON(url, function (data){
var rel = data.product;
var wqsSelectVariants = $('<div class="product-configure-variants tui" />');
var select = $('<select id="product_configure_variants"/>');
$.each(rel.variants, function (index, variant){
select.append('<option value=' + variant.id + '>' + variant.title + '</option>');
wqsSelectVariants.append(select);
});
$('.varianten_'+rel.id).html(wqsSelectVariants);
});
var price = rel.price.price_incl;
sum += price;
productHtml = productHtml + '</div></form></div>';
productsHtml.push(productHtml);
});
$('.total').text('€'+sum.toFixed(2));
productsHtml = productsHtml.join('')
$container.html(productsHtml);
});
}
});
});
etc....
<script type="text/javascript">
$(document).ready(function(){
$(".trigger").on("click", function(e){
e.preventDefault();
$('form[name="formsub"]').each(function(){
var variant = $('#product_configure_variants').val();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action')+variant+'/?quantity=1',
data: $form.serialize(),
success: function(data, status){
if(status == 'success'){
}else if(status == 'error'){
}
}
});
});
});
});
</script>
Does anyone know what's going wrong or give me some directions on how to fix that?
Try using $('form[name="formsub"]:visible') as your selector. That should give you just the visible forms instead of all the ones on the page.

Categories

Resources