SignalR MVC4 Issue - javascript

I am following this tutorial to integrate SignalR to my project http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/
So basically this is my View where I want to show my table.
#{
ViewBag.Title = "PatientInfo";
}
<h2>PatientInfo</h2>
<h3>#ViewBag.pName</h3>
<h5>#ViewBag.glucoseT</h5>
#if (Session["LogedUserFirstname"] != null)
{
<text>
<p>Welcome #Session["LogedUserFirstname"].ToString()</p>
</text>
#Html.ActionLink("Log Out", "Logout", "Home")
<div class="row">
<div class="col-md-12">
<div id="messagesTable"></div>
</div>
</div>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/SignalR/Hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
}
My project is running but the table doesn't appear at all. I started by pasting the view because I believe that the scripts are not executed in the first place; The Alert Message is NOT being shown even if I try to add one directly after
$(function () {
alert("I am an alert box!");
This is my Layout.cshtml file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#p_table").dataTable();
});
</script>
#RenderSection("scripts", required: false)
</body>
</html>
I am using Visual Studio 2012, MVC4.
Please Help..

Make sure you have placed all your script tags from the view inside the scripts section of the view:
#section scripts {
... your <script> tags come here
}
The reason why your alerts don't work is because you have directly put them inside the body of the view which gets rendered at the #RenderBody() call of the Layout. But as you can see it's only at the end of this Layout that we have references to the scripts such as jQuery and signalr.
Now they will appear at the proper location: #RenderSection("scripts", required: false).
By the way use the console window in your webbrowser to see potential script errors you might have. For example in your case it would display that jQuery is not defined error.
Another remark: don't include signalR script twice: right now you seem to have included jquery.signalR-2.2.0.js in your view and jquery.signalR-2.2.0.min.js in your Layout.

Related

Getting Uncaught ReferenceError: $ is not defined for jquery

I am trying to call a local api I am testing. I am getting a Uncaught ReferenceError: $ is not defined on the call. Here is the JS and html. Is there something I am missing with defining the query within the .js file? It was working before I did some refactoring I am not sure if I deleted something I need and didnt even notice it.
taskpane.js
function domainWhois(domain){
var apiurl = 'http://localhost:5000/linkcheck';
console.log("entering domainWHois");
var request = {"link": domain};
$.ajax({
url: apiurl,
method: 'POST',
type: 'json',
data: JSON.stringify(request),
contentType: 'application/json',
crossDomain: true
}).done(
function(data){
console.log("successfully called API");
console.log(JSON.stringify(data));
}).fail(function(error){
console.log("api call failed");
console.log(JSON.stringify(error));
});
}
Here is the HTML set up
!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contoso Task Pane Add-in</title>
<!-- Office JavaScript API -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
<script type="text/javascript" src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js"></script>
<!-- For more information on Office UI Fabric, visit https://developer.microsoft.com/fabric. -->
<link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-core/9.6.1/css/fabric.min.css"/>
<!-- AJAX-->
<!-- Template styles -->
<link href="taskpane.css" rel="stylesheet" type="text/css" />
<script src="taskpane.js" type="text/javascript"></script>
</head>
<body class="ms-font-m ms-welcome ms-Fabric">
<header class="ms-welcome__header ms-bgColor-neutralLighter">
<img width="90" height="90" src="../../assets/logo-filled.png" alt="Contoso" title="Contoso" />
<h1 class="ms-font-su">Welcome to your Email Security Assistant</h1>
</header>
<section id="sideload-msg" class="ms-welcome__main">
<h2 class="ms-font-xl">Please sideload your add-in to see app body.</h2>
</section>
<main id="app-body" class="ms-welcome__main" style="display: none;">
<div>
<h2>Secuirty Checks</h2>
<h3>Attachments</h3>
<p><label id="attachment-count"></label></p>
<p><label id="attachment-msg"></label></p>
<h3>Embedded Links</h3>
<p id="linkCheck"></p>
<h3>Header Checks</h3>
<p><label id="reply-match"></label></p>
<p><label id="dkimspfchk"></label></p>
<p><label id="domainMatch"></label></p>
</div>
</main>
</body>
</html>
Check Handling code which relies on jQuery before jQuery is loaded . It will solve your problem. Because your jquery is loaded. So t is recommended to put external scripts imports before the closing body tag, it allows asynchronous loading while the loading in the head tag is a blocking synchronous loading.

