Manage bootstrap modal with javascript - javascript

Good evening guys,
I program a symfony website by using webpack encore bundle to manage js & css.
I used to work with jquery which is quite simple, but would like to evolve to pure javascript.
I try to translate the following code in javascript :
<html>
<button class="exercice-class" data-id="x">exercice button</button>
</html>
when an user click on the "exercice button", i want to get the value of data-id to generate an URL
<script>
$(function() {
$('.exercice-class').on("click", function(e) {
e.preventDefault();
let id = $(this).data("id");
let url = "../exercice-class/" + id + "/";
$.get(url, function(data){
$(".container-fluid").append(data);
$('#showModal').modal('show');
});
});
});
</script>
Then i get the content of the URL and add it to the modal window
What I want to do first is to open a modal window by using a variable as a parameter.
Second question, I would like to get data from a modal (using a form) and send them to a database. I read things about asynchronous request by it's not really clear for me, i'm looking for something close to ajax request.
Thank you in advance.!
Juuk

here is a small example, you can test it
var classbutton = document.querySelector('.exercice-class');
classbutton.addEventListener('click', (e) => {
e.preventDefault();
let id = element.getAttribute('id');
let url = "../exercice-class/" + id + "/";
let requete = new XMLHttpRequest();
requete.open('GET', url);
requete.send();
requete.onload = function() {
if (requete.readyState === XMLHttpRequest.DONE) {
if (requete.status === 200) {
let reponse = requete.response;
document.querySelector('.container-fluid').append(reponse);
document.querySelector('#showModal').showModal();
}
else {
}
}
}
});

