JavaScript success message disappear - javascript

HTML button:
<button type="submit" class="btn btn-default" id="addBtn" onclick="addfunction();">Add</button>
addfunction() code:
var title = document.getElementById("TitleInput").value;
var ID = firebase.database().ref().child('emp').push().key;
//upload pic
var filename = selectionfile;
filename = newsID;
var storageRef = firebase.storage().ref(filename);
var uploadTask = storageRef.put(selectionfile);
if (user != null) {
userid = user.uid;
var Dataa = {
ID: ID,
title: title,
};
var updates = {};
updates['/emp/' + ID] = Dataa;
var returnUpdate = firebase.database().ref().update(updates);
if (returnUpdate) {
var mess = document.getElementById("confirm_mess");
mess.setAttribute("class", "bg-success h4");
mess.setAttribute("style", "padding: 1%; margin: 1% 9% 0 35%");
mess.innerHTML = "done";
}
}
}
and this is the validation code
$(function () {
$("#title_span").hide();
var error_title = false;
$("#TitleInput").focusout(function () {
Title_validation();
});
function Title_validation() {
var title = $("#TitleInput").val();
if (title == "") {
$("#title_span").html("wrong input");
$("#title_span").show();
error_title = true;
}
else {
$("#title_span").hide();
}
}
$("#my_form").submit(function () {
error_title = false;
Title_validation();
if (error_title == false) {
return true;
}
else {
return false;
}
});
});
my problem is, when i click the add button, "done" message disappear immediately because the refreshing, i want the message to appear for few second and then refresh the page. how can i do that? knowing that i try to use setTimeout but it does not work.

Change type="submit" to type="button"

If your button has to submit a form remove the type="submit", change the <button> tag to <a> and change your code to the following. You also have to add an ID to your form:
<script>
addfunction() {
var title = document.getElementById("TitleInput").value;
var ID = firebase.database().ref().child('emp').push().key;
if (user != null) {
userid = user.uid;
var Dataa = {
ID: ID,
title: title,
};
var updates = {};
updates['/emp/' + ID] = Dataa;
var returnUpdate = firebase.database().ref().update(updates);
if (returnUpdate) {
var mess = document.getElementById("confirm_mess");
mess.setAttribute("class", "bg-success h4");
mess.setAttribute("style", "padding: 1%; margin: 1% 9% 0 35%");
mess.innerHTML = "done";
}
setTimeout(function () { //wait 5 seconds
document.getElementById(yourForm).submit; //submit your form
}, 5000);
}
}
</script>
OR show the message after everything is send. I think you use a form to submit your data. just add to your <form> action=?done=true
Then you call the script if the variable 'done' is true:
<?php
if (isset($done)) {
echo "<script>your script</script>"; //or do whatever you want if the var is true
}
?>

Related

making a ajax live load

