I cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...
Related
So, I am working on an audio part where I fetch my words from a JSON file and when I show them on my front-end it should onclick on the audio button fetch the word from the server and create the audio... But I keep on getting Cannot read property toLowerCase of undefined and I cannot seem to find the error.
let's start with the variables I declared:
var MEDIAARRAY;
var WORDS;
var audioArray;
var audio = new Audio();
var LANGUAGE;
var SOUNDARRAY;
The piece of code (I took over the code given as answer and it helped me a bit further so I decided to edit the question with the code I have right now).
$(document).ready(function () {
getFileArray();
});
$(document).on("click", ".sound", function () {
getFileArray("SomeLanguage");
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
var currentVal = $(this).parent().find('.fa-volume-up');
if (foundID > -1) {
var audio = new Audio();
audio.src = 'TheServerURL' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[foundID] + '';
audio.play();
}
});
The line where the error occurs:
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
The button where the class sound is appended to:
function getAudioForWords() {
var audioBtn = $('<a/>', {
'class': 'sound btn btn-primary'
}).html('<i class="fa fa-volume-up"></i>');
return audioBtn;
}
the code where class exerciseWord gets append to:
var wordCol = $('<div>', {
class: 'col-md-9 ExerciseWordFontSize exerciseWord',
'id': 'wordInput[' + ID123 + ']',
text: exercise.word
});
and the piece of code that gets the fileArray, but most likely will be useless for you to inspect, but it was related to my code so... yeah.
function getFileArray(param)
{
var request = {
language: param
};
$.ajax(
{
url: "TheServerURL",
type: "POST",
async: true,
data: request,
dataType: 'json',
}).done(function (response)
{
console.log(response)
MEDIAARRAY = response;
audioArray = response.audio;
console.log(audioArray);
});
}
The error states varialble MEDIAARRAY remains uninitialized somewhere in your code flow. See if following takes you close to the resolution
You have not mentioned at what point getFileArray function is called. Call to getFileArray function is critical because that is when MEDIAARRAY is assigned value.
Ensure getFileArray is called before you access any propery of MEDIAARRAY.
Ensure your API always returns object which contains audio property.
Example,
$(document).on("click", ".sound", function () {
//Ensure you supply parameter value to your function(i.e. value of the element you take user input from)
getFileArray("SomeLanguage");
var foundID = MEDIAARRAY.audio.lowercase.indexOf($(this).parent().find('.exerciseWord').val().toLowerCase() + '.mp3');
var currentVal = $(this).parent().find('.fa-volume-up');
if (foundID > -1) {
var audio = new Audio();
audio.src = 'TheServerURL' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[foundID] + '';
audio.play();
}
});
The code below get's Json object from a URL in a loop.
Problem is I cannot seem to display returned Json data.
I want to display the Temperature and Humidity from the object.
Valid Json objects are returned OK, but i cannot display it in HTML div.
I see nothing printed to screen.
FULL CODE:
<html>
<head>
<title>json loop</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<div id="container">
<div id="div"></div>
<div id="output">nothing yet</div>
</div>
<script>
var previous = null;
var current = null;
var data;
setInterval(function() {
$.getJSON(
"https://dweet.io/get/latest/dweet/for/myesp8266",
function(json) {
data = json;
current = JSON.stringify(data);
$("div").html(data);
console.log(data);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
var output = document.getElementById('output');
output.innerHTML = data ;
</script>
</body>
</html>
You are not putting the stringified string to the HTML. Use current and not data ?
data = json;
current = JSON.stringify(data);
$("div").html(current);
console.log(current);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
EDIT
If you want the temperature, use :
$("div").html(data.with[0].content.temperature);
have you tried it like this ?
setInterval(function() {
$.getJSON("https://dweet.io/get/latest/dweet/for/myesp8266",
function(json) {
data = json;
current = JSON.stringify(data);
//$("div").html(data);
console.log(data);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
var output = document.getElementById('output');
output.innerHTML = current ;
});
}, 2000);
Edit:
here is an example on how this may work: https://plnkr.co/edit/GI5uzojOOmJNwAc73aXq?p=preview
I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'
I have this script below which is used in a survey. The problem I have is, onbeforeunload() works when I don't call a function inside it. If I make any function call(save_survey() or fetch_demographics()) inside it, the browser or the tab closes without any prompt.
<script type="text/javascript">
$(document).ready(function() {
$('#select_message').hide();
startTime = new Date().getTime();
});
loc = 0;
block_size = {{ block_size }};
sid = {{ sid }};
survey = {{ survey|tojson }};
survey_choices = '';
startTime = 0;
demographics_content = {};
function save_survey(sf)
{
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
var surveydat = '';
if(sf==1)
{ //Success
surveydat = 'sid='+sid+'&dem='+JSON.stringify(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+JSON.stringify(survey_choices);
}
if(sf==0)
{ //Fail
surveydat = 'sid='+sid+'&dem='+json_encode(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+json_encode(survey_choices);
}
//Survey Save Call
$.ajax({
type: 'POST',
url: '/save_surveyresponse/'+sf,
data: surveydat,
beforeSend:function(){
// this is where we append a loading image
$('#survey_holder').html('<div class="loading"><img src="/static/img/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$('#survey_holder').html('Success');
alert("Dev Alert: All surveys are over! Saving data now...");
window.location.replace('http://localhost:5000/surveys/thankyou');
},
error:function(){
// failed request; give feedback to user
$('#survey_holder').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
function verify_captcha()
{
// alert($('#g-recaptcha-response').html());
}
function block_by_block()
{
var div_content ='<table border="0" cellspacing="10" class="table-condensed"><tr>';
var ii=0;
var block = survey[loc];
var temp_array = block.split("::");
if(loc>=1)
{
var radio_val = $('input[name=block_child'+(loc-1)+']:checked', '#listform').val();
//console.log(radio_val);
if(radio_val!=undefined)
survey_choices += radio_val +'\t';
else
{
alert("Please select one of the choices");
loc--;
return false;
}
}
for(ii=0;ii<block_size;ii++)
{
//Chop the strings and change the div content
div_content+="<td>" + temp_array[ii]+"</td>";
div_content+="<td>" + ' <label class="btn btn-default"><input type="radio" id = "block_child'+loc+'" name="block_child'+loc+'" value="'+temp_array[ii]+'"></label></td>';
div_content+="</tr><tr>";
}
div_content+='<tr><td><input type="button" class="btn" value="Next" onClick="survey_handle()"></td><td>';
div_content+='<input type="button" class="btn" value="Quit" onClick="quit_survey()"></td></tr>';
div_content+="</table></br>";
$("#survey_holder").html(div_content);
//return Success;
}
function updateProgress()
{
var progress = (loc/survey.length)*100;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#active-bar").html(Math.ceil(progress));
}
function survey_handle()
{
if(loc==0)
{
verify_captcha();
$("#message").hide();
//Save the participant data and start showing survey
fetch_demographics();
block_by_block();
updateProgress();
$('#select_message').show();
}
else if(loc<survey.length)
{
block_by_block();
updateProgress();
}
else if(loc == survey.length)
{
//Save your data and show final page
$('#select_message').hide();
survey_choices += $('input[name=block_child'+(loc-1)+']:checked', '#listform').val()+'\t';
//alert(survey_choices);
//Great way to call AJAX
save_survey(1);
}
loc++;
return false;
}
</script>
<script type="text/javascript">
window.onbeforeunload = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
//fetch_demographics();
save_survey(0);
return "You have spent "+Math.ceil(t)+ " minute/s on the survey!";
//!!delete last inserted element if not quit
}
</script>
I have checked whether those functions have any problem but they work fine when I call them from different part of the code. Later, I thought it might be because of unreachable function scope but its not the case. I have tried moving the onbeforeunload() at the end of script and the problem still persists. Wondering why this is happening, can anyone enlighten me?
I identified where the problem was. I am using json_encode instead of JSON.stringify and hence it is crashing(which I found and changed already in sf=1 case). That tip with debugger is invaluable. Also, its working fine even without async: false.
Thank you again #AdrianoRepetti!
I am using a script with jQuery:
$(document).ready(function () {
var button;
var line;
var inputs;
var params = {};
var updatefield;
$('button.update').click(function () {
button = $(this);
params['button'] = button.val();
line = button.closest('.line');
updatefield = line.find('td.resultFromGet');
inputs = line.find('input');
inputs.each(function (id, item) {
switch($(item).attr('type')){
case 'checkbox':{
params[$(item).attr('name')] = new Array($(item).is(':checked'));
break;
}
default:{
params[$(item).attr('name')] = new Array($(item).attr('value'));
break;
}
}
});
//alert(JSON.stringify(params, null, 4));
$.get( 'core/ajax/correct_exec.php', params )
.done(function (data){
if(data == '1'){
$(updatefield).html('UPDATE_RECORD_SUCCESS');
} else {
$(updatefield).html( data );
}
});
});
});
The page I am getting is doing echo '1'; from PHP in case of success.
I try to test this with data == 1 but it doesn't work even though it is a success. In fact, it sends me $(updatefield).html( data ); which is 1. So why can't it just print UPDATE_RECORD_SUCCESS?
The data response is coming with white space, if you use trim() function something like this, then if condition should be executed.
if(data.trim() == '1'){
$('#updatefield').html('UPDATE_RECORD_SUCCESS'); //this should be executed
} else {
$('#updatefield').html( data );
}
Here you can see the space with data in chrome debugger.