Unable to alert success message after function executes - javascript

I am unable to get an alert of "Thank you for your enquiry!" after the function successfully executes and is sent to the database. My codes are as follows:
function addenquiry() {
Texttitle = $("#Texttitle").val();
Textenquiry = $("#Textenquiry").val();
if (validate()) {
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/addenquiry.php";
url += "?userid=" + userid + "&Texttitle=" + Texttitle + "&Textenquiry=" + Textenquiry;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
addEnquiry(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
function addEnquiry(response) {
var arr = JSON.parse(response);
if (arr[0].result == 1) {
alert("Thank You for your enquiry!")
}
else {
alert("Sorry please try again");
}
}
Not sure where i have gone wrong, the title and message is successfully recorded in the database but i am not getting the alert, hope to receive some guidance and help from someone. Thank you!

Related

Simple XMLHttpRequest the response xhttp.responseText; don't work

this.responseText don't return the content of file. Can anyone help me with this problem? Thanks
Console.log don't return the content of file.
function loadMegaContent() {
var xhttp = new XMLHttpRequest();
var mesaj = "";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
mesaj = this.responseText
console.log("-WorkGood-" + this.responseText);
document.getElementById("logTextWXY").innerHTML = mesaj;
} else if (this.status == 404) {
mesaj = "The log don't exist in path";
document.getElementById("logTextWXY").innerHTML = mesaj;
}
};
xhttp.open("GET", "/admin/installstatus/fileContent.txt", true);
xhttp.send();
console.log("--mesaj" + mesaj);
}
Error
// The message display by console is next:
<title>Session expired</title>
<meta http-equiv="refresh" content="0;url=/Portal"/>
</head><body><p>Session expired please relogin</p></body></html>
If you just want to get the content of a file asynchronously, use fetch like:
async function loadMegaContent(){
let response = await fetch("/admin/installstatus/fileContent.txt");
if(response.status==200){
let data = await response.text();
console.log("-WorkGood-" + data);
document.getElementById("logTextWXY").innerHTML = data;
}else if (response.status==404){
mesaj = "The log don't exist in path";
document.getElementById("logTextWXY").innerHTML = mesaj;
}
}

How to pass a string in url in Javascript?

I'm trying to make an application that accesses different sites inside of an iframe from a private JSON dns server.
I have completed the main code, but now I am trying to make it able to be accessed through the url. (Ex. https://thissite.info?url='test.json'&dnsserver='https://thissite.info')
I also want it to default to a value if the variable is not defined in the url. For this, I'm using the following code:
function setup(){
var dns = document.getElementById("dns");
var urlbar = document.getElementById("urlbar");
var frame = document.getElementById("viewport");
if (typeof url === "undefined") {
url = 'Welcome Page URL Here';
} else {
urlbar.value = url;
}
if (typeof dnsserver === "undefined") {
dnsserver = 'Default Server Here';
} else {
dns.value = dnsserver;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.status)
if(this.readyState == 4 && this.status == 200){
var response = JSON.parse(this.responseText);
frame.src=response;
console.log("Request Completed with 200");
};
if(this.readyState == 4 && this.status == 404){
console.log("Website Not Found");
frame.src='404.html'
};
}
xmlhttp.open("GET",dnsserver + url + '.json', true);
xmlhttp.send();
console.log("Request Sent");
}
But even if I pass the vars in the URL, it doesn't accept it.
<script type="text/javascript"> $(function () { $("#btnQueryString").bind("click", function () { var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val()); window.location.href = url; }); }); </script> <input type="button" id="btnQueryString

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

Update DOM object in time intervals using JavaScript Worker

I'm trying to do some DOM objects updates in background.
What I mean is update tab title, and some elements regardless if user has tab active or not ( to show that there are new notifications )
I already found out, that Worker has to be used as it runs in background ( but don't have access to DOM). Tried as follows:
Main HTML:
...some html
<script>
$(document).ready(function ($) {
if (window.Worker) {
console.log('[DEBUG] Worker is supported')
var eventsWorker = new Worker("<c:url value="/resources/js/eventTimer.js" />");
setInterval(eventsWorker.postMessage([appUrl]), 20 * 1000);
//setEventsNonWorker()
eventsWorker.onmessage = function (e) {
console.log('Message received from worker' + e.data);
setEventsCount(e.data, appName, eventsTxt);
}
} else {
console.log('[DEBUG] Worker is NOT supported')
setEventsNonWorker()
}
});
function setEventsNonWorker(){
//regular update with setTimout and stuff
}
worker javascript file
function setEventsCount(count, appName, eventsTxt) {
var bell, text, countPar;
if (count > 0) {
bell = '<i class="fa fa-bell"></i> ';
countPar = '(' + count + ') ';
text = bell + eventsTxt + countPar;
$(".event-menu-li").html(text);
$("#event-menu-icon").html(bell + count)
document.title = countPar + appName;
} else {
bell = '<i class="fa fa-bell-o"></i> ';
text = bell + eventsTxt;
$(".event-menu-li").html(text);
$("#event-menu-icon").html(bell)
document.title = appName;
}
}
onmessage = function (e) {
var appUrl = e.data[0];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
postMessage(xmlhttp.responseText);
}
};
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
}
The first call is working ( the event count is properly set ) but there are no more calls in 20 sec
Ok it turns out I was putting timeout in wrong place
html should be
//...
eventsWorker.postMessage([appUrl]);
eventsWorker.onmessage = function (e) {
console.log('Message received from worker' + e.data);
setEventsCount(e.data, appName, eventsTxt);
//...
which will just init worker , while worker.js should have the timeout
//...
onmessage = function (e) {
var appUrl = e.data[0];
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
postMessage(xmlhttp.responseText);
}
};
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
setInterval(function () {
xmlhttp.open("GET", appUrl, true);
xmlhttp.send();
}, 20*1000);
}

jquery to javascript converted but not working

my initial code was in jquery + ajax and i tried to write it in javascript but its not working now. Can anyone tell me where's the mistake and why its not showing anything when i run through the server? i checked in the console and there is no error either
my code in JQ
$(document).ready(function(){
findteacher = function() {
var file = "course.php?course="+ $("#course").val();
$.ajax({
type : "GET",
url : file,
datatype : "text",
success : function(response) {
var file2 = response.split(",");
$("#courseInfo").html("The course: " + file2[0] + " Taught by: " + file2[1]);
}
});
}
clear = function() {
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findteacher);
});
My code in JS
function findteacher () {
var file = "course.php" + document.getElementById('course');
function callAjax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('courseInfo').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
var file2 = callAjax.split(",");
document.getElementById('courseInfo').text("The course: " + file2[0] + " Taught by: " + file2[1]);
}
document.getElementById('go').onclick(findteacher)
}
window.onload = findteacher;
You're missing ?course= in file. You're not getting .value of the course element. callAjax.split(",") makes no sense -- callAjax is a function, not a string -- you should be using xmlhttp.responseText.split(",") in the onreadystatechange function. onclick is a property you assign to, not a method, so .onclick(findteacher) should be onclick = findteacher; and you shouldn't do this inside the function, it should be done just once when the page is loaded.
function findteacher () {
var file = "course.php?course=" + document.getElementById('course').value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var file2 = xmlhttp.responseText.split(",");
document.getElementById('courseInfo').innerHTML = "The course: " + file2[0] + " Taught by: " + file2[1];
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send(null);
}
function clear () {
document.getElementById('courseInfo').innerHTML = '';
}
window.onload = function() {
document.getElementById('go').onclick = findteacher;
document.getElementById('course').onclick = clear;
}

Categories

Resources