how to pass dynamic url in ajax request via model reveal? - javascript

i am using foundation reveal model but i am not able to pass dynamic url to data-ajax-url.
i want to pass dynamic project_site.id in url but not i am able to append dynamic url .
currently i test on local url: "http://0.0.0.0:3000/project_sites/21/attendances/" here 21 is hard coded url i want to pass dynamic url.
reference i used:- https://codepen.io/sujayjaju/pen/akAYzP?editors=1010
here is my code-
<div class="full reveal" id="exampleModal1" data-reveal data-ajax-url="http://0.0.0.0:3000/project_sites/21/attendances/">
<button class="close-button" data-close aria-label="Close modal" type="button">
<span aria-hidden="true">×</span>
</button>
</div>
<p><button class="button small warning button-margin-top fi-eye" data-open="exampleModal1"> View</button></p>
application.js
$(document).on('open.zf.reveal', "#exampleModal1", function (e) {
var $modal = $(this);
var ajax_url = $modal.data("ajax-url");
if (ajax_url) {
$modal.html("Now Loading: "+ajax_url);
$.ajax(ajax_url).done(function (response) {
$modal.html(response);
});
}
});

If you want to pass a dynamic URL, why don't you just pass it in jquery instead of relying on data-attributes?
var ajax_url = "http://0.0.0.0:3000/project_sites/" + project_site.id + "/attendances/";

If you must work with data-attributes what about doing something like this:
$(document).foundation();
$(document).on('open.zf.reveal', "#login", function (e) {
var $modal = $(this);
var project_site_id = 21
var ajax_url = $modal.data("ajax-url");
var lastpos = ajax_url.lastIndexOf("/");
var newUrl = ajax_url.substring(0, lastpos);
var lastWord = ajax_url.substring(lastpos);
newUrl += '/' + project_site_id + lastWord;
$modal.attr("data-ajax-url", newUrl);
console.log(newUrl);
if (ajax_url) {
$modal.html("Now Loading: "+ajax_url);
$.ajax(ajax_url).done(function (response) {
$modal.html(response);
});
}
});
<link href="https://cdn.jsdelivr.net/foundation/6.2.1/foundation.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/motion-ui/1.1.1/motion-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/what-input/1.1.4/what-input.min.js"></script>
<script src="https://cdn.jsdelivr.net/foundation/6.2.1/foundation.min.js"></script>
<html>
<body>
<div id="login" class="reveal text-center" data-reveal
data-ajax-url="https://codepen.io/sujayjaju/pen/VKkxKY.html">
</div>
<a href="#login" data-open="login" class="button">
Open Modal Form
</a>
</body>
</html>
Obviously, you would need to replace my project_site_id variable with your project_site.id variable.

Related

Local storage and window.location.href.replace

