Ajax ready state not stuck on 1 - ajax

after searching the internet I was unable to find an answer as to why my AJAX code is not working. My assignment is to retrieve a text file and display it to the browser using AJAX but the ready state stops at 1. an example file is canada.txt and is located in the directory http://157.201.194.254/~ercanbracks. The .html and .js files are below:
HTML file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>AJAX</title>
<link rel="stylesheet" type="text/css" href="assign09.css" />
<script type="text/javascript" src="assign09.js"></script>
</head>
<body>
<h1>Ten Largest Cities</h1>
<h3>Select a Country:</h3>
<form action="">
<select id="country">
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
<option value="russia">Russia</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit"
onclick="makeRequest(document.getElementById('country').value)" />
<div id="error"> </div>
</form>
<h3>Cities:</h3>
<div id="cities">
<pre>
City Population
------------------ ---------------
<span id="cityList"></span>
</pre>
</div>
</body>
</html>
.js file:
var httpRequest;
var countryOption;
function makeRequest(option)
{
countryOption = option;
if (window.XMLHttpRequest) // Modern Browsers
{
httpRequest = new XMLHttpRequest();
}
else // older IE browsers
{
try
{
httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e)
{
try
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('ERROR - Unable to make XMLHttpRequest');
}
}
}
if (!httpRequest)
{
alert('ERROR: httpRequest failed -- try a different browser');
return false;
}
else
{
var url = "http://157.201.194.254/~ercanbracks/" + option + ".txt";
alert('Ready State = ' + httpRequest.readyState);
httpRequest.onreadystatechange = getCities;
httpRequest.open("GET", url, true)
httpRequest.send(null);
}
}
function getCities()
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.readyState == 4)
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.status == 200)
{
var response = httpRequest.responseText;
document.getElementById("cities").innerHTML = response;
}
else
{
alert('problem with request');
alert('Ready State = ' + httpRequest.statusText);
}
}
}

Related

html dropdown with SandBoxMode.IFRAME

I am trying to make a piece of code (sorry lost the link to original) but I am struggling and cannot get past the error message "The script completed but the returned value is not a supported return type". I have looked at changing this to a string, but to be honest I am at the limit of my ability to understand what I am trying to do. Any assistance greatly appreciated.
code.gs is:
function getMenu1() {
var t = HtmlService.createTemplateFromFile('myForm');
t.data = SpreadsheetApp
.openById('11_3xQkJdQ172_97LWUoOu22qUMBS-vSrr7TN9bqWicg')
.getSheetByName('PROJECTS')
.getRange('D:D')
.getValues();
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
Logger.log('doGetMenu1 ran');
}
and myform.html is:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<body style="font-family: Arial, Helvetica, sans-serif">
<div>
<input class="left" type="text" name="cuStaff" id="cuStaff" style="width=150px" required>
<datalist id="cuStaff">
</datalist>
<input class="left" type="date" name="dateA" id="dateA" style="width:150px" required>
<input class="left" type="time" name="timeA" id="timeA" style="width:75px" required>
</div>
</body>
<select id="cuStaff">
<option> Choose a option </option>
</select >
<body onload = "addList()"></body>
<script>
function addList() {
console.log('addList ran!');
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(injectMyContent)
.getMenu1();
};
window.injectMyContent = function(argReturnedData) {
for(var i = 0; i < argReturnedData.length; i++) {
var opt = argReturnedData[i];
var document = myForm.html
var el = document.createElement("option");
var el = document
el.text = opt;
el.value = opt;
select.appendChild(el);
};
};
window.onFailure = function(err) {
alert('There was an error! ' + err.message);
};
</script >
</head>
</html>
JSFiddle here
Seems like the 2 functions are being mixed. Try:
function doGet() {
var t = HtmlService.createTemplateFromFile('myForm');
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getMenu1() {
var data = SpreadsheetApp
.openById('11_3xQkJdQ172_97LWUoOu22qUMBS-vSrr7TN9bqWicg')
.getSheetByName('PROJECTS')
.getRange('D:D')
.getValues();
Logger.log('getMenu1 ran')
return data;
}

Onchange() for AJAX

I am trying to display the onchange value of a textbox using ajax. My code is as follows :
ajaxquery.php
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//fuction to return the xml http object
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p>Country : <input type="text" name="country" onChange="getCurrencyCode('code.php?country='+this.value)">
</form>
</body>
</html>
code.php
<?php
$country=$_REQUEST['country'];
echo $country;
?>
The value is not displaying. Where am I going wrong?
P.s. I am completely new to ajax and have no knowledge about it. Appreciate any help :)
<p>Country : <input type="text" name="country" onblur="getCurrencyCode('code.php?country='+this.value)">
<p>Country Code : <input type="text" name="cur_code" id='cur_code' ">
Changed the onchange function to onblur and added another input type. It is working perfectly now!