javascript program not appending markup correctly

I am following a tutorial in Jasmine and serverless. The problem I am facing is around Javascript.
There is a public directory which has an index.html
Jasmine tests are in public/tests directory. It also has an index.html.
Following JS code (SpecHelper.js below) is suppose to find markups with class markup in public/index.html and copy that code in <body> of public/tests/index.html but it isn't doing so. I am unable to find the issue.
public/index.html
<body>
<div class='markup'>
<div class='view-container container'>
<div class='one-half column'>
<h3>Learn JS, one puzzle at a time</h3>
<a href='' class='button button-primary'>Start now!</a>
</div>
<div class='one-half column'>
<img src='/images/HeroImage.jpg'/>
</div>
</div>
</div>
</body>
SpecHelper.js
var fixture;
function loadFixture(path) {
var html;
jQuery.ajax({
url: '/index.html',
success: function(result) {
html = result;
},
async: false
});
return $.parseHTML(html);
}
function resetFixture() {
if (!fixture) {
var index = $('<div>').append(loadFixture('/index.html'));
var markup = index.find('div.markup');
fixture = $('<div class="fixture" style="display: none">').append(markup);
$('body').append(fixture.clone());
} else {
$('.fixture').replaceWith(fixture.clone());
}
}
beforeEach(function () {
resetFixture();
});
public/tests/index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.3.4</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.3.4/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.3.4/jasmine.css">
<!-- App Dependencies -->
<script src="lib/jquery-2.1.4.js"></script>
<script src="/vendor.js"></script>
<!-- Test libraries -->
<script type="text/javascript" src="lib/jasmine-2.3.4/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-2.3.4/jasmine-html.js"></script>
<script type="text/javascript" src="lib/jasmine-2.3.4/boot.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="/app.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="SpecHelper.js"></script>
<script type="text/javascript" src="app_spec.js"></script>
</head>
<body>
<!--This is always empty! -->
</body>
</html>
The test in Jasmine fails with following error
1 spec, 1 failure
Spec List | Failures
learnJS can show problem view
Expected 0 to equal 1.
Try this
fixture = $('<div class="fixture" style="display: none">').append(markup.html());
Then maybe
$('body').append(fixture.clone().html());
got it working..phew ... had to clear browser cache by going to developer tools, networks. I noticed that most files were being picked from memory. Right clicked and cleared cache and cookies.

Content no load (jquery mobile)

