Use ajax on client side when working with node - javascript

I have a very basic nodejs app that is displaying a html pages. This pages has two buttons linked with js function in a separated file. One of the function use ajax, the other not. The one using ajax is not working (not found I guess).
The external js file was working perfectly well under apache. Is there something specific to do to be able to use ajax on client side with node.js?
Here the node.js part:
var express = require ('express');
var app = express ();
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ChemAlive_JS'));
app.get('/', function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/test.html');
});
app.listen(8080);
The html part:
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="/Interface.css" type="text/css" rel="stylesheet" />
<link href="/ketcher.css" type="text/css" rel="stylesheet" />
<link href="/font-chemalive.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="/ddsmoothmenu.css" />
<link rel="stylesheet" type="text/css" href=/ddsmoothmenu-v.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/ui_bis.js"></script>
</head>
<body >
<div id="background">
<div id="LoginButton" class="deck login" >
<img class="LoginButtonUnpressed" alt="Login/Start" src="/ChemAlive_Start_Button.png">
<img class="LoginButtonPressed" alt="Login/Start" src="/ChemAlive_Start_Button_pressed.png">
<div class="popup" style="top: 0px; right: 80px;">
<p>Log-on or launch your calculations.</p>
</div>
</div>
<!-- Welcome Dialogue box -->
<div id="welcome_DB" class="dialogWindow fileDialog" >
<div class="h1">
<p>Welcome. Thank you for visiting our interface!</p>
</div>
<div class="iconDiv">
<img src="/Green_gears.png"/>
</div>
<div class="mainDiv">
<div class="desText">
<p>ChemAlive i</p>
</div>
</div>
<div class="navDiv">
<input type="submit" id="welcome_cancel" class="dialogButton" value="Cancel"/>
<label for="welcome_cancel" onclick="gototry();"><span class="label">Just Try It</span></label>
<input id="welcome_login" class="dialogButton" type="submit" value="Done"/>
<label for="welcome_login" style="right: 10px" onclick="gotologin();"><span class="label">Login</span></label>
<input id="welcome_register" class="dialogButton" type="submit" value="Done"/>
<label for="welcome_register" style="right: 20px" onclick="gotoregister();" ><span class="label">Registration</span></label>
</div>
</div>
<!-- Close welcome DB -->
</div>
</body>
</html>
And the external, client side, js:
$('LoginButton').observe('click', ui.onClick_login);
ui.onClick_login = function() {
window.alert("Hey There")
ui.showDialog('register_login');
}
function gototry() {
document.getElementById("welcome_DB").style.display = "none";
}
function gotologin() {
document.getElementById("welcome_DB").style.display = "none";
document.getElementById("login_v2").style.display = "inline-block";
}
function gotoregister() {
document.getElementById("welcome_DB").style.display = "none";
document.getElementById("register_DB").style.display = "inline-block";
}
Its $('LoginButton').observe('click', ui.onClick_login) call is not working.
Any ideas?

rename ui.onClick_login to a simple name like my_onclick_login
$('#LoginButton').observe('click', my_onclick_login);
my_onclick_login = function() {
window.alert("Hey There")
ui.showDialog('register_login');
}

Related

