i'm try use Ajax send correctAnswers to postgresql with Django but it error.
I don't know where I missed it.
function checkAnswers() {
window.scrollTo(0, 0);
var correctAnswers = 0;
for (var i = 0; i < questions.length; i++) {
var radios = document.getElementsByName("question" + (i + 1));
var questionCol = document.getElementsByClassName("col-12")[i];
var isCorrect = false;
for (var j = 0; j < radios.length; j++) {
if (radios[j].value == questions[i].correctAnswer && radios[j].checked) {
correctAnswers++;
isCorrect = true;
break;
}
}
document.getElementById("result").innerHTML =
"คุณได้คะแนน " + correctAnswers + " / " + questions.length;
var backButton = document.createElement("input");
backButton.setAttribute("type", "button");
backButton.setAttribute("value", "กลับไปหน้าหลัก");
backButton.setAttribute("class", "btn btn-primary center1");
backButton.setAttribute("onclick", "location.href='User-page.html'");
document.getElementById("quizForm").appendChild(backButton);
$.ajax({
url: "/submit_quiz/",
type: "POST",
data: { correctAnswers: correctAnswers },
success: function (response) {
console.log("ส่งค่าไป data base สำเร็จ");
},
});
}
It has no ajax response.
Related
I want to make something awesome for Bootstrap 5.
As I search for week now, there aren't many good Tabs-responsive tabs solutions for Bootstrap 5 and most of them are not really good solution for mobile phones.
But in my search I encountered this one: https://codepen.io/Ayn_/pen/xdVBVg
https://github.com/Aynn/Bootstrap-Responsive-Tabs
So far my try with bs5: https://codepen.io/xkpx/pen/ExWXKRy
How can I convert this to work with bs5?
$(document).ready(function() {
rTab();
});
$(window).resize(function() {
rTab_resize();
});
function rTab()
{
$('.nav-tabs').each(function() {
var li = [];
var le = [];
var ddtab_w;
var currentw = $(this).outerWidth();
for(var i = 0; i < $(this)[0].children.length; i++)
{
li.push($(this)[0].children[i].outerHTML);
le.push($(this)[0].children[i].offsetWidth);
if(i == $(this)[0].children.length-1)
{
//$(this)[0].children[i].innerHTML = "<a href='#' data-toggle='tab'> Tab ("+ (i+1) +") <span class='caret'></span></a></a>";
ddtab_w = $(this)[0].children[i].offsetWidth;
}
}
var total_tabs = $(this)[0].children.length;
var wTracker = 0;
var tabs;
$(this).html('');
for(var i = 0; i < li.length; i++)
{
if((le[i] + wTracker) <= currentw)
{
wTracker += le[i];
tabs = i;
if (i == li.length-1)
{
for(var i = 0; i < li.length; i++)
{
$(this).append(li[i]);
}
}
} else {
i = li.length-1;
while(ddtab_w + wTracker >= currentw)
{
wTracker -= le[tabs--];
}
if(tabs < 0) { tabs = 0; }
for(var x = 0; x < tabs; x++)
{
$(this).append(li[x]);
}
var dropdown_tabs = ddTab(total_tabs-tabs, "Tabs");
$(this)[0].appendChild(dropdown_tabs[0]);
wTracker += $(this)[0].children[$(this)[0].children.length-1].offsetWidth;
while(tabs<li.length)
{
dropdown_tabs[1].innerHTML += li[tabs++];
}
}
}
if($(this)[0].children[$(this)[0].children.length-1].classList[1] == "pull-right")
{
isActive(dropdown_tabs, $(this)[0].children[$(this)[0].children.length-1]);
}
if($(this)[0].children.length == 1)
{
dropdown_tabs[0].style.paddingLeft = "10px";
dropdown_tabs[0].style.marginRight = "-10px";
dropdown_tabs[0].style.textAlign = "center";
dropdown_tabs[0].style.position = "relative";
dropdown_tabs[0].style.width = "100%";
dropdown_tabs[0].setAttribute("class","dropdown pull-right active");
dropdown_tabs[1].style.left = "7px";
dropdown_tabs[2].data = dropdown_tabs[1].children[0].innerText + " (" + dropdown_tabs[1].children.length + ")";
$(dropdown_tabs[1]).click(function() {
dropdown_tabs[2].data =event.target.text + " (" + dropdown_tabs[1].children.length + ")";
});
}
});
}
function rTab_resize()
{
reset();
rTab();
}
function reset()
{
$('.nav-tabs').each(function() {
if($(this)[0].children[$(this)[0].children.length-1].classList[1] == "pull-right")
{
var drop_down_tab = $(this)[0].children[$(this)[0].children.length-1].children[1];
var initial_value = drop_down_tab.children.length;
for(var i = 0; i < initial_value; i++)
{
$(this).append(drop_down_tab.children[0]);
}
$(this)[0].children[$(this)[0].children.length-(1+initial_value)].remove();
}
});
}
function ddTab(total_dropdown, tabName)
{
var n_li = document.createElement("li");
n_li.setAttribute("class","dropdown pull-right");
n_li.style.position = "relative";
n_li.style.right = "13px";
var n_a = document.createElement("a");
n_a.setAttribute("class","dropdown-toggle");
n_a.setAttribute("data-toggle","dropdown");
n_a.setAttribute("href","#");
var n_sp = document.createElement("span");
n_sp.setAttribute("class","caret");
var n_ul = document.createElement("ul");
n_ul.setAttribute("class","dropdown-menu");
var n_tx = document.createTextNode(tabName + " (" + total_dropdown + ")");
n_a.appendChild(n_tx);
n_a.appendChild(n_sp);
n_li.appendChild(n_a);
n_li.appendChild(n_ul);
return [n_li, n_ul, n_tx];
}
function isActive(dropdown_tabs, child)
{
for (var i = 0; i < dropdown_tabs[1].children.length; i++)
{
if(dropdown_tabs[1].children[i].classList[0] == "active")
{
child.setAttribute("class","dropdown pull-right active");
}
}
}
I'm currently developing a Chrome extension that is supposed to scrape my Internet activity. So first of all here is my JS code (I only have this file without counting the manifest.json, the jquery.js and the logo) :
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes
}
chrome.tabs.onUpdated.addListener(function (tabId, info) {
if(info.status === 'complete') {
chrome.tabs.executeScript({
code: "document.documentElement.outerHTML"
}, function(result) {
if (!chrome.runtime.lastError) {
var el = document.createElement( 'html' );
el.innerHTML = result[0];
var scraping = [
{
"url": "",
"title": "",
"text": "",
"ranking_word": {},
"a": [],
"img": [],
"html": ""
}
]
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
scraping[0]["url"]= tabs[0].url;
});
var head = el.getElementsByTagName('head');
for (var i = 0; i < head.length; i++) {
scraping[0]["title"] = head[i].getElementsByTagName('title')[0].innerHTML;
}
var a = el.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
scraping[0]["a"].push(a[i].href);
}
var img = el.getElementsByTagName('img');
for (var i = 0; i < img.length; i++) {
scraping[0]["img"].push(img[i].src);
}
var txt = "";
var text_in_body = [];
var body = el.getElementsByTagName('body');
for (var i = 0; i < body.length; i++){txt += body[i].textContent;}
txt = txt.split("\n");
for (var i = 0; i < txt.length; i++){txt[i] = txt[i].split(" ")}
for (var i = 0; i < txt.length; i++) {for (var a = 0; a < txt.length; a++){if (txt[i][a] == " " || txt[i][a] == "" || txt[i][a] == "," || txt[i][a] == "." || txt[i][a] == "!" || txt[i][a] == "?" || txt[i][a] == ";"){delete txt[i][a];}}}
for (var i = 0; i < txt.length; i++) {text_in_body = text_in_body.concat(txt[i])}
scraping[0]["text"] = text_in_body.join(" ");
ranking_word = {}
for (var i = 0; i < text_in_body.length; i++) {
ranking_word[text_in_body[i]] = getAllIndexes(text_in_body, text_in_body[i]).length;
}
scraping[0]["ranking_word"] = ranking_word;
scraping[0]["html"] = result;
var response = $.get("https://api.myjson.com/bins/1e0ybo", function(data, textStatus, jqXHR) {
if (textStatus == "success") {
console.log("%cSuccess: Getting Data", 'background-color: #8cc2e6; color: #000');
console.log(response.responseJSON);
console.log(scraping);
var newJSON = Object.assign(response.responseJSON, scraping);
console.log(newJSON)
$.ajax({
url:"https://api.myjson.com/bins/1e0ybo",
type:"PUT",
data:JSON.stringify(newJSON),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data, textStatus, jqXHR){
console.log("%cSuccess: Uploading Data", 'background-color: #8cc2e6; color: #000')
}
});
}
});
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
On lines 72, 73 and 75 I put console.log() to check that all variables had the values they should have, except that it's not the case (as you can see on the console screenshot below) .
I don't understand why my response.responseJSON value (I also tried with data but it gave me the same thing) and my scraping variable are equal, they shouldn't be. I checked that my file where I get the data didn't have those values but no...
Anyone have any idea how to fix this?
The screenshot
$('#createFields').click(function () {
for (var i = 0; i <= numberOfFields; i++) {
fieldsArray[i] = {};
console.log(fieldsArray);
};
});
i get the numberOfFields variable from a select box
$("body").on("change","input:checkbox",
function () {
if ($(this).prop('checked')) {
var val = $(this).prop('value');
addColumns(val);
}
else {
console.log("deleting...")
singleArray=singleArray.splice(singleArray.length, newArray.length);
InitData();
}
}
);
I call the addColumns function each time a checkbox is checked.
function addColumns(val) {
var defer = $.Deferred();
newArray = [];
str = [];
str.push(val);
var url = ListJoin.appweburl + "/_api/SP.AppContextSite(#target)/Web/Lists/getbytitle('" + selectedList + "')/items?$select=" + str + "" +
"&#target='" + ListJoin.hostweburl + "'";
ListJoin.executor.executeAsync({
url: url,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
var jsonObject = JSON.parse(data.body);
var response = jsonObject.d.results;
for (var i = 0, len = response.length; i < len; i++) {
var tu = [];
var keys = Object.keys(response[i]);
//Skip keys[0] because it's always metadata
for (var j = 1; j < keys.length; j++) {
var key = keys[j];
var val = [response[i][key]];
console.log("bujar" + val);
newArray.push(val);
}
}
fieldsArray[1].push(newArray);
can not push neither concat newArray=['BBB','MMM','CCC'] to the an array of the fieldsArray array
InitData();
defer.resolve();
},
error: function (data) {
console.log(data);
defer.reject();
}
});
return defer;
}
I am a little bit confused about the jQuery AJAX method, the method is calling when I change something on the screen. May there be some problem asynchronous task?
This is inside of the jQuery click function:
$("#divModularFenster").html(html).dialog({
modal: true,
buttons: {
"OK": function () {
getJSONObjektList(function (jsonObjekt) {
console.log("Callback: " + JSON.stringify(jsonObjekt));
// other code
var pj = JSON.stringify(jsonObjekt);
$.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pj,
dataType: "json",
processData: false,
url: "http://localhost:53658/PostDatenZumWebservice",
success: function (data) {
alert("Post erfolgreich: ");
}
});
});
}
}
});
This method should be call before I send the data to my service:
function getJSONObjektList(callback) {
var jsonObjekt = {};
jsonObjekt.ObjektId = [];
jsonObjekt.Selected = [];
doc = Qv.GetCurrentDocument();
doc.GetAllObjects(function (objects) {
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
var id = obj.id;
var caption = obj.caption;
var type = obj.type;
var my = obj.my;
//liste alle verfuegbaren Objekte auf
jsonObjekt.ObjektId.push(id);
if (type === "Statusbox") {
doc.GetObject(id, function () {
var statusboxInhalt = this.Data.Rows;
var utilJSONObjekt;
for (var j = 0; j < statusboxInhalt.length; j++) {
utilJSONObjekt = {};
utilJSONObjekt.SelectedObjektId;
utilJSONObjekt.SelectedObjektWerte = [];
var inhalt = statusboxInhalt[j];
console.log("Name: " + inhalt[0].text + " Wert: " + inhalt[2].text);
var valAr = inhalt[2].text.split(",");
for (var k = 0; k < valAr.length; k++) {
//liste alle verfuegbaren Objekte auf
utilJSONObjekt.SelectedObjektWerte.push($.trim(valAr[k]));
}
jsonObjekt.Selected.push(utilJSONObjekt);
//callback erst starten, wenn alle Elemente durchlaufen worden sind
if (j === (statusboxInhalt.length - 1)) {
callback(jsonObjekt);
}
}
});
}
}
});
}
Some ideas?
I've json like this. in that json there is object name tipe and I want to sum act_qty1, act_val1, acvqty, acvval, budqty, budval, cm_val1, cm_val2, cm_val3 in the same tipe(e.g. sum them where their tipe is "ESL"). How to sum that in javascript? can it done with loop?
here is what I've made so far:
function detail(kodenegara, koderesult)
{
$.mobile.showPageLoadingMsg();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.greenfields.co.id:502/Service1.svc/"+kodenegara,
dataType: "json",
success:function(data){
var result = koderesult;
var details = "";
for (i = 0; i < data[result].length; i++){
$("#"+data[result][i].tipe).empty();
}
for (i = 0, types={} ; i < data[result].length; i++){
$("#"+data[result][i].tipe).append("<tr>"+
"<td>"+data[result][i].mc+"</td>"+
"<td>"+data[result][i].value3+"</td>"+
"<td>"+data[result][i].value2+"</td>"+
"<td>"+data[result][i].value1+"</td>"+
"<td>"+data[result][i].avgqty+"</td>"+
"<td>"+data[result][i].budqty+"</td>"+
"<td>"+data[result][i].budval+"</td>"+
"<td>"+data[result][i].acvqty+"</td>"+
"<td>"+data[result][i].acvval+"</td>"+
"</tr>").trigger('create');
//----------------------------------//
// HERE IS what I've made TO SUM THE VALUES //
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
for(i = 0; i < data[result].length; i++) {
if(data[result][i].tipe == 'ESL')
{
//how to summing data[result][i].cm_val3 where data[result][i].tipe == 'ESL'
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
}
}
}
//show the page
$.mobile.changePage("#detail_"+kodenegara, "slide", false, true);
},
error: function () {
alert("ERROR");
}
});
}
I don't know how to write the right looping for summing the value while tipe is "ESL" (or "ESL1L" or "WHP" or else). if I use this:
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
that only sum the last array. how to write the right looping to sum with that condition?
Here come a working fiddle
http://jsfiddle.net/xKJn8/1/
var SumByTipe = {};
for(i in data.GetReportIdResult){
var currtipe = data.GetReportIdResult[i].tipe;
if (currtipe){
if (currtipe in SumByTipe){
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
SumByTipe[currtipe][j + '_total'] += parseFloat(data.GetReportIdResult[i][j]);
}
}
}else{
var firstSum = {};
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data.GetReportIdResult[i][j]);
}
}
SumByTipe[currtipe]=firstSum;
}
}
}
console.debug(SumByTipe);
That should do the trick :
var sum_cm_val3=0;
for (var i=0;i<data[result].length;i++) {
if (data[result][i].tipe == "ESL") {
var cm_val3 = data[result][i].cm_val3;
if (parseInt(cm_val3)==cm_val3) {
sum_cm_val3 += parseInt(cm_val3);
}
}
}