can anyone know how can I make this as an ajax live load?
unfortunately, I have limited acknowledge about javascript/jquery/ajax
simply I want to load the search result on ajax live load
This is my javascript code to load the data but it will refresh the page
I want to not refresh the page and load the data on live load
<script type="text/javascript">
function get_url() {
var urlPrefix = 'https://example.com/home/courses?'
var urlSuffix = "";
var slectedCategory = "";
var selectedLevel = "";
var selectedIelts = "";
var selectedCountry = "";
var selectedPtype = "";
var selectedDtype = "";
var selectedLanguage = "";
var selectedRating = "";
//Get selected category
$('.categories:checked').each(function() {
selectedCategory = $(this).attr('value');
});
// Get selected countries
if($("#country-search-value-unique").val() != 'all'){
selectedCountry = $("#country-search-value-unique").val();
};
if($("#ielts-search-value-unique").val() != 'all'){
selectedIelts = $("#ielts-search-value-unique").val();
};
if($("#ptype-search-value-unique").val() != 'all'){
selectedPtype = $("#ptype-search-value-unique").val();
};
if($("#dtype-search-value-unique").val() != 'all'){
selectedDtype = $("#dtype-search-value-unique").val();
};
if($("#level-search-value-unique").val() != 'all'){
selectedLevel = $("#level-search-value-unique").val();
};
if($("#price-search-value-unique").val() != 'all'){
selectedPrice = $("#price-search-value-unique").val();
};
// Get selected difficulty Level
$('.languages:checked').each(function() {
selectedLanguage = $(this).attr('value');
});
// Get selected rating
$('.ratings:checked').each(function() {
selectedRating = $(this).attr('value');
});
urlSuffix = "category="+selectedCategory+"&&level="+selectedLevel+"&&ielts="+selectedIelts+"&&country="+selectedCountry+"&&ptype="+selectedPtype+"&&dtype="+selectedDtype+"&&language="+selectedLanguage+"&&rating="+selectedRating;
var url = urlPrefix+urlSuffix;
return url;
}
function filter() {
var url = get_url();
window.location.replace(url);
//console.log(url);
}
function toggleLayout(layout) {
$.ajax({
type : 'POST',
url : 'https://example.com/home/set_layout_to_session',
data : {layout : layout},
success : function(response){
location.reload();
}
});
}
function showToggle(elem, selector) {
$('.'+selector).slideToggle(20);
if($(elem).text() === "show_more")
{
$(elem).text('show_less');
}
else
{
$(elem).text('show_more');
}
}
$(document).on('click', '.catparent-label', function(e) {
$(this).next('ul').fadeIn(); $('li.has').removeClass('is-active'); $('ul.tree').addClass('has-selection'); $('ul.tree').find("label").removeClass('is-seleted'); $(this).closest('li').addClass('is-active'); $(this).addClass('is-seleted'); $('ul.tree').find("input[type='checkbox']"); $(this).closest('li').find(".catparent"); $('.BackListDisciplines').show(); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.subcat-label', function(e) {
$('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').find("input[type='checkbox']").prop('checked', !1); $(this).addClass('is-seleted'); $(this).closest('li').find(".subcat"); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.BackListDisciplines', function(e) {
$('li.has').removeClass('is-active'); $('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').removeClass('has-selection'); $('.tree ul').hide(); $('ul.tree').find("input[type='checkbox']"); $('.BackListDisciplines').hide(); StudyFilter()
}
);
</script>

How can i remove duplicate entries in an html table

i'm using socket.io for a chat and stats web app. I have a problem figuring out on how to remove duplicate entries in my html table. The duplicate entries happen only because i fetch the api every time someone sends a message, so every time i fetch the api, the stats appear in the table and the table gets too much data.
var socket = io("ws://localhost:3000/");
document.getElementById("message").addEventListener("keydown", (e) => {
if (e.keyCode == 13) {
e.preventDefault();
setTimeout(() => {
document.getElementById("sendbtn").click();
}, 500);
}
});
window.onbeforeunload = function () {
return "Data will be lost if you leave the page, are you sure?";
};
document.getElementById("message").addEventListener("keydown", (e) => {
if (e.keyCode == 13) {
e.preventDefault();
document.getElementById("userbtn").click();
}
});
var send = () => {
if (
document.getElementById("username").value.length == 17 &&
username.length > 1
) {
socket.emit("message", document.getElementById("message").value);
document.getElementById("message").value = " ";
return false;
} else {
alert("Please enter and submit your steam ID");
}
};
var setusername = () => {
socket.emit("username", document.getElementById("username").value);
};
var stats = [];
socket.on("user", async (user) => {
username = user;
console.log(user);
});
socket.on("stats", (data) => {
var table = document.getElementById("users-table");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var kd = data.kd;
cell1.innerHTML = username;
cell2.innerHTML = kd.toFixed(2);
cell3.innerHTML = data.time.toFixed() + " h";
});
var username = "";
var message = " ";
socket.on("message", (msg) => {
message = msg;
document.getElementById("messages").innerHTML +=
"<span class=username-bx>" +
username +
"</span>" +
":" +
" " +
msg +
"<br>";
});
window.setInterval(function () {
var messagebox = document.getElementById("messages");
messagebox.scrollTop = messagebox.scrollHeight;
}, 50);
For more info you can ask me in the comments.
The fact that the global variable user is set by the socket is a bit weird (I would have expected the user to be part of the response).
Anyway, if you want to only add new messages and stats I would recommend you to work out an id for those (user + msg and user + data.kd? Or whatever will help you to determine that the message is a new one or duplicated) Then maintain a list/set of those. On new msg/stats only add them to your Dom if the id doesn't already exist.