I and my course mate are trying to write a code where when the order button is clicked it should save on local storage and redirect to an order page.
So far when we click on order it is not registered in the application/local storage section of the google developer tool and thus does not redirect to a new page.
We put an eventlistener to show a console.log for when we click, just to be sure the buttons are in order(this part is not important).
We also used an online javascript validator to eliminate typos and errors.
Also do we need any specific code on the order.html file to interface with local storage?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>grc</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>Groceries</li>
<li>Contact</li>
</ul>
</nav>
</header>
<main>
<aside><img class="imgclass1" src="images/rounded logo.png" alt="Grocer Nigeria"></aside>
<article class="preinventory">
<section class="columns-desktop">
<div class="inventory">
<img class="sales" src="images/tomato.jpg" alt="Tomato"/>
<div class="columns">
<div class="title">Tomato</div>
<div class="Price">$100</div>
</div>
<p class="Desc"> Our Tomato2</p>
<button data-order="Tomato2">Order</button>
</div>
<div class="inventory">
<img class="sales" src="images/tomato.jpg" alt="Tomato"/>
<div class="columns">
<div class="title">Tomato</div>
<div class="Price">$100</div>
</div>
<p class="desc"> Our Tomato</p>
<button data-order="Tomato">Order</button>
</div>
</section>
</article>
</main>
<footer>
<nav>
<ul>
<li>Home</li>
<li>Groceries</li>
<li>Contact</li>
</ul>
</nav>
</footer>
<script type="text/javascript">
window.addEventListener("DOMcontentLoaded", function(e){
const orderButtons= document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button){
button.addEventListener("click",function(e){
const button= e.currentTarget;
const container= button.parentNode;
const order={
id:button.getAttribute("data-order"),
title: container.querySelector(".title").innerText,
price1: container.querySelector(".Price").innerText,
desc:container.querySelector(".desc").innerText
};
localStorage.setItem('order', JSON.stringify(order));
const url = window.location.href.replace("grc.html","order.html");
window.location.href = url;
});
});
});
window.addEventListener("DOMcontentLoaded", function(e){
console.log("The page is loaded.");
});
const orderButtons= document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button){
button.addEventListener("click", function(e){
console.log("The button was clicked.");
});
});
</script>
</body>
</html>
**Below is what I see when I run the live server**
<!-- Code injected by live-server -->
<script type="text/javascript">
// <![CDATA[ <-- For SVG support
if ('WebSocket' in window) {
(function() {
function refreshCSS() {
var sheets = [].slice.call(document.getElementsByTagName("link"));
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < sheets.length; ++i) {
var elem = sheets[i];
head.removeChild(elem);
var rel = elem.rel;
if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
}
head.appendChild(elem);
}
}
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + '/ws';
var socket = new WebSocket(address);
socket.onmessage = function(msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
console.log('Live reload enabled.');
})();
}
// ]]>
</script>
</body>
</html>
The issue here is that the event DOMContentLoaded does not fire.
Here is how I have used the load event instead; for redirection, I have simply used URL search params (because I don't know what your other html file looks like) although you may use your other html document instead.
The snippet is below
However note: Stackoverflow will not allow the JavaScript to run, and will throw a securityError. To run this code you must save it on your computer or use a jsFiddle
function continue_ordering() {
alert("Now continue with order");
};
window.addEventListener("load", function(e) {
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
button.addEventListener("click", function(e) {
const button = e.currentTarget;
const container = button.parentNode;
const id = button.getAttribute("data-order");
const order = {
id,
title: container.querySelector(".title").innerText,
price1: container.querySelector(".price").innertext,
desc: container.querySelector(".desc").innerText
};
localStorage.setItem("order-" + id, JSON.stringify(order));
window.location.search = "?ordering=true&order-id=" + id;
});
});
});
window.addEventListener("load", function(e) {
if (window.location.search.search("ordering=true") != -1) {
console.log("User is ordering");
const params = new URLSearchParams(location.search)
const id = params.get("order-id");
if (!id || id == null) throw "There is no order id, error. Remove the ?ordering=true from the url and try again.";
const order_info = JSON.parse(localStorage.getItem("order-" + id));
if (!order_info) throw "Order information is not present: try ordering again. Remove the ?ordering=true from the url";
console.log("Order info is:\n", order_info);
document.getElementById("ordering").removeAttribute("hidden");
return;
};
document.getElementById("make-order").removeAttribute("hidden");
});
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
button.addEventListener("click", function(e) {
console.log("The button was clicked.");
});
});
<div id="make-order" hidden>
<button data-order="test">Order</button>
<div class="title">This is the title</div>
<div class="price">130 USD</div>
<div class="desc">Lorem</div>
</div>
<div id="ordering" hidden>
<h1>
You are ordering.
<br> Choose
Stop ordering Or Continue with order
</h1>
</div>
The DOMcontentLoaded event has already fired by the time that code hooks it.
Check this post;
Code inside DOMContentLoaded event not working

How to run JavaScript in WebStorm