Display pokemon image [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am trying to display the image from pokeapi but I get an error when I input the name. When I input the number I do get the pokemon image after clicking twice. But when I search for another pokemon I get a number of the previous pokemon. I would appreciate the help on the proper way to display the image. Thanks.
JS code is as follows:
document.querySelector("#search").addEventListener("click", getPokemon);
function getPokemon(e) {
const name = document.querySelector("#pokemonName").value;
fetch(`https://pokeapi.co/api/v2/pokemon/${name || id}`)
.then((res) => res.json())
.then((data) => {
console.log(data);
document.getElementById("data_id").innerHTML = data.id;
document.getElementById("data_name").innerHTML = data.name;
document.getElementById("data_type").innerHTML = data.types
.map((type) => type.type.name)
.join(", ");
document.getElementById("data_moves").innerHTML = data.moves
.map((move) => move.move.name)
.slice(0, 5)
.join(", ");
document.getElementById("search").addEventListener("click", getImage);
function getImage() {
const img = new Image();
img.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${name || id}.png`;
document.getElementById("image").appendChild(img);
}
})
.catch((err) => {
console.log("Error pokemon not found", err);
});
e.preventDefault();
}
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CSS -->
<link rel="stylesheet" href="style.css" />
<!-- BOOTSTRAP -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous"
/>
<!-- Google fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Unbounded&display=swap"
rel="stylesheet"
/>
<!-- cdnfonts -->
<link
href="https://fonts.cdnfonts.com/css/pokemon-solid"
rel="stylesheet"
/>
<title>Pokedex</title>
</head>
<body>
<div class="main-container">
<h1 class="heading">Pokemon</h1>
<form class="nameForm">
<input
type="text"
id="pokemonName"
name="pokemonName"
placeholder="Enter Pokemon Name"
/><br />
<button type="submit" class="sub-btn" id="search">Enter</button>
</form>
<div class="pokemonInfo container text-center">
<div id="image"></div>
<div class="row row-cols-2 gy-1">
<div class="pokemon-info-left dark-green col">Pokedex no.</div>
<div class="yellow col" id="data_id"></div>
<div class="w-100"></div>
<div class="pokemon-info-left light-green col">Name</div>
<div class="light col" id="data_name"></div>
<div class="w-100"></div>
<div class="pokemon-info-left dark-green col">Type</div>
<div class="yellow col" id="data_type"></div>
<div class="w-100"></div>
<div class="pokemon-info-left light-green col">Move</div>
<div class="light col data_moves" id="data_moves"></div>
</div>
</div>
</div>
<!-- Javascript -->
<script src="main.js"></script>
</body>
</html>
I tried a few ways cant seem to get it to work.
You can create a image tag inside of div#image and change its src attribute after you receive the response from the API. Here is how:
In you HTML code, add this:
<div id="image">
<img src="" alt="Pokemon Image" id="pokemon-image" />
</div>
In you JS code, remove these lines:
document.getElementById("search").addEventListener("click", getImage);
function getImage() {
const img = new Image();
img.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${name || id}.png`;
document.getElementById("image").appendChild(img);
}
and replace with these code:
const img_link = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${data.id}.png`
document.getElementById("pokemon-image").setAttribute("src", img_link);

How to get AJAX data in jQuery?

I have a partial view where I want to reload certain <div> tag based on successful response. I am using .filter to get specific tag but it is not working. Based on other stack-overflow articles and google, this should work but not in my case.
My objective is, out of AJAX response, extract specific div tag and reload the view.
AJAX:
$.ajax(
{
url: '/MyUrl',
success: function(response)
{
updateOrderStatusContent(response);
}
});
this.updateOrderStatusContent = function (markup) {
alert("markup " + markup); // This returns HTML.
var $response = $(markup); // Creating jQuery object from HTML response.
// Option-1 = Get text
var getSpecificText = $response.filter('#delivery-status-update').text();
alert(getSpecificText); // This is empty.
// Option-2 = Get HTML
var getSpecificHtml = $response.filter('#delivery-status-update').html(); // to get HTML
alert(getSpecificHtml); // This is empty.
// Option-3 = Here I tried output the content of #delivery-status-update in new <div> which is also not working.
$('#delivery-status-updated').html(jQuery(markup).find('#delivery-status-update').html());
};
markup output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='UTF-8' />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta content='IE=Edge' http-equiv='X-UA-Compatible' />
<script src="/Scripts/S2/console.js"></script>
<!--[if IE]> <script src="/Scripts/S2/html5.js"></script>
<script src="/Scripts/S2/json2.js"></script>
<![endif]-->
<title></title>
<link href="/Content/S2/menu.css" rel="stylesheet" />
<link href="/content/themes/stwo/jquery-ui.css" rel="stylesheet" />
<link rel="shortcut icon" type="image/x-png" href="/Branding/Snapfinger/favicon.png" />
<link rel="apple-touch-icon" href="/Branding/Snapfinger/touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="/Branding/Snapfinger/touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="/Branding/Snapfinger/touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="/Branding/Snapfinger/touch-icon-ipad-retina.png">
<link rel="stylesheet" href="/Branding/Snapfinger/Snapfinger.css" />
<!--[if IE]><link rel="stylesheet" href="/Branding/Snapfinger/ie.css" /> <![endif]-->
</head>
<body>
<header class="header" id="header"> Skip to content
<div class="header-wrapper">
<div class="logo" id="logo" aria-label="Zaxby's logo" itemscope itemtype="https://schema.org/Organization" tabindex="0"> <img itemprop="logo" alt="Zaxby's logo" src="/api/content/image/119/7/200/200"></div>
<input type="hidden" id="restaurantId" value="9018" />
<input type="hidden" id="menuType" />
<input type="hidden" id="unitNumber" value="198" />
<input type="hidden" id="currentUtcTime" value="2018-04-24T19:27:29.2451514Z" />
<div class="restaurant-info">
<h1 class="title" id="title">Zaxby's</h1>
<meta itemprop="brand" content="Zaxby's" />
<meta itemprop="menu" content="https://local.kiofc.com/o/Restaurant/9018" /> <span itemprop="geo" itemscope itemtype="https://data-vocabulary.org/Geo"><meta itemprop="latitude" content="34.0756282" /><meta itemprop="longitude" content="-84.6527738" /> </span>
<div class="restaurant-name" itemprop="name">Zaxby's</div>
<div class="store-name" itemprop="name">ACWORTH_00198</div>
<ul id="restaurant-address" class="address" itemprop="address" itemscope itemtype="https://schema.org/PostalAddress">
<li class="street" itemprop="streetAddress" tabindex="0">3511 BAKER RD</li>
<li class="city" itemprop="addressLocality" tabindex="0">ACWORTH</li>
<li class="state" itemprop="addressRegion" tabindex="0">GA</li>
<li class="zip" itemprop="postalCode" tabindex="0">30101</li>
<li class="country" itemprop="addressCountry" tabindex="0">US</li>
</ul><a title="View location on google maps" class="map" itemprop="map" target="_blank" href="https://maps.google.com/maps?client=gme-snapfinger&channel=SnapfingerMobileViewMap&oi=map&q=3511+BAKER+RD,+ACWORTH,+GA+30101"> View Map </a>
<div class="phone" itemprop="telephone"> <a title="Call 678-574-0400" href="tel://678-574-0400">678-574-0400</a></div>
<input type="hidden" id="LocationDescription" value="ACWORTH - BAKER RD" />
</div>
</div>
</header>
<div class="page" id="delivery-status-bar">
<div class="content">
<section class="delivery-status" id="delivery-status-bar-section">
<div id="delivery-status-update">
<h3 class="summary-title">Delivery Status</h3>
<div id="order-id">
<h3 class="summary-title" tabindex="0">Order Confirmation : 97140987</h3></div>
<ol class="progress-tracker" data-progress-tracker-steps="4">
<li class="progress-tracker-done">Received</li>
<li class="progress-tracker-done">Kitchen</li>
<li class="progress-tracker-todo">In Transit</li>
<li class="progress-tracker-todo">Delivered</li>
</ol>
</div>
</section>
</div>
</div>
<footer class="footer" id="footer">
<div id="copyright-version">
<div id="copyright-info" tabindex="0"> © Copyright 2018 Tillster, Inc. All rights reserved.</div>
<div id="version-info" tabindex="0"> v 1.0.0.21003</div>
</div>
</footer>
<input id="concept-key" name="concept-key" type="hidden" value="Snapfinger" />
<input id="concept-id" name="concept-id" type="hidden" value="-1" />
<input id="is-vanity-url" name="is-vanity-url" type="hidden" value="False" />
<input id="is-on-premise" name="is-on-premise" type="hidden" value="False" />
<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="/Scripts/jquery-ui-1.11.1.js"></script>
<script src="/Scripts/S2/modernizr2.7.1.js"></script>
<script src="/Scripts/S2/jquery.lazyload.min.js"></script>
<script src="/Scripts/jquery/getscriptonce/jquery.getscriptonce.js"></script>
<script src="/Scripts/handlebars.js"></script>
<script src="/Scripts/S2/utility.js"></script>
<script src="/Scripts/S2/loginRegister.js"></script>
<script src="/Scripts/S2/analytics.js"></script>
<script src="/Scripts/S2/orderStatus.js"></script>
<div id="dialog">
<p id="dialog-message"></p><img id="dialog-image" alt="dialog message" src="#" /></div>
<noscript>
<iframe src="//www.googletagmanager.com/ns.html?id=GTM-PC8WMW" height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<script>
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src =
'//www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-M84GGD');
</script>
<script type="text/javascript">
s$.analytics.getOrderLevelData("pageLoad")
</script>
</body>
</html>
What am I missing here? Do I need to create another partial view to achieve what I want?
Basically you need to use .find() instead of .filter().
var markup = '<!DOCTYPE html><html lang="en"><head> <title></title></head><body><header class="header" id="header"> </header><div class="page" id="delivery-status-bar"><div class="content"><section class="delivery-status" id="delivery-status-bar-section"><div id="delivery-status-update"><h3 class="summary-title">Delivery Status</h3><div id="order-id"><h3 class="summary-title" tabindex="0">Order Confirmation : 123</h3></div><ol class="progress-tracker" data-progress-tracker-steps="4"><li class="progress-tracker-done">Received</li><li class="progress-tracker-done">Kitchen</li><li class="progress-tracker-done">In Transit</li><li class="progress-tracker-todo">Delivered</li></ol></div></section></div></div><footer class="footer" id="footer"></footer></body></html>';
var $response = $(markup); // Creating jQuery object from HTML response.
var $delivery = $response.find('#delivery-status-update');
var getSpecificText = $delivery.text(); // to get text
var getSpecificHtml = $delivery.html(); // to get HTML
console.log(getSpecificText);
console.log(getSpecificHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Angularjs fails to dynamic change image src

Hello i'm building an application where i want to dynamically change the source of an image in order to force reload it . The problem is that in order of this i only get a broken image on the browser. Instead , if a run the function manually by a button it runs perfect .
HTML document
<!DOCTYPE html>
<html lang="en" ng-app='cameraApp'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node JS Camera</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.4/angular-sanitize.min.js'></script>
<script src="cameraApp.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h1>Welcome to NodeJS Camera v1</h1>
</div>
<div ng-controller="HomeController">
<div class="cameraControl col-md-5">
<p>Here is the camera control</p>
<button class="btn btn-default" ng-click="getSnapshot()">Snapshot</button>
<button class="btn btn-info" ng-click="intervalFunction()">Start Feed</button>
</div>
<div class="lifeFeed col-md-7">
<p>Here is the live feed</p>
<p><button class="btn btn-default" ng-click="readSnapshot()">Snapshot Read</button></p>
<img width='600' height='600' ng-src="{{snapshot}}" alt="SnapShot taken">
</div>
</div>
</div>
</body>
</html>
cameraApp.js
var cameraApp = angular.module('cameraApp',[]);
cameraApp.controller('HomeController', function($scope,$http,$timeout) {
function updateImage() {
var img = 'snapshots/camera.jpg'+ '?decache=' + Math.random();
console.log('Snapshot Loaded');
$scope.snapshot = img;
};
$scope.readSnapshot = updateImage;
$scope.getSnapshot = function() {
$http.get('/api/getSnapshot')
.then(function(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Snapshot captured');
$scope.readSnapshot();
}, function(response) {
console.log('Error in capturing...');
});
}
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getSnapshot();
$scope.intervalFunction();
}, 2000);
};
// Kick off the interval
$scope.intervalFunction();
});
There are two solutions I've used for this in the past.
1) Use an ng-if/ng-show on your img tag. This will prevent the broken image from displaying.
<img ng-if='snapshot'>
2) Set a default image that will load and then be replaced once the other images load.
$scope.snapshot = 'snapshots/default.png';

search a databse by using a cfquery inside a javascript function

Hi this is my first question on stackoverflow :)
trying to get coldfusion working with javascript.
I'm trying to pull out data off a database and show it in my page.
but i realized js is a client side language and cf being serverside.
I can't just run cfquery inside a function so i have two files
one is my index.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
</head>
<body class="jumbotron">
<div class="container text-center " >
<div class="row">
<img class="col-sm-4 col-sm-offset-4" src="emp.jpg"/>
</div>
<div class="row" style="margin-top:20px" >
<div class="col-sm-6 col-sm-offset-3">
<div id="imaginary_container">
<div class="input-group stylish-input-group">
<input type="text" class="form-control" id="searchBar" name="searchBar" placeholder="Search" >
<span class="input-group-addon">
<button onclick="search(global,$http)">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
</div>
</div>
</div>
<script>
function search($scope, $http) {
var searchQ = document.getElementById('searchBar').value;
$http.get('/grid.cfc?method=getContact&returnformat=json').
success(function (response) {
$scope.todos = data.DATA;
}).
error(function (data) {
$scope.todos = data;
});
};
</script>
</body>
</html>
and one is my grid.cfc
<cfcomponent>
<cffunction name="getContact" access="remote" >
<cfargument name="firstName" default="">
<cfargument name="lastName" default="">
<cfquery name="searchQry" datasource="MehrabanDSource">
SELECT
*
FROM Contacts
WHERE FirstName=fname;
</cfquery>
<cfreturn searchQry>
</cffunction>
</cfcomponent>
can you help me make sense of my code, i don't really know if im on the right track or how can i pass in a variable to my grid.cfm so it knows what first name to look for. THANKS A LOT in ADVANCE :)
thank you Dan, thank you Leigh :) i used :
<cfajaxproxy cfc="functions" jsclassname="ajax_proxy" />
<cfajaximport>
<script>
function send_ajax(searchBar) {
var instance = new ajax_proxy();
instance.setCallbackHandler(return_ajax);
instance.functionality(searchBar);
}
function return_ajax(result) {
document.getElementById('output').innerHTML = result;
}
</script>

Can't get JS function working properly

I've got this form with bootstrap but I can't find why it's not working properly ant I've no idea why.
HEAD>>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="css/bootstrap-theme.css" rel="stylesheet" type="text/css"/>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/corrections.css" rel="stylesheet" type="text/css"/>
<script src="js/JQuery-2.1.1-min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
--> code here
</body>
HTML >>
<div class="col-lg-4">
<form class="form-inline well">
<div class="form-group">
<label class="sr-only" for="text">Some label</label>
<input id="text" type="text" class="form-control" placeholder="Text here">
</div>
<button type="submit" class="btn btn-primary pull-right">Ok</button>
<div class="alert alert-danger" style="display:none">
<h4>Error</h4>
Required amount of letters is 4
</div>
<div class="success alert-success" style="display:none">
<h4>Success</h4>
You have the required amount of letters
</div>
</form>
</div>
JS >>
<script>
$(function () {
$("form").on("submit", function () {
if ($("input").val().length < 4) {
$("div.form-group").addClass("has-error");
$("div.alert").show("slow").delay(4000).hide("slow");
return;
} else if ($("input").val().length > 3) {
$("div.form-group").addClass("has-success");
$("div.success").show("slow").delay(4000).hide("slow");
return;
}
});
});
</script>
the alert class shows everytime, any idea why?
The use of $("input") here is unusual. That selector will pull back all elements on the page that are <input>s, which is almost certainly not what you mean. (If there are other inputs on the page, you might get exactly what you're describing.) Use a more precise selector, like $("#text"), and maybe use debug to output the value of val().length so you know what you're evaluating.
(On a side note, "text" is not a very useful name for a text input, and your else-if seems redundant, but they probably aren't causing problems in your code.)

Categories

Resources