Using jquery validate during form submission

I'm really new at this and I'm encountering an issue where the alert for a ddl is popping up, but in the background the form is still submitting with a blank from the value "" on the 'Select' option
The ddl:
Type
My scripts:
<script type="text/javascript">
function saveCallReport() {
var selectedFranchises = "";
var selectedGroups = "";
var selectedContacts = "";
var selectedTopics = "";
var ID = $('#<%=txtID.ClientID %>').val();
if (ID == '') ID = '0';
var Created = $('#<%=txtCreated.ClientID %>').val();
var Confidential = document.getElementById('<%=chkConfidential.ClientID %>').checked;
var Description = $('#<%=txtDescription.ClientID %>').val();
var Employee = $('#<%=ddlEmployee.ClientID %>').val();
var Priority = $('#<%=ddlPriority.ClientID %>').val();
var Type = $('#<%=ddlType.ClientID %>').val();
// Get Selected Franchises
var LstRight = document.getElementById("<%=lstSelectedFranchises.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedFranchises = selectedFranchises + LstRight.options[i].value + ',';
}
if (selectedFranchises == null)
selectedFranchises = "";
// Get Selected Groups
LstRight = document.getElementById("<%=lstSelectedGroups.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedGroups = selectedGroups + LstRight.options[i].value + ',';
}
if (selectedGroups == null)
selectedGroups = "";
// Get Selected Contacts
LstRight = document.getElementById("<%=lstSelectedContacts.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedContacts = selectedContacts + LstRight.options[i].value + ',';
}
if (selectedContacts == null)
selectedContacts = "";
// Get Selected Topics
LstRight = document.getElementById("<%=lstSelectedTopics.ClientID %>");
for (i = 0; i < LstRight.length; i++) {
selectedTopics = selectedTopics + LstRight.options[i].value + ',';
}
if (selectedTopics == null)
selectedTopics = "";
var obj = {
id: ID,
created: Created,
hqemployee: Employee,
type: Type,
priority: Priority,
confidential: Confidential,
description: Description,
franchises: selectedFranchises,
groups: selectedGroups,
contacts: selectedContacts,
topics: selectedTopics,
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%= ResolveUrl("~/CallReportDetail.aspx/saveCallReport") %>',
data: JSON.stringify(obj),
dataType: "json",
success: function (result) {
$('#txtID').val(result.d);
window.location.replace("/CallReports/Details?Id=" + result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("There was a problem saving the Call Report: " + thrownError);
}
});
return false;
}
var submit = 0;
function CheckDouble() {
if (++submit > 1) {
alert('Saving...');
return false;
}
}
$(function formValid() {
$("[id*=btnSave]").click(function() {
var ddlType = $("[id*=ddlType]");
if (ddlType.val() == "") {
alert("Please select a type!");
return false;
}
});
});
</script>
My submit button:
<td style="padding-left: 720px;">
<asp:LinkButton ID="btnSave" Type="submit" runat="server" Text="Save" OnClientClick="CheckDouble(); return saveCallReport();" UseSubmitBehavior="false" CssClass="btn btn-primary btn-sm"/>
</td>
Can anybody tell me where I may be going wrong? I had a notion that I need a submitHandler, but don't have a clue how to write that into this code.
Ok there's a few issues here.
You should avoid adding OnClientClick and JQuery .click() events on the same button. It's just bad style, and a bit confusing.
You're submitting the data via JQuery ajax, so there's no need for a LinkButton. Just use a normal html button.
Your saveCallReport() function handles the success and failure outcomes all by itself, there's no need to return anything.
The CheckDouble() method will increment the submit value even if the validation fails, so then a subsequent click on the button after you select from the ddl will alert the Saving... message, which is not the intended behavior. You should just add/remove a disabled attribute on the button while it's submitting.
So anyway, here's what I would suggest. The html button:
<button id="btnSave" class="btn btn-primary btn-sm">Save</button>
Wire up the button:
$(document).ready(function() {
$('#btnSave').click(function () {
var ddlType = $("#ddlType");
if (ddlType.val() == "") {
alert("Please select a type!");
return false;
}
$(this).attr("disabled", "disabled");
saveCallReport();
$(this).removeAttr("disabled");
});
});

