document.ready jquery difficulty - javascript

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
});

Related

Triggering a Rest API call with a JQuery Mobile button

This is simple but my JS is a bit rusty..
I am trying to trigger a get request by pressing a JQuery Mobile element.
I can see the button but failing to do an actual Get Request
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<p><input type="checkbox" data-role="flipswitch" name="flip-checkbox-1" id="generator_button"></p>
</form>
</body>
<script>
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
</script>
Please, note: in your markup there is a Flip switch of type checkbox, not a button, so I believe you may better check the state of the underlying checkbox instead of stick to a tap event.
Reference: jQuery Mobile Flip switch
Moreover, you it would be nice to provide a JQM page structure to the whole stuff.
Here is an example:
function sendRequest() {
$.ajax({
'url': '192.168.8.110:5000/generator_on',
'type': 'GET',
'success': function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
}
$(document).on("change", "#generator_button", function() {
var state = $("#generator_button").prop("checked");
if (state === true) {
// Flip switch is on
console.log("Request sent.");
//sendRequest(); // uncomment
} else {
// Flip switch is off
//...endpoint _off
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="page-one" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Header</h1>
</div>
<div role="main" class="ui-content">
<label for="flip-checkbox-1">Flip toggle switch checkbox:</label>
<input type="checkbox" data-role="flipswitch" name="generator_button" id="generator_button">
</div>
<div data-role="footer" data-position="fixed">
<h1>Footer</h1>
</div>
</div>
</body>
</html>
You are missing }); on last line of your javascript.
Your javascript code should look like this
$("p").on("tap",function(){
$.ajax({
'url' : '192.168.8.110:5000/generator_on',
'type' : 'GET',
'success' : function(data) {
if (data == "success") {
alert('request sent!');
}
}
});
});
Ok, so I had to change the url to: 'http://192.168.8.110:5000/generator_on and tested it on a browser without an adblock I mentioned to make it work!

$(...).getJSON is not a function

I'm trying to develop a simple API call that returns my comments in a JSON response but when I click on it I get the error
$(...).getJSON is not a function
My idea is, when I click on the button "Comment"(id=showarea) it immediately prints the comments from that answer and the textarea.
I'm "hardcoding" on the file just for testing.
I had this file (javascript/askme/comment.js)
function initCommentReloader() {
$('#textarea').on('click', 'a', function() {
$.getJSON("/controller/api/comments/comment.php", {answerid: answerid}, function(data) {
$.each(data, function(i, comment) {
console.log(comment);
});
});
});
}
but when nothing happens that way, it doesn't even recognize the click,
then I changed to an hardcode way and the error happened. I checked my jquery include and everything seems properly included.
This is the file where I'm trying to load the comments. Can you find anything wrong?
I'm sorry if this is extreme newbie, but I've been stressing this way too much.
Kind regards
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>AskMe</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#tabs" ).tabs();
} );
</script>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="{$BASE_URL}css/fonts/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="{$BASE_URL}css/fonts/font-awesome.css">
<link rel="stylesheet" type="text/css" href="{$BASE_URL}css/styles/bootstrap.css">
<link rel="stylesheet" type="text/css" href="{$BASE_URL}css/styles/main.css">
<link rel="stylesheet" type="text/css" href="{$BASE_URL}css/styles/responsive.css">
<link rel="stylesheet" type="text/css" href="{$BASE_URL}css/styles/clean-blog.min.css">
<!-- JS -->
<script type="text/javascript" src="{$BASE_URL}javascript/vendor/bootstrap.js"></script>
<script type="text/javascript" src= "{$BASE_URL}javascript/Chart.js"></script>
<script type="text/javascript" src="{$BASE_URL}javascript/main.js"></script>
<script src="https://cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
</head>
<div class="post-button clearfix">
<button class="btn icon-chat" title="Add a comment on this answer"
type="submit" id="showarea" name="showarea" value="Show Textarea">
Comment</button>
<div id="textarea">
{include file="comment.tpl"}
{include file="comment_form.tpl"}
</div>
</div>
<script>
answerid = {$answer['answerid']};
console.log();
$("#showarea").click(function() {
$("#showarea").getJSON("/controller/api/comments/comment.php", function (data) {
console.log(data);
});
});
</script>
{HTML::script('askme/comment.js')}
It may not be the particular issue here, but the same confusing error comes up if using the "slim" version of jQuery which excludes ajax, animations, etc.
If ".slim" appears in the line which includes jQuery, try taking that out.
Also, check the browser console to be sure jQuery is loading properly and not getting a 404 or similar error.
Maybe change
$("#showarea").getJSON
to
$.getJSON
you can try:
$(document).on('click', '#textarea>a', function() {
$.getJSON("/controller/api/comments/comment.php", {answerid: answerid}, function(data) {
$.each(data, function(i, comment) {
console.log(comment);
});
});
});
OR
$(document).on('click', '#textarea>a', function() {
$.getJSON( "/controller/api/comments/comment.php", {answerid: answerid})
.done(function( data ) {
$.each(data, function(i, comment) {
console.log(comment);
});
})
});
OR
$(document).on('click', '#textarea>a', function() {
$.ajax({
dataType: "json",
url: "/controller/api/comments/comment.php",
data: {answerid: answerid},
success: success
}).done(function( data ) {
$.each(data, function(i, comment) {
console.log(comment);
});
});
});
May be due to jQuery version, you need to change
$.getJSON
to
jQuery.getJSON
Another option is droping $.getJSON and using $.ajax as (according to jQuery documentation) $.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});

How to initialize bootstraps tooltip after including with ajax?

I am loading content (HTML) to my website with ajax. This includes, inter alia, this snippet:
Hover me...
As described here: bootstrap 3 > tooltip, i need to initialize it. How can i initialize it after ajax success?
Edit: Full working example. Here i simulate an "ajax call". The problem is the duration. When you delete the timeout it would work:
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div id="html" style="margin-top: 50px;">
That works: Hover me 1...
</div>
<div style="margin-top: 50px;">Ajax: <span id="ajax"></span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript">
// Document ready
$(document).ready(function ()
{
loadResult();
activateTooltip();
});
// Result
function loadResult()
{
// "Ajax call"
setTimeout(function(){
var result = 'Hover me 2...';
$("#ajax").html(result);
}, 2000); // Simulate Ajax duration
activateTooltip();
}
// Tooltip
function activateTooltip()
{
$('[data-toggle="tooltip"]').tooltip();
}
</script>
</body>
</html>
https://plnkr.co/edit/KBsJK27F9Sb5kV2Ozy56
Hover me...
and reactivate tooltip function in ajax success:
function loadResult()
{
$.ajax({
type: "POST",
url: "index.php?action=loadResult",
data: "id=1",
dataType: 'text',
success: function(data){
var json = $.parseJSON(data);
$("#result").html(json.result);
activateTooltip();
}
});
}
Just add this attribute:
data-placement="right"

SignalR MVC4 Issue

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.

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>

Categories