Load a div without refreshing the page in asp.net - javascript

I'm loading a popup div dynamically with different html page contents. The HTML page controls are rending on div successfully but the problem is, the whole page is refreshing during loading the content using $("#middlepart").load()
I want to reload the content without refreshing the page in asp.net.
The code is given below:
<div class="popmiddlepart">
<div class="type-benifit">
<div class="subdivOne">
<div class="fl-lt">
<label>Type of Benefit</label>
</div>
<div class="fl-lt">
<div id="ddlBenefitType" >
</div>
</div>
<div class="clearfix"></div>
<hr style="margin-bottom: 10px; margin-top: 10px;">
</div>
</div>
<div id="relate-message-box-html" style="display: none">
<i class="fa fa-info-circle" aria-hidden="true" style="color: red;"></i><strong></strong>
<span id="spnToolTipTexthtml"></span>
</div>
<div class="clearfix"></div>
<div id="middlepart" class="dynamic-content">
<div class="middle-part">
content goes here
</div>
</div>
</div>
I'm updating the div calling the dropdown onchange event
$("#ddlBenefitType").relateSelectControl({
selectControlDataSource: benefittypedata,
dataValueField: 'id',
dataTextField: 'text',
onchange: function (e) {
e.preventDefault();
var selectedtype = $("#ddlBenefitType").getSelectControlText();
if (selectedtype == 'Accommodation') {
var key = getQueryStringValue('id');
$("#middlepart").load(baseUrl + "employee/accomodationdetails_ie.html?id=" + key);
}
if (selectedtype == 'Loan') {
var key = getQueryStringValue('id');
$("#middlepart").load(baseUrl + "employee/loandetails_ie.html?id=" + key);
}
}
});

Try $.get(). It is shorthand for making a jquery ajax call to load the html from an external source asynchronously.
Something like this should work:
$.get( baseUrl + "employee/accomodationdetails_ie.html?id=" + key, function( data ) {
$( "#middlepart" ).html( data );
});

Related

Dynamically Updating Controls ASP.Net and Bootstrap