I am developing an application with jQuery mobile and json bring data.
I have a problem loading content when I click on a button but if I enter directly to link the content is there.
Please, look:
if you click on any image it shows a page without content: http://www.example.com.ar/catalogoar/
But if you enter http://www.example.com.ar/catalogoar/arma_ampliada.html?id_arma=1 the content is there.
I can't find the problem. I already try with
$("#tabla_arma").table('refresh');
Please, learn how jQuery Mobile works before you post any more related questions. I am not trying to attack you but people here don't like this kind of questions.
To be able to solve this problem you need to understand how jQuery Mobile page handling works, and you can't solve this problem.
When jQuery Mobile handles pages only first HTML files is fully loaded into the DOM, all intermediate files are loaded only partially. When I say partially I mean HEAD will be stripped away and only FIRST data-role="page" will be loaded.
So if you have 2 pages, for example lets say first one is called index.html and second one is called arma_ampliada.html. When second page is initialized only content inside data-role="page" <div> will load into the DOM, everything else is going to get discarded, including HEAD javascript you need to load your data.
Read more about it here, you will also found solutions.
Your arma_ampliada.html page should look like this:
<html>
<head>
<title>Catálogo de Armas</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<!-- CSS -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.2.css" />
<link rel="stylesheet" href="css/listview-grid.css">
<link rel="stylesheet" href="css/estilos.css">
<!-- JS -->
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function()
{
$.mobile.defaultPageTransition = 'slide';
});
</script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<!-- <script src="js/cordova.js"></script> -->
</head>
<body>
<div data-role="page" data-theme="a" id="demo-page" class="my-page">
<script>
var armas;
function obtenerArmaAmpliada(id_arma){
$.ajax({
type: 'GET',
data: {'id_arma' : id_arma},
dataType : 'jsonp',
url: 'service/datos.php?jsoncallback=?',
success:function(data){
armas = data.armas;
mostrarArmas();
},
error: function() {
alert("error");
}
});
}
function mostrarArmas ()
{
$("#arma_ampliada").html('');
$.each(armas, function(indice, receta)
{
$("#arma_ampliada").append('<tr><td><img src="'+receta.foto+'" class="ui-li-thumb" ><h2>'+receta.marca+'</h2><p>'+receta.modelo+'</p></td></tr>');
});
$("#tabla_arma").table('refresh');
}
$(function(){
var Url = location.href;
Url = Url.replace(/.*\?(.*?)/,"$1");
Variables = Url.split ("&");
for (i = 0; i < Variables.length; i++)
{
Separ = Variables[i].split("=");
eval ('var '+Separ[0]+'="'+Separ[1]+'"');
}
obtenerArmaAmpliada(id_arma);
});
</script>
<div data-role="header" style="overflow:hidden;">
<h1>Catálogo de Armas</h1>
Opciones
<div data-role="navbar">
<ul>
<li>Marcas</li>
<li>Calibre</li>
<li>Tipo</li>
</ul>
</div>
</div>
<div role="main" class="ui-content">
<div id="tabla_arma">
<table id="arma_ampliada">
</table>
</div>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>

How to connect to a SignalR hub from PhoneGap app on iOS?