Kendo Upload upgrade(MVC) - OnUploadSelect code change

With the older version of telerik, we had a snippet of code to find the number of childnodes as given below
function onUploadSelect(ev) {
var numberOfFiles;
if (ev.target.childNodes[1] != undefined && ev.target.childNodes[1] != null) {
numberOfFiles = ev.target.childNodes[1].childNodes.length;
}
if ((numberOfFiles + ev.files.length) > 4) {
//some custom validation error msgs being thrown
}
}
the basic logic of this code is to prevent uploading more than 4 files,
Ex - i select 2 files,dont click on upload instead select a file again and then click on upload, I'm good(2+1<4)
With the KEndo Uplaod, ev.target is undefined,
can you suggest a possible alternative for this?
Thanks
Adarsh
Please try with the below code snippet.
Kendo-HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div class="demo-section">
<input name="files" id="files" type="file" />
</div>
<script>
$(document).ready(function() {
$("#files").kendoUpload({
select: onSelect
});
});
function onSelect(e) {
if (e.files.length > 4) {
alert("Please select max 4 files.");
e.preventDefault();
}
else {
var existingfileCount = $(".demo-section li").length;
if((e.files.length + existingfileCount) > 4)
{
alert("You can not upload more than 4 files");
e.preventDefault();
}
}
}
</script>
</body>
</html>
Kendo-MVC
Javascript
<script>
function onSelect(e) {
if (e.files.length > 4) {
alert("Please select max 4 files.");
e.preventDefault();
}
else {
var existingfileCount = $(".demo-section li").length;
if((e.files.length + existingfileCount) > 4)
{
alert("You can not upload more than 4 files");
e.preventDefault();
}
}
}
</script>
View.cshtml
<div class="demo-section">
#(Html.Kendo().Upload()
.Name("files")
.Events(events => events.Select("onSelect"))
)
</div>
Note : I have used 'demo-section' class to simplyfy the code. If you want to rename this class then rename this class in html/cshtml and javascript.
Let me know if any concern.
Hi this is what you want ,
function onSelect(e) {
var ct = $('#Count').val();
if (e.files.length > 4) {
alert("Please select max 4 files.");
e.preventDefault();
}
else {
ct= parseInt(ct == "" ? 0 : ct);
$('#Count').val(ct + e.files.length);
}
}
#Html.Hidden("Count")
to restrict user to not upload more then 4 file. If i understand right.

Dropdown using Ajax

I wrote the below code; when I select India/America in the dropdown related text files with some contents, has to be read and displayed inside a div element, but am getting an error in the line xhr.send()
can anyone explain why??
<html>
<head>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getcity()
{
var a=document.getElementById("country");
var b=a[a.selectedIndex].value;
alert(b);
var xhr=new XMLHttpRequest();
if(b=="India")
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","india.txt",true);
}
else
{
xhr.onreadystatechange=function()
{
if((xhr.readystate==4)&&(xhr.status==200||xhr.status==304))
{
document.getElementByID("display").innerHTML=xhr.responseText;
}
}
xhr.open("GET","america.txt",true);
}
xhr.send(null);
}
</script>
</head>
<body>
<select id="country" onchange="getcity()">
<option>India</option>
<option>America</option>
</select>
<div id="display"></div>
</body>
</html>

Can't prevent file upload on failed validation using jQuery Form plugin