Thanks for your response! i tried your code and work on it...
This is what i did :
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url);
httpRequest.send();
httpRequest.onload = function (){
if (httpRequest.readyState === XMLHttpRequest.DONE){
if (httpRequest.status === 200){
let httpResponse = httpRequest.response;
console.log(httpResponse);
}
}
}
It seems that fetch is a newer way to work with data since vanilla.
I did the same thing we tried to do before and i succeeded to get data.
document.addEventListener('click', function (event) {
if (!event.target.closest('.exercice-class')){
return null;
}
else {
event.preventDefault();
let exercice = event.target.closest(".exercice-class");
let dataAttribute = exercice.getAttribute('data-id');
let url = "../exercice-class/" + dataAttribute + "/";
fetch(url)
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data)
})
.catch(function (error) {
console.log(error);
});
}
});
In reality i get the same result with the two solutions.. the problem is that i get "data" i can't exploit...
Imagine i use the second example :
if i try to do :
.then(function (data) {
let exerciceData = data.getElementById("#adiv");
document.querySelector('container-fluid').append(exerciceData);
document.querySelector('showModal').show();
"exerciceData" can't be used.
Modal just don't open.
Thank for your help.

Related

Change name of card on Trello with API by Javascript

I have this code in Javascript to modify the name of a Trello card through its API, and I do not get it, any ideas?
Documentation API Trello: https://developers.trello.com/v1.0/reference#cardsid-1
Code:
var onAuthorize = function() {
updateLoggedIn();
$("#output").empty();
Trello.members.get("me", function(member){
$("#fullName").text(member.fullName);
var id= "5ab7c3c631a2019c50b701c8";
//Change name
Trello.put('/boards/me/cards/5ab7c3c631a2019c50b701c8/name?value=nombrecito',function () {alert("funciona bien")}, function(err) {alert( "mal")});
});
};
var updateLoggedIn = function() {
var isLoggedIn = Trello.authorized();
$("#loggedout").toggle(!isLoggedIn);
$("#loggedin").toggle(isLoggedIn);
};
var logout = function() {
Trello.deauthorize();
updateLoggedIn();
};
Trello.authorize({
interactive:false,
success: onAuthorize
});
$("#connectLink")
.click(function(){
Trello.authorize({
type: "popup",
success: onAuthorize
})
});
$("#disconnect").click(logout);
The error I get is [object Object]
I have also tried with this URL:'cards/5ab7c3c631a2019c50b701c8/name?value=nombrecito'
It looks like your Trello.put URL is a little off.
Fix the Trello.put with...
Trello.put("/boards/mecards/5ab7c3c631a2019c50b701c8/name?value=nombrecito", function () {}, function(err) {alert(err)});
Have you tried the live example on the documentation page? It's not that complicated and something like this.
const API_KEY = 'your key';
const TOKEN = 'your token';
let id = 'your trello card id';
let newName = 'a new name what you want';
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("PUT", "https://api.trello.com/1/cards/"+id+"?name="+newName+"&key="+API_KEY+"&token="+TOKEN);
xhr.send(data);
I've tested with my own cards and it works very well.

Avoid identical client ajax request on refresh

I would like to test if the ajax request is identical so it can be aborted or some other alert action taken?
In reality clients can change the request via a few form elements then hit the refresh button.
I have made a poor attempt at catching the identical request. Need to keep the timer refresh functionality.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var current_request_id = 0;
var currentRequest = null;
var lastSuccessfulRequest = null;
function refreshTable() {
$('#select').html('Loading');
window.clearTimeout(timer);
//MY CATCH FOR DUPLICATE REQUEST NEEDS WORK
if (lastSuccessfulRequest == currentRequest)
{
//currentRequest.abort();
alert('Duplicate query submitted. Please update query before resubmission.');
}
var data = {
"hide_blanks": $("#hide_blanks").prop('checked'),
"hide_disabled": $("#hide_disabled").prop('checked'),
};
json_data = JSON.stringify(data);
current_request_id++;
currentRequest = $.ajax({
url: "/calendar_table",
method: "POST",
data: {'data': json_data},
request_id: current_request_id,
beforeSend : function(){
if(currentRequest != null) {
currentRequest.abort();
}
},
success: function(response) {
if (this.request_id == current_request_id) {
$("#job_table").html(response);
$("#error_panel").hide();
setFixedTableHeader();
}
},
error: function(xhr) {
if (this.request_id == current_request_id) {
$("#error_panel").show().html("Error " + xhr.status + ": " + xhr.statusText + "<br/>" + xhr.responseText.replace(/(?:\r\n|\r|\n)/g, "<br/>"));
}
},
complete: function(response) {
if (this.request_id == current_request_id) {
$("#select").html("Refresh");
window.clearTimeout(timer);
stopRefreshTable();
window.refreshTableTimer = window.setTimeout(refreshTable, 10000);
lastSuccessfulRequest = currentRequest;
}
}
});
}
//TIMER STUFF TO refreshTable()
//THIS SECTION WORKS FINE
var startDate = new Date();
var endDate = new Date();
var timer = new Date();
function startRefreshTable() {
if(!window.refreshTableTimer) {
window.refreshTableTimer = window.setTimeout(refreshTable, 0);
}
}
function stopRefreshTable() {
if(window.refreshTableTimer) {
self.clearTimeout(window.refreshTableTimer);
}
window.refreshTableTimer = null;
}
function resetActive(){
clearTimeout(activityTimeout);
activityTimeout = setTimeout(inActive, 300000);
startRefreshTable();
}
function inActive(){
stopRefreshTable();
}
var activityTimeout = setTimeout(inActive, 300000);
$(document).bind('mousemove click keypress', function(){resetActive()});
</script>
<input type="checkbox" name="hide_disabled" id="hide_disabled" onchange="refreshTable()">Hide disabled task<br>
<br><br>
<button id="select" type="button" onclick="refreshTable();">Refresh</button>
I'd use the power of .ajaxSend and .ajaxSuccess global handlers.
We'll use ajaxSuccess to store a cache and ajaxSend will try to read it first, if it succeeds it will trigger the success handler of the request immediately, and abort the request that is about to be done. Else it will let it be...
var ajax_cache = {};
function cache_key(settings){
//Produce a unique key from settings object;
return settings.url+'///'+JSON.encode(settings.data);
}
$(document).ajaxSuccess(function(event,xhr,settings,data){
ajax_cache[cache_key(settings)] = {data:data};
// Store other useful properties like current timestamp to be able to prune old cache maybe?
});
$(document.ajaxSend(function(event,xhr,settings){
if(ajax_cache[cache_key(settings)]){
//Add checks for cache age maybe?
//Add check for nocache setting to be able to override it?
xhr.abort();
settings.success(ajax_cache[cache_key(settings)].data);
}
});
What I've demonstrated here is a very naïve but functional approach to your problem. This has the benefit to make this work for every ajax calls you may have, without having to change them. You'd need to build up on this to consider failures, and to make sure that the abortion of the request from a cache hit is not getting dispatched to abort handlers.
One valid option here is to JSON.Stringify() the objects and compare the strings. If the objects are identical the resulting serialised strings should be identical.
There may be edge cases causing slight differences if you use an already JSONified string directly from the response so you'll have to double check by testing.
Additionally, if you're trying to figure out how to persist it across page loads use localStorage.setItem("lastSuccessfulRequest", lastSuccessfulRequest) and localStorage.getItem("lastSuccessfulRequest"). (If not, let me know and I'll remove this.)

XMLHttpRequest - get value from URL and write it in a div

I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation

Apply JS onto table, which is created after page is loaded

I have got an html page, where you can put text into a textarea, click a button and then it creates an html table.
Problem is, that i am using a JS file to make my table sortable, but this JS file is not applied to tables that are created after the page itself is created.
How can i call the JS file again after the button is clicked and the table created? Or is there any other way to apply the JS file to the new table?
My problem seems to be like this problem:
Apply jquery propieties on new element created after the page is loaded
But i can't use JQuery, is there any way without it?
Example for a created table:
<div id="artikelnr2">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="table.css">
<script src="java.js"></script>
<div class="datagrid"><table class="sortable">
<thead><tr><th>Nummer</th><th>Nummer</th><th>Bezeichnung</th><th>Bemerkungen</th></tr></thead>
<tbody>
<tr><td>897-251</td><td>00.702.07803.7</td><td>5G2</td><td>-</td></tr><tr><td>897-1051</td><td>00.702.0306.7</td><td>5G1</td><td>-</td></tr><tr><td>897-1651</td><td>00.702.0307.3</td><td>5G1U</td><td>-</td></tr><tr><td>897-341</td><td>00.702.0323.9</td><td>5G2.5</td><td>-</td></tr>
</tbody>
</table></div>
</div>
I am using sorttable.js from this page:
http://www.kryogenix.org/code/browser/sorttable/
JavaScript which is called after button is clicked (pastes the content of another page into an exisiting div container):
function getOutput(url) {
var file = selectedValue()+".csv";
var value = document.getElementById("artikelnr").value;
<!---Leerzeichen entfernen-->
value = myTrim(value);
var url = url || "verarbeitung.php?eingabe="+value+"&eingabe2="+file ;
getRequest(
url, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('artikelnr2');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('artikelnr2');
container.innerHTML = responseText;
tempResult = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
So this is a suggestion as a major part of your code is not available.
In your existing code, where you create the new table, you need to add/run the following:
sorttable.makeSortable(newTableObject);
The newTableObject reference you either can get straight from your existing code or by calling document.getElementById(idOfTheTableIJustAdded) after your added the new table to the DOM.
Src: http://www.kryogenix.org/code/browser/sorttable/
Update after question edit:
In this script function you should be able to do like this
function drawOutput(responseText) {
var container = document.getElementById('artikelnr2');
container.innerHTML = responseText;
//tempResult = responseText;
var newTableObject = container.querySelector(".sortable");
sorttable.makeSortable(newTableObject);
}

bottle.py: sending data via javascript

Basically, I want to have an interactive button on my website, that, when clicked, sends some data to the server in order to be checked and display the response (without form sending / page reload).
I thought it would be something like:
function checkData()
{
var req = new XMLHttpRequest();
var conf = document.getElementById('my_text_area').value;
req.open("GET", 'check_data', true);
req.onreadystatechange = function ()
{
var pre = document.getElementById('check_data_out');
pre.innerHTML = req.responseText;
}
req.send(conf);
return false;
}
And on the server side:
#get('/check_data')
def check_data():
# Process the content and answer something...
content = str(request.is_ajax) + ' - ' + str(request.GET) + ' - ' + str(request.POST)
return content
But this obviously doesn't work. Either it is not the right way to send data via javascript or not the right way to access it in bottle.py.
Showing me how it works is highly appreciated.
You can use dojo for client side logic.
var button = dojo.byId('button_id'); // button_id refers to the id of the button you want to click
dojo.connect(button,'onclick',dojo.xhrGet({
url: '/check_data',
handleAs : 'text',
load : function(response){
dojo.byId('button_id').innerHTML = response;
}
}));

Categories

Resources