I'm working with Flickr's API. I am asynchronously loading some images and related metadata. I have a script where I do all this, using three AJAX calls:
$(document).ready(function() {
var latLon = {
lat: 38.736946,
lng: -9.142685
};
var numero = 10;
var clicked = 1;
$("#sq").click(function() {
clicked = 1;
});
$("#lg-sq").click(function() {
clicked = 2;
});
$("#thumb").click(function() {
clicked = 3;
});
$("#small").click(function() {
clicked = 4;
});
$("#mid").click(function() {
clicked = 5;
});
$("#apagar").click(function() {
$("#results").html('');
});
$('#pesquisar').click(function() {
$("#results").html('');
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search',
dataType: 'xml',
data: {
api_key: '2fd41b49fedfd589dc265350521ab539',
tags: $("#tag").val(),
format: 'rest'
},
success: sucessHandler,
error: errorHandler
});
function sucessHandler(data) {
$("#results").html('');
var fotos = Array.prototype.slice.call($(data).find("photo"));
if ($("#numero").val() != "") {
numero = parseInt($("#numero").val());
console.log("entrou");
}
fotos.forEach(function(foto, key) {
if (key < numero) {
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes',
dataType: 'xml',
data: {
api_key: '2fd41b49fedfd589dc265350521ab539',
photo_id: $(foto).attr('id'),
format: 'rest'
},
success: function(dataSize) {
var farmId = $(foto).attr('farm');
var serverId = $(foto).attr('server');
var Id = $(foto).attr('id');
var secret = $(foto).attr('secret');
var src = "https://farm" + farmId + ".staticflickr.com/" + serverId + "/" + Id + "_" + secret + ".jpg";
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.getInfo',
dataType: 'xml',
data: {
api_key: '2fd41b49fedfd589dc265350521ab539',
photo_id: $(foto).attr('id'),
format: 'rest',
secret: secret
},
success: function(dataInfo) {
for (var i = 1; i < 6; i++) {
if (clicked == i) {
var size = dataSize.getElementsByTagName('size')[i - 1];
var title = dataInfo.getElementsByTagName('title')[0].textContent;
var owner = $(dataInfo.getElementsByTagName('owner')[0]).attr('username');
var date = $(dataInfo.getElementsByTagName('dates')[0]).attr('taken');
var local = $(dataInfo.getElementsByTagName('owner')[0]).attr('location');
if (local == "") {
local = "desconhecido";
}
var tags = $(dataInfo.getElementsByTagName('tag'));
var allTags = "";
var width = $(size).attr("width");
var height = $(size).attr("height");
var htmlText = "<div class='col-md-12 jumbotron style='display:inline-block;vertical-align:text-top'><p hidden>" + Id + "</p><img src =" + src + " width=" + width + " height=" + height + "><img class='pull-right' src='icon.png' width=50 height=50/>" +
"<p><b>título: </b>:" + title + "</p>" + "<p><b>autor: </b>" + owner + "</p>" + "<p><b>data: </b>" + date + "</p>" + "<p><b>local: </b>" + local + "</br></br>"
for (var i = 0; i < tags.length; i++) {
htmlText += "<label style='border:1px solid grey;margin-left:10px'>" + $(tags[i]).attr('raw') + "</label>";
}
htmlText += "</div>";
$('#results').append(htmlText);
/*$('#results').append("<div class='col-md-4'><img src ="+src+" width="+width+" height="+height+">");
$('#results').append("<p><b>título: </b>:" + title + "</p>" + "<p><b>autor: </b>" + owner + "</p>" + "<p><b>data: </b>" + date + "</p>" + "<p><b>local: </b>" + local);
$('#results').append("</br>");*/
}
}
},
error: function(req, status, err) {
}
});
},
error: errorSize
});
}
});
function errorSize(req, status, err) {
console.log("error size");
}
}
function errorHandler(req, status, err) {
console.log("fail");
}
});
var map;
function initMap() {
map = new google.maps.Map(
document.getElementById('map'), {
center: latLon,
zoom: 8
}
);
}
});
html
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="FlickrPhotosSearch.js"></script>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style type="text/css">
#sq,
#lg-sq,
#thumb,
#small,
#mid,
#ori {
width: 100%
}
input {
width: 50px;
}
#map{
width:1240;
height:300;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Escolha o tamanho das imagens (em píxeis) que quer visualizar</h2>
</div>
</div>
<div class="row">
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="sq">Square [75X75]</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="lg-sq">Large Square</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="thumb">Thumbnail</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="small">Small</button>
</div>
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="mid">Medium</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h2>Pesquisa de fotos</h2>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<input type="text" class="form-control" id="tag">
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-success" id="pesquisar">Pesquisar</button>
</div>
<div class="col-lg-1">
<button type="button" class="btn btn-alert" id="apagar">Apagar</button>
</div>
<div class="col-lg-2">
<input type="text" id="numero" class="form-control" placeholder="numero de fotos">
</div>
</div>
<hr>
<div id="map"></div>
<div class="row" id="results" style="margin-top:100px;margin-left:50px">
</div>
</div>
<script src="googleapi.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAKKKmlp2uHM78D9NMhhzY-lVQmzI81Z_E&callback=initMap" async defer></script>
</body>
</html>
second script
$(document.ready(function(){
var map;
var latLon = {lat:38.736946,lng:-9.142685};
function initMap() {
map = new google.maps.Map(
document.getElementById('map'),
{
center: latLon,
zoom: 8
}
);
}
});
I coded a call to an initMap function on the bottom, but when I try to invoke it, I get the error:
initMap is not a function
I need to make this function available so I can make another AJAX call with the previously-described data. How can I do that?
You need to move initMap() function outside the $(document).ready() function. This method of initializing google maps requires that initMap is accessible globally.
initMap() has to be outside any other function, right inside <script> tag.
$(document).ready(function() {
// all your other stuff
});
var map;
var latLon = {lat:38.736946,lng:-9.142685};
function initMap() {
map = new google.maps.Map(
document.getElementById('map'),
{
center: latLon,
zoom: 8
}
);
}
Related
My default start page has no data
Then filter out the data in the database after the two drop-down list
I hope that the filtered data can be displayed in pagination if there are more than ten records.
But I don't know how to do.
I'm new in this.
Here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
})
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('select'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('select'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedCity = $('#CITY option:selected').val();
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '#Url.Action("Getmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Mytable>tbody').empty();
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>'>+</td><td>' + data[i].ID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Address + '</td><td>' + data[i].Phone + '</td><td>' +'</td></tr>');
$('#Mytable>tbody').append(row);
}
$('#Mytable').show(); //show filter data
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
my dropdownlist is use js to connection
filter data also
that's means after user selected city and area
data will be displayed
here is my html:
<form>
<div class="row well">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">City</span>
<p>
#Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "Please select", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">Area</span>
<p> <select id="AREA" name="AREA"><option>Please select</option></select></p>
</div>
</div>
<div class="col-lg-2">
<button type="button" onclick="SearchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>search
</button>
</div>
</div>
<table id="Mytable" class="table table-bordered table-hover" style="display:none;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
//first page table will not show any data so is null
</tbody>
and my controller
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
string q = "Select * from Shopmap";
SqlDataAdapter da = new SqlDataAdapter(q, con);
da.Fill(dt);
}
return View(dt);
}
//js for first selected dropdownlist
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
//js for selected second dropdownlist then search data
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)
{
var b = new GetCollection();
List<Inserch> shop = b.GetDBdata();
var a = shop.FindAll(x => x.Address.Contains(cityName));
var Alldata = a.FindAll(x => x.Address.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Alldata);
}
I think it will use js to do what I want
then maybe c# code will put in
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)->this function
please tell me what to do
I desperately need.
thank's.
Pagination for Dropdownlist filter data in ASP.NET MVC
You can achieve that in following way:
HTML
<table id="userTable_info">
<thead>
<tr>
<th>Id </th>
<th>Controller </th>
<th>Page_name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
Script:
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#userTable_info').hide();
//On Submit Method
$("#Submit").click(function () {
var ddlCategory = parseInt($("#ddlCategory").val());
var ddlSubCategorie = parseInt($("#ddlSubCategorie").val());
$.ajax({
type: "POST",
url: 'http://localhost:5094/Member/GetShopmap',
dataType: "json",
data: { cityName: ddlCategory, areaName: ddlSubCategorie },
success: function (response) {
console.log(response);
$.each(response, function (index, value) {
var tr = "<tr>";
tr += "<td>" + value.ulogo_id + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.page_name + "</td>";
tr += "<td>" + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
$('#userTable_info').show();
}
});
});
});
</script>
}
Output:
Note: Based on your table defination please implement the neccessary chnages. It ill work as expected.
I have a SharePoint custom FAQ List (columns: Questions, Answers, Category).
I want to filter this FAQ based on the user selecting the category in the front-end (A UI something like this should work for me: JSFiddle)
UPDATE:
I have used the above JS Fiddle code into my code in the SharePoint "Modern Script editor web part".
Here, the FAQ is showing only the last record from the SharePoint List.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.0/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.0/js/bootstrap.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#search-filter").on("keyup", function() {
var unicode = event.charCode ? event.charCode : event.keyCode;
if (unicode == 27) {
$(this).val("");
}
var searchKey = $(this).val().toLowerCase();
$('.accord-toggle').each(function() {
var cellText = $(this).text().toLowerCase();
var accordion = $('#accordion panel');
if (cellText.indexOf(searchKey) >= 0) {
$(this).parent().parent().show();
}
else {
$(this).parent().parent().hide();
$('.panel-collapse.in').collapse('hide');
}
}
);
}
);
}
);
</script>
<br/>
<div class="row-fluid text-left">
<span class="clearable">
<input type="text" id="search-filter" placeholder="Type to Search" />
<span class="icon_clear">x
</span>
</span>
</div>
<br/>
<script type="text/javascript">
$(document).ready(function(){
GetItems();
$(".collapse")
.on('show.bs.collapse', function(){
alert("ss");
$(this).siblings(".card-header").find(".fa").removeClass("fa-plus").addClass("fa-minus");
}
)
.on('hide.bs.collapse', function(){
alert("aa");
$(this).siblings(".card-header").find(".fa").removeClass("fa-minus").addClass("fa-plus");
}
);
}
);
function GetItems(){
var siteURL = _spPageContextInfo.webServerRelativeUrl;
$.ajax({
url: siteURL + "/_api/web/lists/GetByTitle('EPTFAQ')/items", //change the list name
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
,
success: function(data) {
if (data.d.results.length > 0 )
{
$('#accordion').append(GenerateAccordionFromJson(data.d.results));
console.log(data.d.results);
}
else{
$('#accordion').append("<span>No Records Found.</span>");
}
}
,
error: function(error){
alert(JSON.stringify(error));
}
}
);
}
function GenerateAccordionFromJson(objArray) {
var accordionContent = "";
for (var i = 0; i < objArray.length; i++) {
var varHref= "#collapse"+i
var varBodyId = "collapse"+i
accordionContent ='<div class="panel-group" id="accord">' +
'<div class="panel panel-default">' +
'<div class="panel-heading">' +
'<h4 class="panel-title">' +
'<a class="accord-toggle" data-toggle="collapse" href='+varHref+'>' +
'<span class="glyphicon glyphicon-bed">'+objArray[i].Title+'<span class="badge">1</span></span>' +
'</a>' +
'</h4>' +'</div>' +
'<div id='+varBodyId+' class="panel-collapse collapse" data-parent="#accordion">' +
' <div class="panel-body">' +
'<div class="list-group">' +
' <div type="button" class="list-group-item">'+objArray[i].Answer+'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
' </div>';
}
console.log(accordionContent);
return accordionContent;
}
</script>
</head>
<body>
<div class="container">
<div id="accordion">
</div>
</div>
</body>
OUTPUT:
SharePoint List view:
Resulting Output with Error:
Expected Output:
Should show all the 3 Lists and I should be able to filter the results (like in the JS Fiddle example).
In the function GenerateAccordionFromJson, this line
change to accordionContent = accordionContent +'<div class="panel-group" id="accord">' + ....
Today I was working to script, when I wanted to test it, I could see that it didn't works correctly it show the value [object Object] and not the real value (It didn't change the value too). It shows: Click here for see the picture
Its necessary click on "Edit" near of Google or Yahoo. I want to show the correct value when I click "Edit" near Google and Edit it when I click edit. I tried to change the value Checked[Item] for Checker[Name] but it only shows undefined.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.Checker.splice(item, 1, name.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
json:
var Checker = [{
name:"Google",
url: "google.es",
},
{
name:"Yahoo",
url: "yahoo.com",
}
]
Add another input tag for each attribute of Checkers objects.
<input type="text" id="edit-name">
<input type="text" id="edit-url">
And set each input separately
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
Working code:
var Checker = [{
name: "Google",
url: "google.es",
},
{
name: "Yahoo",
url: "yahoo.com",
}
]
document.getElementById('edit').style.display = 'none';
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el2.value;
var name = el.value;
if (url && name) {
Checker[item].name = name;
Checker[item].url = url;
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
<html>
<head>
<title>SSL Checker</title>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-url">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
You are getting correct output with [object Object], because Object.toString() returns exactly [object Object].
To represent your object in a custom format you can change the part of your SSL.Edit() method where you do el.value = Checker[item] to something like
el.value = Checker[item].name; // To show the name
el.value = Checker[item].url; // To show the url
el.value = Checker[item].url + ' ' + Checker[item].url; // To show both
I'm making a chat application using SignalR API. I'm getting error as:
0x800a138f - JavaScript runtime error: Unable to get property 'client'
of undefined or null reference
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="/Css/ChatStyle.css" />
<link rel="stylesheet" href="/Css/JQueryUI/themes/base/jquery.ui.all.css">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/ui/jquery.ui.core.js"></script>
<script src="/Scripts/ui/jquery.ui.widget.js"></script>
<script src="/Scripts/ui/jquery.ui.mouse.js"></script>
<script src="/Scripts/ui/jquery.ui.draggable.js"></script>
<script src="/Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
$("#divLogin").show();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
</head>
<body>
<div id="header">
SignalR Chat Room
</div>
<br />
<br />
<br />
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
</body>
</html>
You are referring to the client object of an undefined object. So I have been searching inside your code for
.client
These were the results:
chatHub.client.onConnected
chatHub.client.onNewUserConnected
chatHub.client.onUserDisconnected
chatHub.client.messageReceived
chatHub.client.sendPrivateMessage
So, if you look at the results, it becomes obvious that chatHub is undefined somewhere. This is how you initialize it:
var chatHub = $.connection.chatHub;
I wonder what is inside $.connection. Are you missing a script from your html?
A couple of things...
You're using an old signalr version, have you tried upgrading to the latest?
Otherwise; I had a similar problem, I had to solve it by setting up the connection without the generated proxy (/signalr/hubs).
See this link http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client and instead of setting it as a "generated proxy", implement it without it. (Search for "Without the generated proxy")
So, like the title says I'm trying to figure out how to define a modal dialog that will update or create customers. And then I can show it on the orders page or other pages simply by calling it...
I'm new to JavaScript but not to programming. In windows app I would create a class that I could call and show to the user but I'm not sure how to do that in js.
I've figured out how to use the modal dialog with a div and with an iframe but making it usable on multiple pages is eluding me.
Please help,
Thanks,
Dave
Edit: I don't want to use an iframe since I would like yo be able to access fields both ways from the page to the dialog and back again.
Edit 2:
So (remember im new to this)... I created the main page (default.aspx) and a customer page (customer.html) and a customer single instance module (customer.js).
From default.aspx I load up the customer module, add an event handler for the "loaded" custom event i created, and it works, loads the data in the form. Then I open the customer dialog, it works, dialog loads its own data from the customer module, however, when i click the save button in the dialog, the data is saved properly but the customer module after saving fires a "datasaved" event and its not getting caught on default.aspx...
can you see anything wrong with this?? this web site was picky as to what i can paste in here so let me know if something got missed...
default.aspx
<script type="text/javascript">
var customer;
var customerDialog;
function showCustomerPopup(closedCallback) {
var width = $(window).innerWidth;
if (width > 420)
width = 420;
$('#divCustomerPopup').remove();
$("body").append("<div id='divCustomerPopup' style='display: none;'></div>");
var divPopup = $("#divCustomerPopup");
$.get("templates/customer.html", function (data) {
divPopup.html(data);
});
customerDialog = $("#divCustomerPopup").dialog({
autoOpen: true,
height: 300,
width: width,
modal: true,
});
}
$(function () {
var custIDField = $("#CustomerID");
customer = Customer.getInstance();
if ($.isNumeric(custIDField.val())) {
customer.load(custIDField.val());
} else {
var qID = getParameterByName('customerid');
if ($.isNumeric(qID)) {
customer.load(qID);
} else {
customer.create();
}
}
$('#CustomerName').on('change', function () {
showCustomerPopup();
});
$("#customer-form").on("submit", function (e) {
e.preventDefault();
addCustomer();
});
$(customer).on("dataloaded", function (e, data) {
console.log("dataloaded");
custIDField.val(data.CustomerID);
$('#CustomerName').val(data.CustomerName);
$('#CustomerOnHold').val(data.OnHoldReason);
});
$(customer).on("datasaved", function (e, data) {
console.log("datasaved");
custIDField.val(data.CustomerID);
$('#CustomerName').val(data.CustomerName);
$('#CustomerOnHold').val(data.OnHoldReason);
customerDialog.dialog('close');
});
});
customer.js
<script type="text/javascript">
var Customer = (function () {
var instance;
function init() {
var dr = {};
function FailedCallback(xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.Message != undefined) {
var msg = new String(xhr.responseJSON.Message);
var event = jQuery.Event("ajaxerror")
event.data = msg
$(instance).trigger(event);
if (msg.contains("login") > 0) {
window.location.href = websiteBaseUrl + "login.aspx?from=" + encodeURIComponent(window.location.href);
} else {
}
} else {
alert(xhr.status + ' - ' + thrownError + '\n\n' + xhr.responseText);
}
};
function WebServerCallback(rawresult) {
var data = jQuery.parseJSON(rawresult.d);
dr = data;
var event = jQuery.Event("dataloaded");
jQuery(instance).trigger(event, dr);
if (!event.isDefaultPrevented())
refreshForm();
};
function WebServerSaveCallback(rawresult) {
var data = jQuery.parseJSON(rawresult.d);
dr = data;
var event = jQuery.Event("datasaved");
jQuery(instance).trigger(event, dr);
if (!event.isDefaultPrevented()) {
refreshForm();
}
};
function NewCustomer() {
WebServerCall("GetCustomerData", WebServerCallback, FailedCallback, "{'CustomerID':'-1'}")
};
function LoadCustomer(CustomerID) {
WebServerCall("GetCustomerData", WebServerCallback, FailedCallback, "{'CustomerID':'" + CustomerID + "'}")
};
function refreshForm() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
$('#customer-CustomerID').val(dr.CustomerID);
$('#customer-CustomerName').val(dr.CustomerName);
$('#customer-CustomerSince').val(new Date(dr.CustomerSince).toDateInputValue());
checkBoxCheck($('#customer-VIP'), dr.VIP);
checkBoxCheck($('#customer-OnHold'), dr.OnHold);
checkBoxCheck($('#customer-Tax1Exempt'), dr.Tax1Exempt);
checkBoxCheck($('#customer-Tax2Exempt'), dr.Tax2Exempt);
$('#customer-OnHoldReason').val(dr.OnHoldReason);
$('#customer-PrimaryContactID').val(dr.PrimaryContactID);
$('#customer-DefaultEmployeeID').val(dr.DefaultEmployeeID);
$('#customer-Phone1').val(dr.Phone1);
$('#customer-Phone2').val(dr.Phone2);
$('#customer-Address1').val(dr.Address1);
$('#customer-Address2').val(dr.Address2);
$('#customer-Address3').val(dr.Address3);
$('#customer-City').val(dr.City);
$('#customer-Province').val(dr.Province);
$('#customer-Country').val(dr.Country);
$('#customer-PostalCode').val(dr.PostalCode);
$('#customer-Description').val(dr.Description);
};
function refreshDR() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
dr.CustomerID = $('#customer-CustomerID').val();
dr.CustomerName = $('#customer-CustomerName').val();
dr.CustomerSince = new Date($('#customer-CustomerSince').val());
dr.VIP = checkBoxCheck($('#customer-VIP'));
dr.OnHold = checkBoxCheck($('#customer-OnHold'));
dr.Tax1Exempt = checkBoxCheck($('#customer-Tax1Exempt'));
dr.Tax2Exempt = checkBoxCheck($('#customer-Tax2Exempt'));
dr.OnHoldReason = $('#customer-OnHoldReason').val();
dr.PrimaryContactID = $('#customer-PrimaryContactID').val();
dr.DefaultEmployeeID = $('#customer-DefaultEmployeeID').val();
dr.Phone1 = $('#customer-Phone1').val();
dr.Phone2 = $('#customer-Phone2').val();
dr.Address1 = $('#customer-Address1').val();
dr.Address2 = $('#customer-Address2').val();
dr.Address3 = $('#customer-Address3').val();
dr.City = $('#customer-City').val();
dr.Province = $('#customer-Province').val();
dr.Country = $('#customer-Country').val();
dr.PostalCode = $('#customer-PostalCode').val();
dr.Description = $('#customer-Description').val();
};
function SaveCustomer() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
var data = "{'CustomerID':'" + $("#customer-CustomerID").val() + "','json':'" + JSON.stringify(dr) + "'}";
WebServerCall("UpdateCustomerData", WebServerSaveCallback, FailedCallback, data)
};
return {
datarow: function () { return dr; },
create: NewCustomer,
load: LoadCustomer,
save: SaveCustomer,
loadData: refreshDR,
loadForm: refreshForm
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
hasInstance: function () {
return (instance);
}
};
})();
Customer.html
<div class="ui-corner-all fieldcontainer">
<div class="ui-corner-all fielddiv">
<label class="ui-corner-all " for="customer-CustomerName">Name:</label>
<input class="ui-corner-all " type="text" id="customer-CustomerName" />
<input type="hidden" id="customer-CustomerID" />
</div>
<div class="ui-corner-all fielddiv">
<label class="ui-corner-all " for="customer-CustomerSince">Since:</label>
<input class="ui-corner-all " type="date" id="customer-CustomerSince" />
<input class="ui-corner-all " type="checkbox" id="customer-VIP" title="VIP" />
<label class="ui-corner-all" for="customer-VIP">VIP</label>
</div>
<div class="ui-corner-all fielddiv">
<input class="ui-corner-all " type="checkbox" id="customer-OnHold" title="On Hold" />
<label class="ui-corner-all" for="customer-OnHold">On Hold</label>
<input class="ui-corner-all " type="checkbox" id="customer-Tax1Exempt" title="GST Exempt" />
<label class="ui-corner-all" for="customer-Tax1Exempt">GST Exempt</label>
<input class="ui-corner-all " type="checkbox" id="customer-Tax2Exempt" title="PST Exempt" />
<label class="ui-corner-all" for="customer-Tax2Exempt">PST Exempt</label>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-OnHoldReason">On Hold/Acct:</label>
<textarea class="ui-corner-all " style="vertical-align: middle;" id="customer-OnHoldReason"></textarea>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-PrimaryContactID">Primary Contact:</label>
<select id="customer-PrimaryContactID" class="ui-corner-all "></select>
<input type="button" id="customer-NewContact" class="ui-corner-all " value="New Contact" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-DefaultEmployeeID">Default Employee:</label>
<select id="customer-DefaultEmployeeID" class="ui-corner-all "></select>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Phone1">Phone 1:</label>
<input class="ui-corner-all " type="text" id="customer-Phone1" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Phone2">Phone 2:</label>
<input class="ui-corner-all " type="text" id="customer-Phone2" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Address1">Address 1:</label>
<input class="ui-corner-all " type="text" id="customer-Address1" /><br />
<label class="ui-corner-all " for="customer-Address2">Address 2:</label>
<input class="ui-corner-all " type="text" id="customer-Address2" /><br />
<label class="ui-corner-all " for="customer-Address3">Address 3:</label>
<input class="ui-corner-all " type="text" id="customer-Address3" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-City">City:</label>
<input class="ui-corner-all " type="text" id="customer-City" /><br />
<label class="ui-corner-all " for="customer-Province">Province:</label>
<input class="ui-corner-all " type="text" id="customer-Province" /><br />
<label class="ui-corner-all " for="customer-Country">Country:</label>
<input class="ui-corner-all " type="text" id="customer-Country" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-PostalCode">PostalCode:</label>
<input class="ui-corner-all " type="text" id="customer-PostalCode" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Description">Description:</label>
<textarea class="ui-corner-all " style="vertical-align: middle;" id="customer-Description"></textarea>
</div>
<div style="width: 100%; text-align:center;">
<input class="ui-corner-all " id="customer-Submit" type="submit" value="Create" /> <input class="ui-corner-all " id="customer-Cancel" type="button" value="Cancel" />
</div>
</div>
<script type="text/javascript" src="../common.js"></script>
<script type="text/javascript" src="../Customer.js"></script>
<script type="text/javascript" >
var custIDField = $('#customer-CustomerID');
var customer; // dataloaded, datasaved events passing dr
var employees;
var contacts;
function getEmployeesCallback(rawresult) {
employees = jQuery.parseJSON(rawresult.d);
loadEmployeesDropDown();
};
function loadEmployeesDropDown() {
var ddl = $("#customer-DefaultEmployeeID");
ddl.empty();
$.each(employees, function (i, item) {
var option = $('<option>').val(item.EmployeeID).text(item.EmployeeName);
if (item.EmployeeID == customer.datarow().EmployeeID) {
option.attr('selected', 'selected');
}
option.appendTo(ddl);
});
};
function getContactsCallback(rawresult) {
contacts = jQuery.parseJSON(rawresult.d);
loadContactsDropDown();
};
function loadContactsDropDown() {
var ddl = $("#customer-PrimaryContactID");
ddl.empty();
$.each(contacts, function (i, item) {
var option = $('<option>').val(item.ContactID).text(item.ContactName);
if (item.ContactID == customer.datarow().PrimaryContactID) {
option.attr('selected', 'selected');
}
option.appendTo(ddl);
});
};
$(function () {
customer = Customer.getInstance();
if (customer.datarow().CustomerID == undefined) {
if ($.isNumeric(custIDField.val())) {
customer.load(custIDField.val());
} else {
var qID = getParameterByName('customerid');
if ($.isNumeric(qID)) {
customer.load(qID);
} else {
customer.create();
}
}
}
// customer.loadForm();
$(customer).on("ajaxerror", function (msg) {
//alert("Ajax Error " + msg);
});
$(customer).on("dataloaded", function (e, data) {
customer.loadForm();
//contacts
if (contacts == undefined) {
var withid = -1;
if (customer.datarow().CustomerID != undefined) {
if (customer.datarow().CustomerID > 0) {
withid = customer.datarow().CustomerID;
}
}
if (withid != -1) {
WebServerCall("GetCustomerContacts", getContactsCallback, FailedCallback, "{'CustomerID':'" + customer.datarow().CustomerID + "'}");
} else {
WebServerCall("GetContacts", getContactsCallback, FailedCallback);
}
} else {
loadContactsDropDown();
}
});
$(customer).on("datasaved", function (e, data) {
alert("Customer " + data.CustomerID + " has been saved.");
});
$("#customer-form").on("submit", function (e) {
e.preventDefault();
customer.loadData();
customer.save();
});
$("#customer-Cancel").on("click", function (e) {
e.preventDefault();
customer.load($("#customer-CustomerID").val());
});
//employees
if (employees == undefined) {
WebServerCall("GetEmployees", getEmployeesCallback, FailedCallback);
} else {
loadEmployeesDropDown();
}
});
</script>
</form>
common.js
`var webserviceBaseUrl = '/WebService.asmx/';
var websiteBaseUrl = '/';
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
if (startIndex == undefined)
startIndex = 0;
return ''.indexOf.call(this, str, startIndex) !== -1;
};
}
if (!('contains' in Array.prototype)) {
Array.prototype.contains = function (arr, startIndex) {
if (startIndex == undefined)
startIndex = 0;
return ''.indexOf.call(this, arr, startIndex) !== -1;
};
}
Date.prototype.toDateTimeLocal = (function () {
var now = new Date(this);
var month = (now.getMonth() + 1);
var day = now.getDate();
var hour = now.getHours();
var min = now.getMinutes();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
if (hour < 10)
hour = "0" + hour;
if (min < 10)
min = "0" + min;
var today = now.getFullYear() + '-' + month + '-' + day + 'T' + hour + ':' + min;
return today;
});
Date.prototype.toDateInputValue = (function () {
var now = new Date(this);
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var today = now.getFullYear() + '-' + month + '-' + day;
return today;
});
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function checkBoxCheck(checkBox, checked) {
if(checked){
if (checked == 'true') {
checkBox.attr('checked', 'checked');
return true;
} else {
checkBox.removeAttr('checked');
return false;
}
} else {
if (checkBox.attr('checked') == 'checked') {
return true;
} else {
return false;
}
}
}
function WebServerCall(functionName, successCallback, failedCallback, datatoSend) {
$.ajax({
type: "POST",
url: webserviceBaseUrl + functionName,
data: datatoSend,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successCallback,
error: failedCallback,
failure: failedCallback
});
}
function FailedCallback(xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.Message != undefined) {
var msg = new String(xhr.responseJSON.Message);
alert(msg);
if (msg.contains("login") > 0)
window.location.href = websiteBaseUrl + "login.aspx?from=" + encodeURIComponent(window.location.href);
} else {
alert(xhr.status + ' - ' + thrownError + '\n\n' + xhr.responseText);
}
}
`
Try something like this. Create a file where your JS resides, CustomerPopupForm.html and put your popup form html inside it:
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="Jane Smith" class="text ui-widget-content ui-corner-all">
<label for="email">Email</label>
<input type="text" name="email" id="email" value="jane#smith.com" class="text ui-widget-content ui-corner-all">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="xxxxxxx" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
Create your function to load the html and show the popup form:
function showPopup(closeCallback){
$("#divPopupHolder").remove(); //remove the holder div from a previous call
$("body").append("<div id='divPopupHolder'>" + + "</div>"); //add a div to document to hold the popup
$.get( "CustomerPopupForm.html", function( data ) {
$("#divPopupHolder").html(data); //add the popup to the new div.
});
dialog = $( "#dialog-form" ).dialog({ //show the dialog
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
if (closeCallback){ //you could do this for other buttons as well so the caller is notified when the dialog is closed.
closeCallback();
}
}
});
}
then call showPopup() from where you need to show the dialog.
So, after much learning (this tutorial was very helpful: https://code.tutsplus.com/courses/30-days-to-learn-jquery) and much trying I eventually made it work... not exactly sure what my problem was but this is what I wish I could find before:
This shows how to create functional single instance "class" (prob not class, plugin, or module i guess is the better term) with "namespace"
I found it was very convenient to use the namespace var as the event "target"
What do you think?
file: test.js
var XMen = {
Customer: (function($, undefined) {
var instance;
var datarow = {};
function init() {
function privateLoadData(idNumber) {
//Load up data
datarow = {IDField: idNumber, ValueField: 'something'};
$(XMen).trigger('XMen.CustomerDataLoaded');
};
function privateDisplay() {
console.log(datarow);
$(XMen).trigger('XMen.CustomerDataDisplayed');
};
return {
dr: function() { return datarow; }, //needs to be wrapped in function to get changes
load: privateLoadData,
display: privateDisplay
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
hasInstance: function () {
return (instance);
}
};
})(jQuery),
SalesOrder: (function($, undefined) { // another one like above? })(jQuery)
}
You would then include this file on your page
file: test.html
<body>
<h1>testing</h1>
<div id="testing"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
var customer = XMen.Customer.getInstance();
(function ($) {
$(XMen).on('XMen.CustomerDataDisplayed', function (e, data) {
console.log("test - XMen.CustomerDataDisplayed");//, e, data);
})
$(XMen).on('XMen.CustomerDataLoaded', function (e, data) {
console.log("test - XMen.CustomerDataLoaded");//, e, data);
})
console.log("test - Loading 8");
customer.load(8);
console.log("test - loading test2.html");
$("#testing").load("test2.html", function () {
console.log("test - finished loading test2.html");
});
setTimeout(function () {
console.log("test - displaying customer...");
customer.display();
}, 2000);
})(jQuery);
</script>
In test2.html we dont include any scripts since they are already included in test.html
file: test2.html
<div id="test2">
<h1>This is test2.html</h1>
<button id="btnTest">Test</button>
</div>
<script>
(function ($) {
$(XMen).on('XMen.CustomerDataDisplayed', function (e, data) {
console.log("test2 - XMen.CustomerDataDisplayed");//, e, data);
})
$(XMen).on('XMen.CustomerDataLoaded', function (e, data) {
console.log("test2 - XMen.CustomerDataLoaded");//, e, data);
})
})(jQuery);
console.log("test2 - displaying customer...");
customer.display();
</script>