I am trying to load a htm to a div in another htm but I keep getting the error below:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Here is my scenario:
First.html (html)
<div id="selectedPage"></div>
First.html (script)
<script>
function loadHTML2Div(htmlPage){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
$("#selectedPage").html(xmlHttp.responseText);
}
};
xmlHttp.open("GET", htmlPage, true); // true for asynchronous
xmlHttp.send(null);
}
$(document).ready(function(){
loadHTML2Div("Second.htm");
});
</script>
Second.htm (html)
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class='jumbotron'>
<span>Verifique as datas disponÃveis e agende seu evento.</span>
</div>
<div data-provide="calendar" id="calendar"></div>
</div>
</div>
</div>
<div class="modal fade" id="preReservaModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="modaldate"></h4>
</div>
<div class="modal-body ">
<div class="form-group">
<label for="exampleInputNome">Nome Completo</label>
<input class="form-control" id="exampleInputNome" placeholder="Digite seu nome completo" type="nome">
<br/>
<label for="exampleInputEmail1">Email</label>
<input class="form-control" id="exampleInputEmail1" placeholder="Digite seu email" type="email">
<br/>
<label for="exampleInputTelefone">Telefone para contato</label>
<input class="form-control" id="exampleInputTelefone" placeholder="Digite seu telefone para contato" type="telefone">
<br/>
<label for="exampleInputPlano">Pacote</label>
<select class="input-large form-control">
<option value="" selected="selected">Selecione um pacote</option>
<option value="DI" >Diamante</option>
<option value="ES">Esmeralda</option>
<option value="RU">Rubi</option>
</select>
</div>
</div>
<div class="modal-footer">
Fechar
Confirmar
</div>
</div>
</div>
</div>
<script src='bootstrap/js/bootstrap-combobox.js'></script>
<script src="bootstrap/js/bootstrap-year-calendar.js"></script>
</body>
I also have a navbar-nav from bootstrap on top of my First.htm for the navigation, and I also have a Third.htm and Fourth.htm that can be opened when the navbar is clicked. I use loadHTML2Div for switching between the contents of the . I don't know if this is the best approach.
As far as I searched this Synchronous XMLHttpRequest error, I would fix it by using ajax async call. I tried using xmlHttpRequest as mentioned above and I also tried using .ajax async
function loadHTML2Div(htmlPage){
$.ajax({
async: true,
type: "GET",
url: htmlPage,
success: function(data){
$("#selectedPage").html(data);
}
});
}
But I got the same error.
Please advise me how can I avoid this sync error. As you can see I tried different ways before elaborating this question.
If you need more information please let me know.
Edited
I kept testing and I fixed this error in some htmls. The problem was I was adding the Jquery and the bootstrap js in both First and Third html for example.
I removed the script declaration from the third.htm for example and left only the declaration in the 'upper' html (First.html). So somehow declaring it on both files was causing me the error.
Unfortunatelly, I still have a problem with the Second.htm which I copied to this question. This htm has a calendar and a bootstrap combobox. If I delete them from the Second.htm and write them in the First.htm, it doesn't work.
<script src='bootstrap/js/bootstrap-combobox.js'></script>
<script src="bootstrap/js/bootstrap-year-calendar.js"></script>
I also have some scripts for the clickDay and setMinDate in the Second.htm as shown below which fail if I remove the scripts declaration and move it to the upper First.htm.
$('#calendar').data('calendar').setMinDate(todayDt);
So it seems to me my lack of knowledge is leading me to this problem. It is probably very simple to solve it, if someone could help me i will appreciate.
set your the ajax attribute async to false
$.ajax({
async: false,
type: "GET",
url: htmlPage,
success: function(data){
$("#selectedPage").html(data);
}
});
I finally figured out what the problem was.
I moved the scripts declaration from Second.htm to First.htm
<script src='bootstrap/js/bootstrap-combobox.js'></script>
<script src="bootstrap/js/bootstrap-year-calendar.js"></script>
Then I changed my html from
<div data-provide="calendar" id="calendar"></div>
to
<div id="calendar"></div>
and created the calendar in the ready function
<script>
$( document ).ready(function() {
$('#calendar').calendar();
});
</script>
As I am a newbie in web development, I know this is still not the best way to structure my website navigation using navbar from bootstrap. For now I will leave this way.
My goal is to have my first htm with the navbar and the contents from each navbar item in different htms (as I have now), but I want the url to change as I click each item:
www.mywebsite.com/First.htm
www.mywebsite.com/Second.htm
www.mywebsite.com/Third.htm
And right now I only have
www.mywebsite.com/First.htm
Where all my scripts are included in the First.htm. It means I am loading the calendar.js even if I don't open the calendars page.
Well, I hope I will help someone with my question/answer in the future even though it is a little confusing. I promise next time I will have more knowledge.
Related
When I click on continue button it checks clients ID in firestore database and if ID does'nt exist then $scope.filePath = "createClient.htm" is called. everything is working fine but when I call this piece of code inside firebase function nothing happens
Inside HTML
<div ng-include="filePath" class="ng-scope">
<div class="offset-1 offset-sm-2 col-11 col-sm-7">
<h2>Enter Client ID</h2>
<br>
<div class="form-group">
<label for="exampleInputEmail1">ID</label>
<input id="client_id" type="text" class="form-control" placeholder="Client ID">
</div>
<div class="float-right">
<button type="button" class="btn btn-danger">Cancel</button>
<button type="button" ng-click="searchClient()" class="btn btn-success">Continue</button>
</div>
</div>
</div>
Internal Script
<script>
$scope.searchClient = function()
{
//$scope.filePath = "createClient.htm"; it works here
var id= document.getElementById('client_id').value;
db.collection("clients") // db is firestore reference
.where("c_id","==",id)
.get()
.then(function(querySnapshot)
{
querySnapshot.forEach(function(doc)
{
if(!doc.exists)
{
console.log("Client Does'nt Exist");
$scope.filePath = "createClient.htm"; // but doesnt works here inside this firebase function
}
}
);
}
);
}
};
</script>
when console.log is shown and firebase function are fully executed then if I click on "Continue" Button again it works fine and content of createClient.htm is shown inside ng-include="filePath". why i need to click twice ?
some friends and I have started a team project but we are stuck at this point. We made a function of the site to add comments under every post. The problem is that when submit is clicked it adds the comment but doesn't refresh the page which causes some problems. The author stays "anonymous" and when refresh button is clicked it shows an alert:
The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you wish to continue?
However, if we just type the URL again and click ENTER everything is good: the author shows up and the comment appears only once. So the only solution for us is to redirect to the same page. Here is the form:
<div style="text-align: left">
<div><i>Leave your comment</i>
</div>
<form method="post">
<fieldset>
<p>
<textarea rows="10" class="form-control" type="text" id="1" name="commentText" style="height: 100px"></textarea>
</p>
<p>
<input type="submit" name="buttonSubmit" onclick="redirect" value="Add comment" class="btn btn-default" style="" />
</p>
</fieldset>
</form>
</div>
This is how the comments are printed on the page:
<h3>Comments</h3>
<br>
<div>
#foreach (var comment in ViewBag.Comments) {
<section class="row">
<article class="post col-md-12">
<div class="about">
Posted on <i>#comment.Date</i>
#if (comment.AuthorId != null) { #: by <i>#comment.Author.FullName</i>
}else { #: by <i>anonymous</i>
}
</div>
<div class="body">#comment.Text</div>
</article>
</section>
}
</div>
Thanks in advance!
Use the #Ajax.BeginForm() helper.
In the AjaxOptions(), you'll want to set the Httpmethod to "Post", InsertionMode.InsertBefore (or After depending on where you want new comments), and UpdateTargetId = "your-comment-div".
You'll need to include jquery.unobtrusive-ajax.js so the Ajax helper works correctly. You can use the nuget package manager to pull it in. Be sure to add it to your jquery bundle.
Then, you need to create the post action in your controller to accept the comment params and return a partial view.
Doing thIs keeps the Ajax confined to a razor helper and controller method.
View:
#using (Ajax.BeginForm("AjaxAddComment",
"MyController",
/* route params */,
new AjaxOptions()
{
InsertionMode = InsertionMode.InsertBefore,
UpdateTargetId = "commentsDiv",
HttpMethod = "Post"
}, htmlAttributes: new { /* ... */ }))
{
<div class="form-horizontal">
#* comment form... *#
</div>
}
...
<div id="commentsDiv">
<div class="comment">...</div>
<div class="comment">...</div>
</div>
Controller:
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<PartialView> AjaxAddComment(string comment, /*...other params*/)
{
var newComment = ... // comment viewModel
// add comment to db
await db.SaveChangesAsync();
return PartialView("_CommentPartial", newComment);
}
_CommentPartial:
<div class="comment">
...
</div>
I'm fairly new to Angular and very new to using the ui-router, so I could be missing something obvious.
If I launch my results.html page on its own, everything from the Web API is bound correctly through the controller and shows up as expected.
When I start from index.html and click on the button that calls $state.go(), I am navigated to the results.html page .. but none of the data from the controller shows up. The controller & service are still being called though - because I put console.log() statements to verify that the object I want is being returned after $state.go() and it is - the template just isn't registering it.
Here is my code for my ui-router and main controller:
// script.js
var app = angular.module('BN', ['ui.router']);
// configure our routes
app.config(function ($locationProvider, $stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('');
$stateProvider
.state('default',{
url:'/',
templateURL:'index.html',
controller: 'MainController'
})
.state('results', {
url:'/results',
controller: 'ResultsController',
controllerAs: 'vm',
templateUrl: 'Results/Results.html'
})
.state('instructor', {
url:'/api/instructors/:id',
templateUrl: 'Instructors/Instructor.html'
});
$locationProvider.html5Mode(true);
});
app.controller('MainController', MainController);
function MainController ($state) {
var vm = this;
vm.Submit=function( ){
$state.go('results');
};
}
So Results.html renders perfectly fine launched on it's own, but when navigated to - the controller is called but not bound to the html template.
You have your index.html file set up properly, but after that you're using ui-router incorrectly.
In your index.html file where you have:
<body ui-view>
this tells ui-router to load the contents of your templates into the body of your document, so your templates should just be snippets of html to be rendered within your body tag. So you should delete everything from results.html until all that remains is this:
<div id="headerBar" >
<div class="form-group" id="headerBar" >
<input class="form-control input-lg" type="text" id="inputlg" placeholder="Zipcode" />
<button id="sub" class="btn btn-default btn-lg" type="submit" ng-click="vm.getInstructors()">Find an Instructor!</button>
</div>
</div>
<table>
<tr ng-repeat="Instructors in vm.instructors">
<td style="padding-top:5px;">
<div>
<nav class="navbar">
<div class="container-fluid">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="searchString" >
</div>
<button type="submit" class="btn btn-default" value="Filter">Search</button>
</form>
</div><!-- /.container-fluid -->
</nav>
</div>
</td>
</tr>
</table>
<div class="col-md-8">
</div>
<aside class="sidebar" ui-view="map">MAP</aside>
A few other things. You have the controller setup in your routes, so you don't need to specify it anywhere in results.html. Also you should not be able to navigate to results.html. Instead you would just navigate to (your domain)/results.
I am trying to clone elements when clicking a button. I was trying to use ko.toJS. On page load it works fine, but when I want clone the items, it is unable to bind the items (like, value, Text, etc.).
Here is the HTML:
<div class="stockItems-inner" data-bind="foreach: StockItems">
<div data-bind="if: Type=='Input'">
<div class="stock_container_input">
<input type="text" data-bind="value: Value" />
</div>
</div>
<div data-bind="if: Type=='Radio'">
<div class="stock_container_control">
<div data-bind="foreach: Options">
<div class="stockLbl">
<input type="radio" data-bind="text: Text, checked:$parent.Value, attr:{'id':Id, 'name': $parent.Text, 'value': Value}" />
<label data-bind="attr:{'for':Id}, text: Text"></label>
</div>
</div>
</div>
</div>
</div>
<div class="addItem">
<button type="button" data-bind="click: CloneItem"><img src="images/add.png" alt="" /></button>
</div>
The View Model:
ConfigurationStockViewModel = function() {
var self = this;
this.StockItems = ko.observableArray();
this.ApplyData = function(data){
self.StockItems(data.Items);
}
this.CloneItem = function(StockItems){
self.StockItems.push(ko.toJS(StockItems));
};
};
When clicking the button, an error is thrown: Unable to process binding. I am using JSON data for binding.
Not exactly sure what end result you want without working code, but sounds like you want to clone the last item in array and add to array?
If so, I think you have an error - your add button click binding will never pass anything to the function you defined, since it is outside the foreach. You need something like this:
this.CloneItem = function() {
var toClone = self.StockItems()[self.StockItems().length - 1]
self.StockItems.push(toClone);
};
Here is a simplified example without radio buttons, etc:
http://jsfiddle.net/5J47L/
Using PhoneGap...
I would like to find a way to prevent the navigation for data-role='page', if the user has no network connection. I'm having a hard time finding any resources for this, am a few hours deep on google searching, although I could be using the wrong terms.
I want the user to only be able to navigate here if there is network connection:
<div data-role="page" id="Location">
<div data-role="header" data-theme="e">
Incid..
<h1>
Location</h1>
Use Current
</div>
<!-- /header -->
<div data-role="content">
<!--<div id="panel">
<input id="target" type="text" placeholder="Search Box">
</div>-->
<div id="map_canvas">
</div>
</div>
Using this jQuery for pageshow:
$('#Location').live('pageshow', function (event, ui) {
try {
display();
}
catch (e) {
log(e);
alert(e);
}
});
I know I should be able to catch the network status using if(navigator.network.connection.type == 'none'), but I'm having difficulty stopping the Location page from showing.
Use $.mobile.changePage('#pageID') to change the page depending on if the user has a network connection or not.