Javascript trim whitespace on click

I have an email form field. On click, it executes this javascript ...
$(document).on('click', '#add_delegate', function() {
RegistrationHelper.added_delegate = true;
// var button = $(event.target);
var button = $(this);
var uri = button.data('url');
if (typeof uri === 'undefined') {
return false;
}
var input = $('#email_search');
var data = {email:input.val()};
data.text().replace(/ /g,'');
var spinner = $('#delegate_add_spinner');
spinner.css({display:'inline-block'});
$.ajax({type:'POST', url: uri, data:data}).success(function(card) {
var html = $(card);
var data_id = html.attr('data-id');
var existing_elem = $('.mini_addresscard[data-id=' + data_id + ']');
if (existing_elem.length < 1) {
input.popover('hide');
// this is in a seperate timeout because IE8 is so damn stupid; it crashes if run directly
setTimeout(function () {
$('#address_cards').append(html);
var last_card = $('#address_cards div.mini_addresscard').last();
//last_card.get(0).innerHTML = card;
// html.attr("id", 'sdklfjaklsdjf');
last_card.css({display:'none'}).show('blind');
}, 10);
} else {
var background = existing_elem.css('background');
existing_elem.css({'background':'#FFFFAC'});
existing_elem.animate({
'background-color':'#EBEDF1'
}, {
complete: function() {
existing_elem.css({background:background});
}
});
// var border_color = existing_elem.css('border-color');
// existing_elem.css({'border-color':'#EFF038'});
// existing_elem.animate({'border-color':border_color});
}
}).complete(function(data) {
spinner.hide();
}).error(function(data) {
var input = $('#email_search');
input.popover("destroy");
var error = 'Please try again later'; //incase something crazy happens
if(data.status == "422"){
error = 'You cannot add yourself as a supervisor.';
}
if(data.status == "404" ){
error = 'Could not find anyone with that email address.';
}
add_popover(input, error);
input.popover('show');
});
return false;
});
My goal is to trim the whitespace before the AJAX request
So as you can see in the code above I added the line
data.text().replace(/ /g,'');
... but now it renders that button useless. In other words the button does nothing when clicked.
Since you're using jQuery, why not make use of .trim():
This:
var data = {email:input.val()};
data.text().replace(/ /g,'');
Becomes:
var data = {email:$.trim(input.val())};
The trim supposed to remove the spaces at beginning and end of the input:
var input = $('#email_search').val();
input = input.replace(/^\s+/, '').replace(/\s+$/, '');

How to use condition like where Clause in indexdb for browsers