I'm new at this so apologies in advance if I'm missing something obvious, but I'm not able to figure out how to run JavaScript in WebStorm. The WebStorm documentation says to simply open the HTML file in the browser, but that doesn't seem to work. For what it's worth, everything is working up on codepen.io.
Here's the HTML (for a simple weather app):
<body>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<div class="container-fluid">
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<div class="white-box text-center">
<span>Weather where you are:</span>
<div class="loc"></div>
<div class="weather"></div>
<div class="temp"></div>
<br>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</body>
And here's the script (still in draft, as it needs to be expanded to, among other things, link to images covering all values for 'weather'):
$(document).ready(function() {
$( window ).on("load", function(){
$.getJSON("http://ip-api.com/json", function(json) {
var json;
json = JSON.stringify(json);
var obj = JSON.parse(json);
var latitude = obj.lat;
var longitude = obj.lon;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&appid=74a6725c2ca6f1342464bb9005bf0b63", function(json) {
var json;
json = JSON.stringify(json);
var obj = JSON.parse(json);
var loc = obj.name;
var weather = obj.weather[0].description;
var tempInCelsius = obj.main.temp - 273.15;
var tempInCelsiusString = tempInCelsius.toFixed(1) + " &#8451";
var tempInFahrenheit = obj.main.temp * 9/5 - 459.67;
var tempInFahrenheitString = tempInFahrenheit.toFixed(1) + " &#8457";
var tempStringCombined = tempInCelsiusString + " | " + tempInFahrenheitString;
$(".loc").html(loc);
if(weather === "haze"){
weather = "<img src='https://cdn3.iconfinder.com/data/icons/chubby-weather/440/fog-512.png'>";
}
$(".weather").html(weather);
$(".temp").html(tempStringCombined);
});
});
});
});
Many thanks in advance for any help!
Select the tab of html file(say index.html), and click in the menu Run > Run... and select index.html.

Changing text by calling javascript

im trying to change a line of text if a link is clicked, however it doesnt seem to be calling my script to change it.
<script >
var paragraphToChange = document.getElementById("q1");
paragraphToChange.innerHTML ="Quotation is by:" + Antole France
</script>
<div id="body">
<p>javascript.html - JavaScript page</p>
<a href id="q1">Quotaion is by:</a>
</div>
What you're trying to accomplish is probably something like this:
HTML
<div id="q1">
<a onClick="javascript:clickFunction()">Quotation is by</a>
</div>
JavaScript
clickFunction = function() {
document.getElementById("q1").innerHTML = "<a href='http://www.quotationspage.com/quote/1463.html'>Antole France</a>";
}
JSFiddle
Sir you have to set the value of "newValue" to the quotation.
var newValue = '"Quotation is by:" + Antole France'
paragraphToChange.innerHTML = newValue;
You are missing the click event on the Html tag. Hence, this paragraphToChange.innerHTML ="Quotation is by:" + Antole France"
never gets call.
Why don't you start with this example first:
<p id="display"></p>
<button onclick="displayBob">Bob</button>
<button onclick="displayTom">Tom</button>
<script>
displayBob = function ()
{
document.getElementById("display").innerHTML = "Hello Bob";
}
displayTom = function ()
{
document.getElementById("display").innerHTML = "Hello Tom";
}
</script>

Pass URL Parameters from one page to another

Trying to do the following:
Store params from url, i.g. mydomain.com/page.html?cid=123456
If a user clicks on a button (they have a class of .btn-cta) it will take the params ?cid=123456 and add them to the new page those buttons link to /tour.html
I'm currently doing 1/2 of that with passing the params to an iframe on the page, now I need to get the above part working:
var loc = window.location.toString(),
params = loc.split('?')[1],
iframe = document.getElementById("signupIndex"),
btn = $('.btn-cta');
iframe.src = iframe.src + '?' + params;
Here's how I'd do it using jquery:
$('.btn-cta').each(function(i, el){
let $this = $(this); // only need to create the object once
$this.attr({
href: $this.attr("href") + window.location.search
});
});
And in Vanilla ES2015
document.querySelectorAll('.btn-cta')
.forEach(el => el.attributes.href.value += window.location.search);
This takes all the elements that have class .btn-cta and appends the page query string to each of their href attributes.
So if the page url is `http://domain/page.html?cid=1234
Tour
becomes
Tour
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() {
var loc = window.location.href;
var params = loc.split('?')[1];
$(".btn-cta").click(function(){
window.open("tour.html?"+params,'_self',false);
});
});
</script>
</head>
<body>
<button type="submit" class="btn-cta">Click Me</button>
</body>
</html>

Issue trying to get website to work - possible issue with my html code?

SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Categories

Resources