Here's my form:
<form id="frmUpload" action="../scripts/upload.php" method="post" enctype="multipart/form-data">
<div id="sermonInfo">
File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100">
</div>
</form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar" style="width: 0%;"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
And here's the JS I'm using:
<script>
$(function() {
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #title').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('form').ajaxForm({
beforeSend: function(e) {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the file.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #title').removeClass('error');
$('#required').empty();
var result = true;
title = $('#title').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop();
if (fileName !== '' && extension !== 'mp3') {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#title').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #title').val('').removeClass();
}
</script>
As you can see, I'm using console output the keep an eye on what's going on.
My problem is, if a file is selected, the file still uploads, whether formValid (in beforeSend) is true or false.
I've tried adding preventDefault before return false;. I've also tried clearing the file input in the if (!formValid) {} block. As you can see, I've wrapped the uploadProgress and complete functions to check if formValid is false. If the console output in uploadProgress shows formValid to be false, the file still uploads.
What am I missing here? How can I prevent the file upload if the validation fails?
I finally figured out the issue: I was comparing my script to some examples online and noticed that the examples' callback was named beforeSubmit, but I was using beforeSend.
Oddly, the validation code was still executing, but returning false didn't stop the upload.
Basically, it looks like you might be missing the jquery.form.js extension. Without JavaScript console output, I can only guess that that ought to be the problem. Try the following (entire) page as a reference, where stopping the upload works:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test Page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type="text/javascript">
</script>
<script src="http://malsup.github.com/jquery.form.js" type="text/javascript">
</script>
<style type="text/css">
div.c1 {width: 0%;}
</style>
</head>
<body>
<form id="frmUpload" action="%3C?php%20basename(__FILE__,%20'.php');%20?%3E" method="post" enctype="multipart/form-data" name="frmUpload">
<div id="sermonInfo">File: <input type="file" id="uploadedFile" name="uploadedFile" class="error"><br>
<br>
Title: <input type="text" id="title" name="sermonTitle" size="35" maxlength="100"></div>
<input type="submit" value="Submit"></form>
<div id="uploadInfo">
<div class="progress">
<div class="statusBar c1"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
<br>
<div id="required">Only mp3 files are allowed!</div>
</div>
<script type="text/javascript">
$(function() {
/*
* Upload
*/
// Reset validation and progress elements
var formValid = true,
percentVal = '0%';
$('#uploadedFile, #title').removeClass('error');
$('#status, #required').empty().removeClass();
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
$('form').ajaxForm({
beforeSend: function(e) {
if (!ValidateUploadForm()) {
formValid = false;
console.log('validateuploadform returned false');
} else {
console.log('validateuploadform returned true');
formValid = true;
}
console.log('in beforeSend. formValid: ' + formValid);
if (!formValid) {
return false;
}
},
uploadProgress: function(event, position, total, percentComplete) {
console.log('in uploadProgress function. formValid: ' + formValid);
if (formValid) {
var percentVal = percentComplete + '%';
$('.statusBar').width(percentVal)
$('.percent').html(percentVal);
}
},
complete: function(xhr) {
console.log('in complete function. formValid: ' + formValid);
if (formValid) {
console.log('xhr.responseText: ' + xhr.responseText);
console.log('formValid: ' + formValid);
if (xhr.responseText === 'success') {
$('.statusBar').width('100%');
$('.percent').html('100%');
$('#status').html('Successfully uploaded the file.').addClass('successUpload');
// Clear the form
ClearForm();
} else if (xhr.responseText === 'fail') {
$('#status').html('There was a problem uploading the file. Try again.<br>If the problem persists, contact your system administrator.').addClass('errorUpload');
}
}
}
}); // End Upload Status Bar
});
function ValidateUploadForm() {
// Reset errors and clear message
$('#uploadedFile, #title').removeClass('error');
$('#required').empty();
var result = true;
title = $('#title').val(),
fileName = $('#uploadedFile').val();
extension = $('#uploadedFile').val().split('.').pop();
if (fileName !== '' && extension !== 'mp3') {
$('#uploadedFile').addClass('error');
$('#required').html('Only mp3 files are allowed!');
return false;
} else if (fileName === '') {
result = false;
} else if (title === '') {
$('#title').addClass('error');
result = false;
}
console.log('returning ' + result + ' from the validateuploadform function');
if (!result) { $('#required').html('All fields are required.'); }
return result;
}
function ClearForm() {
$('#uploadedFile, #title').val('').removeClass();
}
</script>
</body>
</html>
As a side note, you might want to use
extension = $('#uploadedFile').val().split('.').pop().toLowerCase();
to make sure that the form also accepts MP3, as this is seen relatively often too in the wild.
If this doesn't fix your problem, it would help if you could upload the full HTML of one page in question.
UPDATE
With respect to the uploaded files, you have a simple typo in line 91 of testUpload.php:
if ((fileName === '') || (extension !== 'mp3'))
should be
if ((fileName === '') || (extension !== 'mp3')) {

Resources