I am using indexdb as it supports all browser. I have successfully added data and got data from indexdb but I want to use where clause condition. Like I have Product Name, Pathogen, Disease,Route so I want to get data where Product Name let's say is Ali and Disease is Skin. They way I have got from different sites what it does it show all the record with starting and end the value provided in the two input fields.
Here is my code which I am using.
<!doctype html>
<html>
<head>
</head>
<body>
<script>
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function() {
//No support? Go in the corner and pout.
if(!indexedDBOk) return;
var openRequest = indexedDB.open("products",1);
//var openRequest = indexedDB.open("idarticle_people5",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("products")) {
var os = thisDB.createObjectStore("products", {autoIncrement:true});
//I want to get by name later
os.createIndex("name", "name", {unique:false});
//I want email to be unique
os.createIndex("pathogen", "pathogen", {unique:false});
os.createIndex("disease", "disease", {unique:false});
os.createIndex("route", "route", {unique:false});
}
}
openRequest.onsuccess = function(e) {
db = e.target.result;
//Listen for add clicks
document.querySelector("#addButton").addEventListener("click", addPerson, false);
//Listen for get clicks
document.querySelector("#getButton").addEventListener("click", getPerson, false);
}
openRequest.onerror = function(e) {
//Do something for the error
}
},false);
function addPerson(e) {
var name = document.querySelector("#name").value;
var pathogen = document.querySelector("#pathogen").value;
var disease = document.querySelector("#disease").value;
var route = document.querySelector("#route").value;
console.log("About to add "+name+"/"+pathogen);
//Get a transaction
//default for OS list is all, default for type is read
var transaction = db.transaction(["products"],"readwrite");
//Ask for the objectStore
var store = transaction.objectStore("products");
//Define a person
var person = {
name:name,
pathogen:pathogen,
disease:disease,
route:route
}
//Perform the add
var request = store.add(person);
request.onerror = function(e) {
alert("Sorry, that email address already exists.");
console.log("Error",e.target.error.name);
console.dir(e.target);
//some type of error handler
}
request.onsuccess = function(e) {
console.log("Woot! Did it");
}
}
function getPerson(e) {
var name = document.querySelector("#nameSearch").value;
var endname = document.querySelector("#diseaseSearch").value;
if(name == "" && endname == "") return;
var transaction = db.transaction(["products"],"readonly");
var store = transaction.objectStore("products");
var index = store.index("name");
//Make the range depending on what type we are doing
var range;
if(name != "" && endname != "") {
range = IDBKeyRange.bound(name, endname);
} else if(name == "") {
range = IDBKeyRange.upperBound(endname);
} else {
range = IDBKeyRange.lowerBound(name);
}
var s = "";
index.openCursor(range).onsuccess = function(e) {
var cursor = e.target.result;
if(cursor) {
s += "<h2>Key "+cursor.key+"</h2><p>";
for(var field in cursor.value) {
s+= field+"="+cursor.value[field]+"<br/>";
}
s+="</p>";
cursor.continue();
}
document.querySelector("#status").innerHTML = s;
}
}
</script>
<input type="text" id="name" placeholder="Name"><br/>
<input type="text" id="pathogen" placeholder="Pathogen"><br/>
<input type="text" id="disease" placeholder="Disease"><br/>
<input type="text" id="route" placeholder="Route"><br/>
<button id="addButton">Add Data</button>
<p/>
<input type="text" id="nameSearch" placeholder="Name"><br/>
<input type="text" id="diseaseSearch" placeholder="Disease"><br/>
<button id="getButton">Get By Name</button>
<p/>
<div id="status"></div>
</body>
</html>
You can try the following procedure with three parameters:
databaseid
tableid - storage name
callback - function, which returns array of selected data
cond - conditional function. returns true for ok records, and false for others.
Here is the code:
function selectFromTable (databaseid, tableid, cb, cond) {
var request = window.indexedDB.open(databaseid);
request.onsuccess = function(event) {
var res = [];
var ixdb = event.target.result;
var tx = ixdb.transaction([tableid]);
var store = tx.objectStore(tableid);
var cur = store.openCursor();
cur.onblocked = function(event) {
}
cur.onerror = function(event) {
}
cur.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cond(cursor.value) ) res.push(cursor.value);
cursor.continue();
} else {
ixdb.close();
cb(res);
}
}
}
Try using a browser database API adapter and read about its usage from its wiki page.
You need to include all 3 JS files to get started.

Categories

Resources