I cannot for the life of me work out how to update bootstrap controls with ASP.Net.
I have the following code:
#{
Layout = null;
}
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title Mark Hub</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<script>
var url = "http://localhost:51520/api/teacher/"
function getTerms(course) {}
//get a reference to the select element
$select = $('#termSelect');
//request the JSON data and parse into the select element
$.ajax({
url: url + "global/currentterms/" + course ,
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.person, function(key, val){
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
</script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Mark Hub", "Index", "Teacher", null, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Teacher", "Index", "Teacher")</li>
<li>#Html.ActionLink("Admin", "Index", "Admin")</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-1 text-left">
<select class="form-control" id="courseSelect" onclick="getTerms()">
<option>DEC 10</option>
</select>
</div>
<div class="col-md-1 text-left">
<select class="form-control" id="termSelect">
</select>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<hr />
<footer>
<p>© #DateTime.Now.Year</p>
</footer>
</div>
</div>
</div>
</div>
</body>
</html>
I am trying to take the value the user selects (I only have one for convenience at the moment) from the courseSelect control, pass it to my Javascript function getTerms, call a web api and populate the termSelect control dynamically from the returned JSON.
Selecting a value from my courseSelect combobox is not updating my termSelect combobox.
How would I fix my code?
EDITED WITH UPDATE CODE TO REFLECT UPDATES IN ANSWERS
<script>
var url = "http://localhost:51520/api/teacher/"
$(function(){
$('#courseSelect').on('change',function(){
// This is equal to your getTerms function
var course = $('#courseSelect').val();
//request the JSON data and parse into the select element
$.ajax({
url: url + "global/currentterms/" + course,
dataType:'JSON',
success:function(data){
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.termID, function(key, val){
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
},
error:function(){
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
})
})});
</script>
My code still doesn't work and when I add a breakpoint in VS, the function isn't called on me selecting a value from the select box courseSelect.
You are calling this function getTerms() on click of the select tag.. which is wrong.. you must use on change event . Even click will work but then it will get trigerred even if you click the text box which will do a API call , this is unnecessary request .. Also stop using inline event binder it's deprecated and soon will stop working in future, you must bind event using on in Jquery change your code to below.
Remove the onClick in your HTML
<select class="form-control" id="courseSelect">
<option>DEC 10</option>
</select>
Then in Jquery use this
$(function(){
$('#courseSelect').on('change',function(){
// This is equal to your getTerms function
var course = $(this).val();
// rest of your logic goes here
});
});
your javascript' function is getTerms(course), while you are calling it on your click method as getTerms()
so you should change your javascript as following :
function getTerms() {}
//get a reference to the select element
$select = $('#termSelect');
$course= $('#courseSelect').val(); // this is how you get the value of course
//your next code

Data repopulate using jquery, javascript

I have a div like below in HTML page:
When I click on any div I am saving the span text in DB and when again come back to the same page I am getting the response as saved text. on the basis of the text I need repopulate the clicked view.
I am adding all the code I have used, not able to populate the data.
<div class="panel-body">
<div class='score score-exel'>
<div class='arrow'></div><span class='scoreText'> 750-850 Excellent</span>
</div>
<div class='score score-good'>
<div class='arrow'></div><span class='scoreText'> 700-749 Good</span>
</div>
<div class='score score-ok'>
<div class='arrow'></div><span class='scoreText'> 650-699 OK</span>
</div>
<div class='score score-fair'>
<div class='arrow'></div><span class='scoreText'> 600-649 Fair</span>
</div>
<div class='score score-poor'>
<div class='arrow'></div><span class='scoreText'> 300-599 Poor</span>
</div>
<div class='btnHold'>
<button class='btn btn-success idkBtn'>I Don't Know</button>
<button class='btn btn-success submitBtn'>Submit</button>
</div>
</div>
In the below code for variable I am adding the selected value when the user clicks the div.
$('.score').bind('click', function(){
$('.arrow').hide();
$(this).find('.arrow').fadeIn();
userCreditScore = $(this).find('span').text().toString();
});
In below code I am getting response and trying to repopulate the data but not possible.
function fillData(){
var response = nav.scorm.getResponse('CREDIT_SCORE');
if(response != ''){
var jsonData = jQuery.parseJSON(response);
*** used many codes like below but not useful
//$('.score').find('span.scoreText:contains('+jsonData.CREDIT_SCORE+')').parent().css('display', 'block');
//$('.score').find('span.scoreText:contains('+jsonData.CREDIT_SCORE+')').parent().click();
}
I assume that you're missing the callback in your nav.scorm.getResponse method - if it's a AJAX call. Check the commented code you have:
//here we do the request
var response = nav.scorm.getResponse('CREDIT_SCORE');
//this line and is executed immediately, while 'response' var is still undefined
if(response != ''){
So depending on code you have in nav.scorm.getResponse you might have smth like
nav.scorm.getResponse('CREDIT_SCORE', function(response){
if(response != ''){
//put it to DOM
console.log(response);
}
});
UPD
The problem was with the spaces in your scores texts,
' 600-649 Fair' won't work, while '600-649 Fair' will do.
Check this fiddle - https://jsfiddle.net/shershen08/v3gxy8rL/

Using datepicker with jquery, dialog box associated with div onselect

Not sure if this is possible, I'm just starting to learn javascript and jQuery. If the way that I would like is not possible, I am very open to hearing of different ways I may be able to achieve this.
I want to display a datepicker, the user will click on dates and when they do a dialog box appears which has specific predefined data in it. They can select a different date, and it will open another dialog box with different predefined data in it, and I want to keep track of the dates that they click on.
<div id="tabs">
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
<div id="tabs-1">
<p>I'm going to have different data applying to only this day</p>
</div>
<div id="tabs-2">
<p>I'm going to have different data applying to only this day</p>
</div>
<div id="tabs-3">
<p>I'm going to have different data applying to only this day</p>
</div>
</div>
Open jQuery dialog box upon selecting a date from jQuery datepicker inline
That link was useful because a user has a jsfiddle posted: http://jsfiddle.net/qqabC/ which is a start to what I am trying to do, I am just not sure of how or if it is even possible to incorporate divs into the dialog boxes like so. I keep messing around with it but I have been getting nowhere. Each date that is selected will have different dialog box content in it.
If this is not possible, what would be the best way to achieve this? Thank you.
--Edit:
I still need to implement the divs that I have defined above with div id "tabs". Tabs = workout days. So tabs-1 to tabs-5 would be 5 total days. tabs-1 is going to be their first click which is day 1 form content, tabs-2 will be their second click which is day 2 form content, and so on. I believe I should use a for loop, because which each click the div is being incremented onto the next one. I was trying to do something like:
var divs = $('#tabs > div[id]');
var links = $('#tabs li');
divs.hide();
for (i=0;i<=max_workouts;i++) {
$('#tabs li').on('click', function(e){
var clickedID = $(this).attr('href').clone().appendTo(#workout-modal);
}
Something like that, to iterate through the div's with each click, but it's not working, I have been trying to find examples of placing existing div content in modals but there is nothing on iterating through divs in this way, do you have any suggestions?
Here is an example of how you could achieve this functionality using Bootstrap. Of course you'll need to change the functionality and design as needed but this should be a fair start
The workflow is as follows:
User clicks a date
Modal is displayed with various inputs
Inputs are cleared when modal opens
User enters info in the inputs
User clicks add workout
A span label is added to the display showing the workout number and the date selected
This span has data attributes set to store the date, title, and each of the values from the modal inputs
If user clicks the "X" on the right end of the span, it is removed
If user clicks the span label anywhere else it reopens the modal and populates the inputs with the data stored as attributes on the span
If the user clicks add workout after loading an existing one, the new span replaces the old one instead of adding to the end of the div
Here is a jsFiddle also
$(function(){
var max_workouts = 5;
$('#workout-datepicker').datepicker({
startDate: "today"
}).on('changeDate', function(e) {
var cur = $('.workout-label').length;
if (cur < max_workouts) {
var workoutDate = e.format('mm/dd/yyyy');
var title = 'Workout ' + (cur + 1) + ' - ' + workoutDate;
openModal(title, workoutDate);
}
else{
var $tooMany=$('#too-many');
$tooMany.show();
setTimeout(function(){ $tooMany.hide() }, 2000);
}
});
var $workoutLabelsContainer = $('#workout-labels-container');
$('#add-workout').click(function() {
var $workoutModal = $('#workout-modal');
var workoutDate = $workoutModal.data('workout-date');
var title = $workoutModal.data('workout-title');
var vaule1 = $('#modal-workout-value-1').val();
var vaule2 = $('#modal-workout-value-2').val();
var $workout = $('<span class="label label-primary workout-label col-sm-12">' + title + '<span class="glyphicon glyphicon-remove pull-right remove-workout" aria-hidden="true"></span></span>');
var clickedLabelIndex = $workoutModal.data('crurent-label-index');
$workout.data('workout-title', title).data('workout-date', workoutDate).data('value-1', vaule1).data('value-2', vaule2);
if (clickedLabelIndex == -1) $workoutLabelsContainer.append($workout);
else($('.workout-label').eq(clickedLabelIndex).replaceWith($workout))
$workoutModal.modal('hide');
});
$workoutLabelsContainer.on('click', '.remove-workout', function(e) {
e.stopPropagation();
$(this).closest('.workout-label').remove();
})
$workoutLabelsContainer.on('click', '.workout-label', function() {
var $workoutLabel = $(this);
var workoutDate = $workoutLabel.data('workout-date');
var title = $workoutLabel.data('workout-title');
var value1 = $workoutLabel.data('value-1');
var value2 = $workoutLabel.data('value-2');
var labelIndex = $('.workout-label').index($workoutLabel);
openModal(title, workoutDate, value1, value2, labelIndex);
});
function openModal(title, workoutDate, value1, value2, labelIndex) {
var $workoutModal = $('#workout-modal');
var $value1 = $('#modal-workout-value-1').val('');
var $value2 = $('#modal-workout-value-2').val('');
$workoutModal.data('workout-title', title).data('workout-date', workoutDate);
$('#workout-modal-title').html(title);
if (value1) $value1.val(value1);
if (value2) $value2.val(value2);
if (labelIndex !== 'undefined' && labelIndex > -1) $workoutModal.data('crurent-label-index', labelIndex);
else $workoutModal.data('crurent-label-index', -1);
$workoutModal.modal({
show: true
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<style>
.workout-label {
padding: 6px;
font-size: 16px;
width: 100%;
display: block;
margin-bottom: 5px;
cursor: pointer;
}
.remove-workout {
cursor: pointer;
}
#too-many{
display:none;
}
</style>
<br>
<br>
<div class="container well" id="workout-container">
<div class="row">
<div class="col-xs-6">
<div id="workout-datepicker"></div>
</div>
<div class="col-xs-6" id="workout-labels-container">
</div>
</div>
<div class="alert alert-danger" id="too-many" role="alert">Maximun reached</div>
</div>
<div id="workout-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="workout-modal-title"></h3>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="firstname" class="col-sm-4 control-label">Some short text:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="modal-workout-value-1" placeholder="">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-4 control-label">Some longer text:</label>
<div class="col-sm-8">
<textarea class="form-control" id="modal-workout-value-2" name="textarea"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="button" class="btn btn-primary" id="add-workout">Add workout</button>
</div>
</form>
</div>
</div>
</div>

How can I avoid an undesired URL address change after a form submission?

I am working on a bootsrap3 template, which is Ajax based.
My index file has a leftside menu and a conent block middle of the page, every time I click on a subelement of this left menu, an Ajax laod will put the page content in this block(ajax-content).*
Any time I call any page, my URL normally looks something like this /index.php#page-one.php, except when the page contains form submission.
The Problem happens when I add an action attribute (acion="page-one.php") to my form tag.
After the form submission my URL turns to /page-one.php ;
consequently I get a white page containing the page-one.php elements whitout any CSS styling and of course no index-file's elements.
What is the correct and best way to come a cross this issue?
index.php:
<body>
<!--Start Container-->
<div id="main" class="container-fluid">
<div class="row">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li class="dropdown">
<a id="configuration" href="#" class="dropdown-toggle">
<i class="fa fa-gears"></i>
<span class="hidden-xs">Menu-element</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="page-one.php">Menu-Subelement-one</a></li>
<li><a class="ajax-link" href="page-wo.php">Menu-Subelement-two</a></li>
</ul>
</li>
</ul> <!-- end of main-menu-->
</div>
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img.gif" class="loader" alt="preloader"/>
</div>
<!--inside this div a short description/introduction(simple text inside a <p> tag) about the Menu-element will be shown-->
<div id="content-header"></div>
<!--inside this div the page content of the Menu-subelement will be shown-->
<div id="ajax-content"></div>
</div>
<!--End Content-->
</div>
</div>
<!--End Container-->
<script src="plugins/jquery/jquery-2.1.0.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugin/jquery.form.js"></script>
<script src="js/script.js"></script>
And here is my script.js:
//
// Function for load content from url and put in $('.ajax-content') block
//
function LoadAjaxContent(url){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: url,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
//////////////////////////////////////////////////////
document.ready
//////////////////////////////////////////////////////
$(document).ready(function () {
var ajax_url = location.hash.replace(/^#/, '');
if (ajax_url.length < 1) {
ajax_url = 'home.php';
}
LoadAjaxContent(ajax_url);
$('.main-menu').on('click', 'a', function (e) {
var parents = $(this).parents('li');
var li = $(this).closest('li.dropdown');
var another_items = $('.main-menu li').not(parents);
another_items.find('a').removeClass('active');
another_items.find('a').removeClass('active-parent');
if ($(this).hasClass('dropdown-toggle') || $(this).closest('li').find('ul').length == 0) {
$(this).addClass('active-parent');
var current = $(this).next();
if (current.is(':visible')) {
li.find("ul.dropdown-menu").slideUp('fast');
li.find("ul.dropdown-menu a").removeClass('active')
}
else {
another_items.find("ul.dropdown-menu").slideUp('fast');
current.slideDown('fast');
}
}
else {
if (li.find('a.dropdown-toggle').hasClass('active-parent')) {
var pre = $(this).closest('ul.dropdown-menu');
pre.find("li.dropdown").not($(this).closest('li')).find('ul.dropdown-menu').slideUp('fast');
}
}
if ($(this).hasClass('active') == false) {
$(this).parents("ul.dropdown-menu").find('a').removeClass('active');
$(this).addClass('active')
}
if ($(this).hasClass('ajax-link')) {
e.preventDefault();
if ($(this).hasClass('add-full')) {
$('#content').addClass('full-content');
}
else {
$('#content').removeClass('full-content');
}
var url = $(this).attr('href');
window.location.hash = url;
LoadAjaxContent(url);
}
if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
$('#formSubmit').ajaxForm();
});
page-one.php:
<!--some php code here-->
<form class="validateForm" id="formSubmit" action="page-one.php" method="get">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" />
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="submit" class="btn btn-primary btn-label-left">
<span><i class="fa fa-save"></i> Save</span>
</button>
</div>
</div>
</form>
Thanks!
I had the same issue to solve for the intranet I work on.
For me, the good way to do this is to avoid using submit method and use instead an input button with a js function to send the form data.
In my case, I did this:
<!-- At the top of my webpage -->
<script language='Javascript'>
function loadingAjax(div_id,user,date1,date2)
{
$("#"+div_id).html('<br><center><img src="images/loading.gif"><br><br><font color="#006699" face="arial" size="4"><b>Loading data<br>VPlease wait ...</b></font></center>');
$.ajax({
type: "POST",
url: "activities.php?USER="+user+"&DATE1="+date1+"&DATE2="+date2,
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<!-- And here is my form -->
<form id='date_form'>
<input type='text' id='user'><input type='text' id='date1'><input type='text' id='date2'>
<input type='button' onclick="loadingAjax('myDiv',document.getElementById('user').value,document.getElementById('date1').value,document.getElementById('date2').value);">
</form>
This allow to send your form in a separate DIV without having to show to everyone your URL.
MORE: you can even use this function to manage your left side menu selection so that your URL would stay '/index.php' all the time.
Hope this help
Regards
Nico
How do you want to submit the form, using ajax?
If you want to use ajax, you should cancel the default action like you do with your links using e.preventDefault();. Post the javascript that handles the form submit if you need help with that.
If you want to post to page-one.php without using ajax, you could add a header() redirect after the php code that processes the form to redirect to the page that you would like to show after the form gets submitted.
As you are loading content by ajax,
You can post content to page-one.php and redirect user to it's previous page. But it will be difficult manage and show error, success, notification message like form validation errors etc.
Another and I think best solution is to use ajax form submission

bootstrap popover form ( ajax)

I am in the middle of implementing a feature.
objective :
to have a popover form with ajax request .
bootstrap popover
NOTE : previously i tried to achive the same with the bootstrap editables
but due to the fact that I don't want data(entered in popover) to be shown on page . (which editables are for) .
So ,
with current method (jsfiddle)
ISSUE :
when I am clicking on the popover to enter data inside the from popover disappears.
i am searching for a jquery fix . ( something with event propagation will do )
my code :
<div class="box-icon" >
<div class="popover-markup">
<i class="icon-plus-sign"></i>
<div class="head hide">Enter Email<i class="icon-remove" style="margin-left: 120px;"></i></div>
<div class="content hide">
<input type="text" placeholder="Type email address">
<button type="submit" class="btn">Submit</button>
</div>
<div class="footer hide">test</div>
</div>
</div>
and my scripts are :
$( document ).ready(function() {
$('.popover-markup > .trigger').popover({
html : true,
title: function() {
return $(this).parent().find('.head').html();
},
content: function() {
return $(this).parent().find('.content').html();
}
});
// Attach click handler to document
$(document).bind('click', function (e) {
$(".popover-markup").popover('hide');
});
// Dont hide when I click anything inside #container
$('.popover-markup').bind('click', function(e) {
e.stopPropagation();
});
});

Categories