So I have a bit of a mindboggler on my hands that's refusing to bend. My objective is to log on a database every single time a page is visited. I have created on the c# side code that logs this info and I know it works. What I'm trying to do now is relatively straightfoward; every time an item (that is, a page) is clicked on the home view list (which acts as a shell for the SPA and doesnt change), send the page name to a function in Javascript which will in turn communicate to the Webmethod. The problem is, when the app starts, as it is a SPA, it collects all the divs (see below) and renders them and for some reason, it does not want to communicate and pass parameters into the javascript function, no matter where I put it (I've put it on a header, I've put it underneath the html, etc). The onclick function works fine when test it separately, but in this application, it refuses to work.
I've also tried using 'body onload="PostName();" as well as window.onload on each of the pages to invoke the function but its also a blank. Some thoughts on where the problem might be?
<tr class="row">
<td>
<div class="tabbable">
<ul class="nav nav-tabs nav-stacked" id="menuTabs">
<li class="active">Home</li>
<li class="">Tutuwa roadshows</li>
<li class="">FAQ's and presentations</li>
<li class="">Example scenarios</li>
<li class="">Financial advisors</li>
<!--<li class="">Private Clients</li>-->
<li class="">Trust deeds</li>
<li class="">Newsflashes</li>
<li class="">Useful links and contacts</li>
<li class="">Webinar</li>
</ul>
</div>
<div class="newsflash">Click here for the latest newsflash.</div>
</td>
<td rowspan="2">
<div class="tab-content">
<div class="tab-pane active" id="land">#Html.Partial("Land")</div>
<div class="tab-pane" id="tutuwaroadshow">#Html.Partial("TutuwaRoadshow")</div>
<div class="tab-pane" id="faqsandpresentations">#Html.Partial("FaqsAndPresentations")</div>
<div class="tab-pane" id="examplescenarios">#Html.Partial("ExampleScenarios")</div>
<div class="tab-pane" id="financialadvisors">#Html.Partial("FinancialAdvisors") </div>
<div class="tab-pane" id="privateclients">#Html.Partial("PrivateClients")</div>
<div class="tab-pane" id="trustdeeds">#Html.Partial("TrustDeeds")</div>
<div class="tab-pane" id="newsflashes">#Html.Partial("NewsFlashes")</div>
<div class="tab-pane" id="usefullinksandcontacts">#Html.Partial("UsefulLinksAndContacts")</div>
<div class="tab-pane" id="webinar">#Html.Partial("Webinar")</div>
</div>
</td>
</tr>
</table>
the function, currently sitting on the header:
<head>
<script type="text/javascript">
function PostName(pageName) {
debugger;
//String PageName = "ExampleScenarios";
$.ajax({
type: "POST",
url: 'HomeController/SaveVisitorHits',
data: { s: pageName },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//do nothing
},
error: function (e) {
// do nothing
}
});
}
</script>
<title></title>
</head>
Note that when I seperate this code from the app, it works fine (see http://jsfiddle.net/cLp6y51c/ as was created by another user who was trying to help earlier on). The problem is within the application, maybe some sort of setting that I'm not aware of.
This is the alternate method I've tried on each of the pages but also doesnt work:
<header>
<img src="../../content/images/examplescenarios-header.jpg" style="height: 340px" />
<script type="text/javascript">
function PostName() {
debugger;
//String PageName = "ExampleScenarios";
$.ajax({
type: "POST",
url: 'HomeController/SaveVisitorHits',
data: { s: "ExampleScenarios" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//do nothing
},
error: function (e) {
// do nothing
}
});
}
window.onload = PostName;
</script>
</header>
<body onload="PostName();">
It looks like you are making a call to a wrong URL. I presume it is a .NET MVC app? In .NET MVC you don't put the word Controller in the URL. The URL should be Home/SaveVisitorHits
Related
I have this part of HTML:
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text">{content}</p>
Read...
</div>
</div>
</div>
</div>
</div>
and I have ajax request which calls after page loading:
<script>
$(window).on('load', function () {
loadArticles();
});
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles", success: function (result) {
}
});
}
</script>
I need to create list of cards(<div class="card">) with data from response. For example, I get 5 articles in response. I need to create 5 card divs and fill its data from the response. How can I do it?
Loop over the objects you get back from the ajax call and use the jQuery .append() function to add them to the dom.
First, you need to add an identifying class (or id) to the parent div in your HTML and remove the card HTML:
<div class="container">
<div class="row">
<div class="col-sm-4 cards-wrapper"></div>
</div>
</div>
Then in your loadArticles function loop over your ajax response and append to that jQuery selected we just defined - '.cards-wrapper':
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles",
}).done(function(data) {
const cards = data.body.cards; // Or however you need to traverse the response object
cards.forEach(function(card) {
$('.cards-wrapper').append('<div class="card"><div class="card-body"><h4 class="card-title">' + card.title + '</h4><p class="card-text">' + card.content + '</p>Read...</div></div>');
})
});
}
Ideally you should extract out that append code into its own function for readability, etc.
You can do it by simply using html template
HTML
First you need to add card-container id to the HTMl tag in which we will inject HTMl using ajax
<div class="container">
<div class="row">
<div class="col-sm-4" id="card-container">
</div>
</div>
</div>
Javascript
<script>
$(window).on('load', function () {
loadArticles();
});
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles", success: function (result) {
//Get template html using ajax and append it with **card-container**
var cardTemplate = $("#cardTemplate").html();
result.forEach(function (card) {
$('#card-container').append(cardTemplate.replace("{title}",
card.title).replace("{content}", card.content));
})
}
});
}
</script>
HTML Template
Assign id cardTemplate to html template
<template id="cardTemplate">
<div class="card">
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text">{content}</p>
Read...
</div>
</div>
</template>
I have also implemented on my end so it will surely gonna work !!!
Building a script that once a date is selected in a datepicker calendar, it uses ajax to post the selected date in a php script;
in the success of that ajax call, it uses another ajax call to post the same selected date to another php script and displays that in the page.
Did some research around and this seemed to be the best solution for what I try to do.
The script is the following:
<script> //for the events
jQuery(function($) {
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
}).on("change", function() {
display("Got change event from field");
// call next ajax function
var mydate = this.value;
$.ajax({
type: "POST",
url: 'boxes_script.php',
data: ({dates: mydate}),
dataType : 'html',
success: function(data) {
$('.caixas').html(data);
alert(data);
$.ajax({
type: "POST",
url: 'events_script.php',
data: ({dates1: mydate}),
dataType : 'html',
success: function(data) {
$('.results-ajax').html(data);
alert(data);
}
});
}
});
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
</script>
This is the code being used atm. Got some updates because of the feedback given here, but the solution still hasn't worked 100%
There's a problem on it and I think it's because the second Ajax call is inside of a success Ajax.
The problem is the following:
The data is being posted in the php scripts, which run like how they should.
The array gets populated with the right information.
The
$('.caixas').html(data);
works fine and displays data from 'boxes_script.php' there.
The
$('.results-ajax').html(data);
receives 100% of the data being sent from 'events_script.php' but for any weird reason, doesn't append it to the page..
I can see the data in alert messages and it's the right data being sent to the browser.
Why isn't that data being appended to the page?
This is the php code for 'events_script.php':
<?php
include 'config/config.php';
include 'libraries/database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
print_r($_POST);
echo $_POST[dates1];
$dias= $_POST[dates1];
$mysql_date = date('Y-m-d', strtotime($dias));
echo $mysql_date;
//Make database query
$sql = "***";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$image = $row['Company_Logo'];
$myArray = json_decode($image, true);
$event=$row['eventID'];
echo '<div class="tab-pane" role="tabpanel">
<div id="'.$dias.'" class="container day-events">
<div class="row event-list">
<div class="event-list-time col-md-3 col-sm-3 center" style="background-image:url('.$myImage = $myArray[0]['name'].');">
<p class="event-list-start-time">'.$row['Start_Date'].'</p>
<hr class="event-list-time-divider">
<p class="event-list-end-time">'.$row['End_Date'].'</p>
</div>
<div class="event-list-info col-md-9 col-sm-9">
<h2 class="event-list-name">'.$row['Event_Name'].'</h2>
<p>Organized by <span class="event-list-organizer">'.$row['Company_Name'].'</span></p>
<p class="event-list-description">'.$row['Event_Description'].'</p>
<button type="button" class="btn more-info-list">More Information</button>
</div>
</div>
</div>
</div>';
}} else { echo 'No results found.'; }
}
?>
Note: no errors were found in the error log. The network gives status 200.
The data can be seen sent to the browser here:
The first part of the data is being appended to the browser, as you can see in the images.
Why is not working everything?
This was what fixed the problem and made the following final result:
Old:
<div class="row events-tabs">
<div class="container" data-example-id="togglable-tabs">
<ul class="nav nav-pills center caixas" id="myTabs" role="tablist">
</ul>
<div class="results-ajax tab-content" id="myTabContent">
</div>
</div>
</div>
New:
<div class="row events-tabs">
<div class="container" data-example-id="togglable-tabs">
<ul class="nav nav-pills center caixas" id="myTabs" role="tablist">
</ul>
<div class="tab-content" id="myTabContent">
<div class="results-ajax"></div>
</div>
</div>
</div>
So, basically using results-ajax as class of an own div fixed the problem.
Change
data1: ({dates1: this.value})
to
data: ({dates1: this.value})
var mydate = this.value; // add before the 1st ajax call
change -
data1: ({dates1: mydate})
Here I need to click on a thumbnail, so that it will show the details on other page, it should show the details of that particular thumb only. I used xml file here to fetch the data and display thumbnail. I am unable to pass the values to other page and open it at the same time onclick event. pls help
<div class="container-page">
<div class="row" id="portfolio">
<div class="col-md-2">
<nav>
<ul class="nav nav-pills nav-stacked" id="test">
<li role="presentation" class="active">Services</li>
<li role="presentation">Desktop</li>
<li role="presentation">Web</li>
<li role="presentation">Mobile</li>
<li role="presentation">Design</li>
</ul>
</nav>
</div>
<div class="col-md-10">
<div class="row" id="thumb">
</div>
</div>
</div>
</div>
<!-- js -->
$.ajax({
type:"GET",
url:"portfolio.xml",
dataType:"xml",
success:function(xml)
{
$(xml).find('thumbnail').each(function()
{
var $thumbnail=$(this);
var type=$thumbnail.find('type').text();
var descr=$thumbnail.find('description').text();
var title=$thumbnail.attr('title');
var imageurl=$thumbnail.attr('imageurl');
var thum='<div class="col-xs-6 col-md-3"> </div>';
thum=$(thum).appendTo("#thumb");
thum = $('').appendTo(thum);
var thumName = $('<div class="thumTitle"></div>').appendTo(thum);
$('<h2>'+title+'</h2>').appendTo(thumName);
$('<p>'+type+'</p>').appendTo(thumName)
thum = $('<img src="'+imageurl+'" alt="image" class="thumbImgSize imgSlide">').appendTo(thum);
$(".forHove").mouseup(function()
{
//here is the redirection code, and want to pass $thumbnail to testxml.html page
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
});
}
});
Well, one of the alternative is using Web Storage API.
Just store img html and use it.
// use 'click' instead of 'mouseup'
$(".forHove").click(function()
{
// store image html to sessionStorage
window.sessionStorage.image_data = $thumbnail.clone().wrapAll("<div>").parent().html();
window.location="http://www.bookmane.in/skillworks/testxml.html";
$(thum).appendTo(".s");
});
// in http://www.bookmane.in/skillworks/testxml.html
// You have data sotred and insert it somewhere
$(document.body).append(window.sessionStorage.image_data);
You can achieve this thing using the following steps:
Add a form tag like
<form action="YOUR_PATH" method="GET">
<a class="thubnailClick" href="#" >
<html_of_your_thumbnail>
<input type="text" name="NAME_OF_PARAMETER" />
</a>
</form>
Now override the click event of <a> tag with
$(document).ready(function() {
$(".thubnailClick").on('click', function(event) {
// to override the default behavior of <a> tag.
preventDefault();
// Find the form element using closest() of jQuery.
// Call submit event of that form using $(form_element).submit();
});
})
Now on the other page you can get parameter from URL using location.search or follow:
Getting Query params using JavaScript
Now use these Params according to your needs.
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".
I want to display the partial view, when I click on navigation bar click. I have a view which contains left side menu. when user click on navigation bar item, appropriate view should display.
I am not getting how can I implement such view?
Manage.cshtml
<div class="row">
<div class="col-xs-12">
<div class="page-header">
<h1>My Account</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked nav-stacked-extended">
<li class="active">
<a id="A3" target="_self" runat="server" href="#Url.Action("Contactinfo", "Account")">Contact Info</a>
</li>
<li class="">
<a id="A4" target="_self" runat="server" href="#Url.Action("changePassword", "Account")">Password</a>
</li>
</ul>
</div>
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
#Html.Partial("Contactinfo")
</div>
</div>
</div>
In above code, I have created left side menu i.e contactinfo, changepassword etc. when Manage.cshtml load first time I want to display Contactinfo view. When user click on password menu, contactinfo get's changed with changedpassword page. Please check following screen shot.
Here in above image you can see left side menu and appropriate page. What I want when user click on password, view changed to password page. Currently it shows contact info page. How can I do this?
i think you should render partial through JavaScript.
Let's say you have <div id="partialView"></div>
Then you should run Ajax query when user clicked on link.
Something like:
$.ajax({
url: $(this).data('yourUrl'),
type: 'GET',
cache: false,
success: function(result) {
$('#partialView').html(result);
}
});
Took me a little while to figure this out too.
Essentially, you want your Controller action to return a partial view, then use Ajax to load that returned partial view.
JavaScript / Ajax
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
data: { 'viewName': 'password' },
success: function (data) {
$('#partial-container').html(data);
}
});
Controller return type
Public ActionResult GetView(string viewName)
{
return PartialView(viewName, model);
}
Ideally, change your HTML so it's easier to reference the div container where you'd like to load the partial
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
<div id="partial-container">#Html.Partial("Contactinfo")</div>
</div>
</div>
In your requirement just make partial Views of the links present in your left side bar and when user clicks on a specific option in left side bar then just load a appropriate partial view from ajax call using jquery and just replace html of right side bar with the html coming from ajax call.
Give your left side menues unique id and then :
A Demo :
$(document).ready(function(){
$("#menu1").click(function(e){
e.preventDefault();
$.ajax({
url: "/MyController/getdata",
type: 'GET',
datatype: 'html',
data: { },
success: function (data) {
$("#div1").html('');
$("#div1").html(data);
});
});
});
Controller(MyController) :
[HttpGet]
Public ActionResult getdata(string dropval)
{
//bind model here
return PartialView("mypartialview",model)
}
try This JS for Clickevent
$(document).on('click', '#anCalcBtn', function () {
$('#anCalcDetail').load('/Home/Contactinfo/');
});
If I am not wrong you are trying to do like This