Triggering a Rest API call with a JQuery Mobile button - javascript

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!

Related

$(...).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"

Whenever I try and load my JSON data into my listview or select menu, nothing shows up

So basically, when I load my data from the server script (retrieve.php), it shows up the in the showlist.html using $('#result').html(data). But whenever I try to load my listview or selectbox with that data..nothing happens. PLEASE ADVICE what I might be doing wrong
//SERVER-SIDE SCRIPT - retrieve.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=sports_rush;charset=utf8', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query = "SELECT eid,event_title FROM event_table";
$result = $pdo->prepare($query);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo json_encode($row);
}
$db_connection = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
//I found this recursive function online to enable me force convert to UTF-8 all the strings contained in an array
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else {
return utf8_encode($d);
}
return $d;
}
?>
//FILE THAT SHOWS MY DATA FROM SERVER-SIDE SCRIPT - Showlist.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<title>SHOW LIST</title>
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css"/>
<link rel="stylesheet" href="jquery-mobile/jquery.mobile-1.4.2.min.css" />
<script src="jquery-mobile/jquery-1.9.1.min.js"></script>
<script src="jquery-mobile/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<div data-role="page" id="home_page">
<div data-role="header" data-theme="a">
<h1>Header</h1>
</div>
<div data-role="content">
<select name="zip" id="zip" onChange="initializeRetrieve()"></select>
<div id="result"></div>
<ul data-role="listview" data-inset="true" id="postallist"></ul>
</div>
</div>
<script>
$(function(){
$.ajax({
url : 'retrieve.php',
type : "POST",
success : function(data){
var output = '';
$('#result').html(data); //This is just a test to see my data
$.each(data, function (index, value) {
output += '<li>' + value.eid + '</li>';
});
$('#postallist').html(output).listview("refresh");
}
});
});
function initializeRetrieve(){
var $select5 = $('#zip');
//request the JSON data and parse into the select element
$.getJSON("retrieve.php", function(data){
//iterate over the data and append a select option where eid is in the json file
$.each(data, function(key, value){
$select5.append('<option>' + value.eid + '</option>');
});
});
}
</script>
</body>
</html>
Have you tried using the GET method
Try putting your request to $(document).ready
$(document).ready(function(){
$.getJSON('retrieve.php', function(data) {
$('#result').html(data);
})
});
//FINALLY GOT IT WORKING. The problem was in my showlist.html. Needed to change up my initialization when my page opens
<html>
<meta charset="utf-8" />
<title>SHOW LIST</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Sports Rush Events</h1>
</div>
<div data-role = "content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$.ajax({
url : 'retrievelist.php',
type : "POST",
dataType: 'json',
success : function(data){
$.each(data,function(i,dat){
$("#list").append("<li><b>ID: </b>"+i+"</br><b> Name: </b>"+dat.event_title+"</li>");
});
$("#list").listview('refresh');
}
});
});
</script>
<div data-role="footer" data-position="fixed">
</div>
</div>

select2 twitter bootstrap css minor issue

I am new into web devlopment. I am trying to use select2-bootstrap. It working fine. Just need a css help.
Initial display of widget :
There is an indent between the bars(between Search for a movie and No matches found)
After clicking on the widget it looks fine as shown here and thereafter the dent disappears even on subsequent use.
Can someone suggest how to remove the dent between two bars in the first pic above.
NOTE :
CSS Added : select2.css, select2-bootstrap.css and bootstrap.css
JS Added : bootstrap.js, jquery-1.9.1.js, select2.js
Also please suggest how to avoid the No matches found display immediately after page loads.
Here is the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Twitter Bootstrap</title>
<link rel="stylesheet" type="text/css" media="screen"
href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="css/select2.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="css/select2-bootstrap.css" />
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript" src="js/select2.js"></script>
<script type="text/javascript">
var contextPath = "<%=request.getContextPath()%>";
$(document)
.ready(
function() {
MultiAjaxAutoComplete('#e6',contextPath + "/getData");
$('#save').click(function() {
alert($('#e6').val());
});
});
</script>
<script type="text/javascript">
function MultiAjaxAutoComplete(element, url) {
$(element).select2({
placeholder : "Search for a movie",
//minimumInputLength : 1,
multiple : true,
ajax : {
url : url,
dataType : 'json',
data : function(term, page) {
return {
q : term,
page_limit : 10,
};
},
results : function(data, page) {
console.log("page = " + page);
return {
results : data.results
};
}
},
formatResult : formatResult,
formatSelection : formatSelection,
initSelection : function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id : item[0],
country : item[1]
});
});
callback(data);
}
});
};
function formatResult(movie) {
return '<div>' + movie.country + '</div>';
};
function formatSelection(data) {
return data.country;
};
</script>
</head>
<body style="background-color: #F9F9F6">
<h1>Serach Movies</h1>
<div class="container-fluid">
<div class="row-fluid">
<div class="span9">
<input type='hidden' id="e6" class="span8" />
</div>
<div class="span3">
<button id="save">Save</button>
</div>
</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