I'm a really new Javascript person who for the first time is trying to write (rather than copy) code for a page. Simply put, I wish to read a text file then display the characters one at a time in a div already created. The 'get' corks fine and the data variable receives the string, however, I get a 'Line 1' input past error from the browser when this executes. Probably 10 things wrong with how I am going about it, but any direction welcome.
enter code here
<div id='textelement' style="width:400px; height:200px ;overflow:auto"></div>
<script type="text/javascript">
$.get("Comments.txt", function (data)
{
var displaytxt = "";
displaytxt = data;
function nextchar ()
{
if (displaytxt.length > 0)
{
$('#textelement').append(displaytxt.substr(0, 1));
displaytxt = displaytxt.substr(1);
setTimeout(nextchar, 70);
}
}
}
</script>
For one thing you did not escape your function properly.
<script type="text/javascript">
$.get("Comments.txt", function (data)
{
var displaytxt = "";
displaytxt = data;
function nextchar ()
{
if (displaytxt.length > 0)
{
$('#textelement').append(displaytxt.substr(0, 1));
displaytxt = displaytxt.substr(1);
setTimeout(nextchar, 70);
}
}
}).fail(function (xhr, status, error) {
alert(error);
});
</script>
After looking at this a while I found that:
1. I never called my function 'nextchar' therefore it never ran. Silly me.
2. setTimeout needs a strange syntax using the function() {} in order to pass parameters. Why is this?
The code below now works for me.
greg
<script type="text/javascript">
function nextchar(displaytxt) {
if (displaytxt.length > 0) {
$('#textelement').append(displaytxt.substring(0, 1));
displaytxt = displaytxt.substr(1);
setTimeout(function () { nextchar(displaytxt); }, 70);
}
}
$.get("PatientComments.txt", function (data) {
var displaytxt = "";
displaytxt = data;
alert(displaytxt);
nextchar(displaytxt);
}).fail(function (xhr, status, error) {
alert(error);
});
</script>
Related
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
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.
var dbShell;
function doLog(s){
/*
setTimeout(function(){
console.log(s);
}, 3000);
*/
}
function dbErrorHandler(err){
alert("DB Error: "+err.message + "\nCode="+err.code);
}
function phoneReady(){
doLog("phoneReady");
//First, open our db
dbShell = window.openDatabase("SimpleNotes", 2, "SimpleNotes", 1000000);
doLog("db was opened");
//run transaction to create initial tables
dbShell.transaction(setupTable,dbErrorHandler,getEntries);
doLog("ran setup");
}
//I just create our initial table - all one of em
function setupTable(tx){
doLog("before execute sql...");
tx.executeSql("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY,title,body,updated)");
doLog("after execute sql...");
}
//I handle getting entries from the db
function getEntries() {
//doLog("get entries");
dbShell.transaction(function(tx) {
tx.executeSql("select id, title, body, updated from notes order by updated desc",[],renderEntries,dbErrorHandler);
}, dbErrorHandler);
}
function renderEntries(tx,results){
doLog("render entries");
if (results.rows.length == 0) {
$("#mainContent").html("<p>You currently do not have any notes.</p>");
} else {
var s = "";
for(var i=0; i<results.rows.length; i++) {
s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";
}
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
function saveNote(note, cb) {
//Sometimes you may want to jot down something quickly....
if(note.title == "") note.title = "[No Title]";
dbShell.transaction(function(tx) {
if(note.id == "") tx.executeSql("insert into notes(title,body,updated) values(?,?,?)",[note.title,note.body, new Date()]);
else tx.executeSql("update notes set title=?, body=?, updated=? where id=?",[note.title,note.body, new Date(), note.id]);
}, dbErrorHandler,cb);
}
function init(){
document.addEventListener("deviceready", phoneReady, false);
//handle form submission of a new/old note
$("#editNoteForm").live("submit",function(e) {
var data = {title:$("#noteTitle").val(),
body:$("#noteBody").val(),
id:$("#noteId").val()
};
saveNote(data,function() {
$.mobile.changePage("index.html",{reverse:true});
});
e.preventDefault();
});
//will run after initial show - handles regetting the list
$("#homePage").live("pageshow", function() {
getEntries();
});
//edit page logic needs to know to get old record (possible)
$("#editPage").live("pageshow", function() {
var loc = $(this).data("url");
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1,loc.length);
var noteId = qs.split("=")[1];
//load the values
$("#editFormSubmitButton").attr("disabled","disabled");
dbShell.transaction(
function(tx) {
tx.executeSql("select id,title,body from notes where id=?",[noteId],function(tx,results) {
$("#noteId").val(results.rows.item(0).id);
$("#noteTitle").val(results.rows.item(0).title);
$("#noteBody").val(results.rows.item(0).body);
$("#editFormSubmitButton").removeAttr("disabled");
});
}, dbErrorHandler);
} else {
$("#editFormSubmitButton").removeAttr("disabled");
}
});
}
Dats my code, awfully long, huh?
Well anyways I got most of it from here, however I get an error on line 67 saying "TypeError: 'undefined' is not a function.".
I'm using Steroids (phonegap-like) and testing dis on an iPhone simulator. I'm sure it uses some cordova for the database work.
Thank you for your help :-)
Which jQuery version do you use? Because .live() was removed with jQuery 1.9 (http://api.jquery.com/live/). You should use .on() instead: http://api.jquery.com/on/
I've tried everything I can think of to get this "send" button to work, but I'm not very good at javascript :(
http://www.kimscakes.biz/contactme.php
Prehaps someone here can tell me where i'm going wrong?
Many thanks
Gem
You are binding the submit before the element exists, move the code after the form or put it inside $(document).ready:
jQuery(document).ready(function () {
jQuery("#submit").click(function () {
console.log("button clicked");
// declare these vars
var name = jQuery("#name");
var email = jQuery("#email");
var message = jQuery("#message");
var human = jQuery("#human");
var success = jQuery("#success");
var error = jQuery("#error");
// reset these vars
success.html("");
error.html("");
// ajax call to script.php
jQuery.getJSON("mailer.php", {
name: name.val(),
email: email.val(),
message: message.val(),
human: human.val()
}, function (html) {
// if html from script.php == 1, happy days
if (html == '1') {
jQuery("#contact").hide()
success.html("Thank You, your message has been sent.")
error.show()
}
else {
error.html(html)
}
});
});
});