I am attempting to build a PhoneGap iOS client for a basic SignalR chat server I have running (ASP.NET MVC 4). Everything works great when accessing it from a page in a browser but I just can't seem to get it to connect from the PhoneGap app. Here's the relevant parts of my code:
Server global.asax
protected void Application_Start()
{
// Register the default hubs route: ~/signalr * This must be registered before any other routes
RouteTable.Routes.MapHubs(new HubConfiguration { EnableCrossDomain = true });
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
Server web.config
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
</system.webServer>
</configuration>
Server hub
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
PhoneGap client
<body>
<div data-role="page">
<div data-role="header">
<h1>Life As A Pixel</h1>
</div><!-- /header -->
<div data-role="content">
<label for="username">Name:</label>
<input type="text" name="username" id="username" value="" />
<label for="message">Message:</label>
<input type="text" name="message" id="message" value="" />
<br>
<input type="button" value="Send" id="sendmessage" />
</div><!-- /content -->
<div data-role="footer" data-position="fixed">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
<script type="text/javascript" src="cordova-2.7.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.3.1.js"></script>
<script type="text/javascript" src="js/jquery.signalR-1.0.0-rc1.min.js"></script>
<script type="text/javascript" src="http://www.mysite.com/signalr/hubs"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub
jQuery.support.cors = true;
$.connection.hub.url = 'http://www.mysite.com/signalr';
var chat = $.connection.chatHub;
alert(chat);
//alert(chat);
// Create a function that the hub can call to broadcast messages.
//chat.client.broadcastMessage = function (name, message) {
//$('#discussion').append('<li><strong>' + name
// + '</strong>: ' + message + '</li>');
//};
// Set initial focus to message input box.
//$('#message').focus();
// Start the connection.
$.connection.hub.start({ jsonp: true }).done(function () {
alert("connected");
$('#sendmessage').click(function () {
// Html encode display name and message.
var encodedName = $('<div />').text($('#username').val()).html();
var encodedMsg = $('<div />').text($('#message').val()).html();
// Call the Send method on the hub.
chat.send(encodedName, encodedMsg);
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
}).fail(function () {
alert("Failed to connect");
});
});
</script>
</body>
I've been through a ton of sites that talk about bits and pieces of it but can't get it figured out.
Thanks in advance,
Jason
I hope this helps. From here -> http://agilefromthegroundup.blogspot.com/2012/09/getting-signalr-and-phonegap-working.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Chat</title>
<link rel="stylesheet" href="jquery.mobile-1.0.1.css" />
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript" src="jquery.mobile-1.0.1.js"></script>
<script type="text/javascript" src="http://jgough/SignalR/Scripts/jquery.signalR-0.5.3.js"></script>
<script type="text/javascript" src="http://jgough/SignalR/signalr/hubs"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<style type="text/css">
.ui-title
{
font-weight: bold;
}
</style>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://jgough/SignalR/signalr";
// Grab the hub by name, the same name as specified on the server
var chat = $.connection.chat;
chat.addMessage = function (message) {
$('#chatMessages').append('<li>' + message + '</li>');
};
$.connection.hub.start({ jsonp: true });
$("#sendChatMessage").click(function () {
var message = $("#chatMessage").val();
console.log("Message: " + message);
chat.send(message);
});
});
</script>
</head>
<body>
<div id="home" data-role="page">
<div data-role="header">
<h1>
Chat!</h1>
</div>
<div data-role="content">
<h2>
Chat your heart out...</h2>
<div>
<textarea id="chatMessage"></textarea>
<br />
<a id="sendChatMessage" data-role="button">Send Chat Message</a>
</div>
<ul id="chatMessages">
</ul>
</div>
<div data-role="footer" data-position="fixed">
Thank you for chatting
</div>
</div>
</body>
</html>

document.ready jquery difficulty

In the master page I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
#RenderBody()
</body>
</html>
Then in the Index.cshtml I have the following code:
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<div data-role="page">
<div data-role="header">
...</div>
<div data-role="content">
<a id="btnShowCustomers" data-role="button" href="#secondDiv"></a>
</div>
<div data-role="footer">
...</div>
</div>
<div id="secondDiv" data-role="page">
<div data-role="content">
</div>
</div>
<script type="text/javascript">
(document).ready(function (event) {
$('#btnShowCustomers').bind('click', function (event) {
GetCustomers();
});
});
function GetCustomers() {
var webMethod = "Home/GetCustomers";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: webMethod,
data: "{}",
dataType: "json",
success: function (dataObj) {
alert('lala');
}
});
}
</script>
Debugging with Firebug i get the following error:
document.ready is not a function
[Break On This Error] (document).ready(function (event) {
How is that possible? On document ready i want to register the handler for the button's click event.. Any suggestions?
(document).ready(function (event) {
should be
$(document).ready(function (event) {
Should be $(document).ready(function (event) ...
Notice the dollar sign prefixed to the start of the string - although this can differ, jQuery code generally uses this prefix to access its context for selectors and whatnot.
See this page for some information on utilising jQuery.
you ar missing a $
$(document).ready(function (event) {
(document).ready(function (event) {
You don't have $ or jQuery before (document), this it thinks it is calling ready directly on the document object. ready is a jQuery short cut, not a DOM method.
if you include JQuery like this:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1.min.js" type="text/javascript"></script>
then this should work:
$(document).ready(function() {
// Handler for .ready() called.
});
As a shortcut you can also write
$(function(){
//your code
});
which is equivalent to writing
$(document).ready(function(){
//your code
});

Categories