How can I use JSONP to bypass an error with XMLHttpRequest? - ajax

Can someone help me to use JSONP so I can bypass this error:
XMLHttpRequest cannot load https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/24332988/ranked?season=SEASON4&?api_key=***********. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
I am having trouble understanding on how to use it.
Here is the code I have right now which gives me the error above. How can I fix this?
//ap.js
var summonerLookUp = function () {
// DECLARE URIs
var nameUri = 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/';
var statUri = 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/';
var statEnd = '/ranked?season=SEASON4&';
// Expose API Key for demo purposes
var apiKey = '?api_key=******************************';
// Grab summoner names;
var summOne = $('#summOne').val();
var summTwo = $('#summTwo').val();
// declare divIds that need to be modified later;
var divIds = {
summoner : '',
sLevel : 'Summoner Level : ',
sId : 'Summoner ID: ',
champKills : 'Champion Kills: ',
death : 'Death Total: ',
assist : 'Assist Total: ',
kda : 'Avg KDA: ',
win : 'Wins: ',
loss : 'Losses: ',
minions : 'Minion Kills: ',
turrets : 'Turret Kills: '
};
// Declare general errorhandler
var errorHandler = function () {
alert('Sorry, please try again.');
};
// Must fetch summoner info first to get basic summoner data
var fetchSummonerStats = function (summoner) {
$.ajax({
url: nameUri + summoner + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summData) {
summData = summData[summoner];
// attach .summoner property to summData for divIds later
summData.summoner = summoner;
console.log('SUMM DATA >>', summData);
fetchDetail(summData);
},
error: errorHandler
});
};
// Declare secondary ajax call to fetch stats
// provide summonername an data to attach
var fetchDetail = function (summoner) {
$.ajax({
url: statUri + summoner.id + statEnd + apiKey,
type: 'GET',
dataType: 'json',
data: {},
success: function (summStats) {
// include previous data to attach for divIds
summStats.id = summoner.id;
summStats.summoner = summoner.summoner;
summStats.level = summoner.summonerLevel;
attachStats(summStats);
},
error: errorHandler
});
};
var attachStats = function(summStats) {
var summNumber;
/*
attach a 1 or 2 based on summonername;
if summStats.summoner === xkouki,
summNumber = 1 else it must be summTwo
*/
if (summStats.summoner === summOne) {
summNumber = 1;
} else if (summStats.summoner === summTwo) {
summNumber = 2;
} else {
return errorHandler();
}
// change summoner to summoner as saved in riot api
summStats.summoner = summStats.name;
for (var divId in divIds) {
/*
if divId === summoner
val = 'xkouki';
*/
var val = summStats[divId];
/*
add summonerNumber to the current key in divIds
if divId === summoner
and summNumber === 1
id = summoner1;
etc ...
*/
var id = divId + summNumber;
/*
attach prefix to actual value
if divid === summoner
divIds.summoner = ''
innerHtml = '' + xkouki
*/
document.getElementById(id).innerHtml = divIds[divId] + val;
}
};
// make sure both values exist
if (!summOne || !summTwo) {
alert('Please make sure you have an entry for summoner one & two');
} else {
// loop through this array using forEach and fetchSummoner
[summOne, summTwo].forEach(function (summoner) {
fetchSummonerStats(summoner);
});
}
};
$(document).ready(function() {
$('#list').click(function() {
$('.list').fadeToggle("fast");
});
});
<!DOCTYPE html>
<html>
<head>
<title>League Stats</title>
<link rel="stylesheet" type="css/text" href="styles.css"/>
<link rel="stylesheet" type="css/text" href="font.css"/>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<link href='http://fonts.googleapis.com/css?family=Trade+Winds' rel='stylesheet' type='text/css'>
<script src="app.js"></script>
</head>
<body>
<div class="container">
<header class="title">
<h1>League of Legends Face Off</h1>
<input id="summOne" placeholder="summoner name"/>
<input id="vs" type="button" value="VS" onclick="summonerLookUp();" />
<input id="summTwo" placeholder="summoner name"/>
</header>
<div class="one">
<div id="summoner1"></div>
<div id="sLevel1"></div>
<div id="sID1"></div>
<div id="champKills1"></div>
<div id="death1"></div>
<div id="assist1"></div>
<div id="kda1"></div>
<div id="win1"></div>
<div id="loss1"></div>
<div id="minions1"></div>
<div id="turrets1"></div>
</div>
<div class="logo"><img class="vs" src="vs.png"></div>
<div class="two">
<div id="summoner2"></div>
<div id="sLevel2"></div>
<div id="sID2"></div>
<div id="champKills2"></div>
<div id="death2"></div>
<div id="assist2"></div>
<div id="kda2"></div>
<div id="win2"></div>
<div id="loss2"></div>
<div id="minions2"></div>
<div id="turrets2"></div>
</div>
<button id="list">summoner names</button>
<div class="list" style="display: none;">
xkouki | theoddone | le groot | renesisbuddy | azoh | gripex | bestriven na
<br/>
dyrus | kingtrick | voyboy | robertxlee | iamgosu | balls | fabbbyyy | azingy | megazero
</div>
</div>
</body>
</html>

Related

Scrollspy Uikit 3 framework and count up

i am a beginer in frontend and javascript hard for me :( I want to make count numbers with component scrollspy uikit 3 without jquery https://getuikit.com/docs/scrollspy
I made like this, but it's not working
<span id="number"></span>
<script>
UIkit.scrollspy('#number', 'inview', function () {
const countUp = new CountUp('number', 0, 1000 );
countUp.start();
});
</script>
I created a script for this.
var util = UIkit.util;
var el = util.$('#heading');
var textIndex = 0;
UIkit.scrollspy(el, {repeat: true, delay: 100});
util.on(el,'inview', function (){
function counter( start, end, duration) {
let current = start,
range = end - start,
increment = end > start ? 1 : -1,
step = Math.abs(Math.floor(duration / range)),
timer = setInterval(() => {
current += increment;
el.textContent = current;
if (current == end) {
clearInterval(timer);
}
}, step);
}
counter(0, 100, 3000);
});
util.on(el, 'outview', function(){
el.textContent = 0;
});
<!-- UIkit CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit#3.6.22/dist/css/uikit.min.css" />
<!-- UIkit JS -->
<script src="https://cdn.jsdelivr.net/npm/uikit#3.6.22/dist/js/uikit.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/uikit#3.6.22/dist/js/uikit-icons.min.js"></script>
<section class="uk-section uk-section-primary" uk-height-viewport="offset-top: true">
<div class="uk-container">
<div class="uk-text-center">
<h1 >SECTION 1</h1>
Source Code for Number Increment
</div>
<div class="uk-text-center uk-margin-medium-top">
<a class="uk-link-reset" href="#section" uk-scroll>Scroll</a>
</div>
</div>
</section>
<section class="uk-section uk-section-secondary" id="section">
<div class="uk-container">
<h1 class="uk-text-center" id="heading">0</h1>
</div>
</section>
You need to listen inview and outview event. Here is the method:
UIkit.util.on(element, 'event', function(){
//your code will be here here
});

How to get input data from MVC ViewModel into ajax post

I am fetching data from a SQL database table into an ASP.NET MVC Razor view but I have troubles getting changed input data into an Ajax post such as:
#model MyViewModel
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
var postData = #Html.Raw(Json.Encode(#Model));
//alert(postData.Test);
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}
When I load the view everything is displayed correctly. The controller action is triggered correctly and the Id (which can not be altered) is passed properly too. However when input fields are changed not the changed values get passed to the controller but the original values that were fetched into the view.
The serialization seems to work, since the alert (postData.Test) returns a value - but always the unchanged one.
Any help would be appreciated.
var postData = #Html.Raw(Json.Encode(#Model));
This line is the culprit. When Razor renders the script, it will assign the original/unchanged model to your postData variable.
If you use "Inspect Element" or dev tools to check the value of postData, you'll see that the values won't change because they're statically assigned.
You need to check for the new values every time you click the button by using
var postData = $("form").serialize();
And be sure to wrap your input fields inside a form tag. See code below:
<form>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Id, "Id:", new {})
</div>
<div class="col-4">
#Html.Label(Model.Id.ToString(), new { title = "" })
</div>
</div>
<div class="row">
<div class="col-1">
#Html.LabelFor(model => model.Test, "Test:", new { })
</div>
<div class="col-9">
#Html.TextBoxFor(model => model.Test, new { data_bind = "value: Test", #type = "text" })
</div>
</div>
</form>
#section scripts {
<script type="text/javascript">
$("#save-click").click(function () {
var nr = #Model.Id;
// use form.serialize or use the id/class of your form
var postData = $("form").serialize();
$.ajax({
type: "POST",
url: actions.test.createOrUpdate + "?id=" + nr,
dataType: "json",
traditional: true,
data: postData,
success: function (response) {
if (response.Code == 0) {
else {
window.location.reload(false);
}
} else {
alert('err');
}
}
});
});
});
</script>
}

How to Save File with time as name and return time value with uploadify

what i intend to do, is to use uploadify to upload a file, change its name in uploadify.php for the value of time() ,save it , and return the name of the saved file back to the HTML, im not sure how to do it, currently im using this as guide
http://www.uploadify.com/documentation/uploadify/customizing-the-server-side-upload-script/
and this is my code so far
index.php
'<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script src="jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadify.css">
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
</style>
</head>
<body>
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>',
'name' : 'somename'
},
'method' : 'post',
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
onUploadComplete : function(data, file , response){
alert('The file was saved to: ' + data);
alert(response);
}
});
});
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
var img = 'localhost/uploads/'+ $("#hidden").val;
var cuenta_sap = $("#cuenta_sap").val();
var ubicacion = $("#ubicacion").val();
var codigo_centro_beneficio = $("#codigo_centro_beneficio").val();
var nombre = $("#nombre").val();
var proyecto = $ ("#proyecto").val();
var departamento = $ ("#departamento").val();
var tipo_activo = $("#tipo_activo").val();
var proveedor = $("#proveedor").val();
var modelo = $("#modelo").val();
var numero_serie = $("#numero_serie").val();
var marca = $ ("#marca").val();
var numero_remision = $("#numero_remision").val();
var myData ='cuenta_sap='+ cuenta_sap + '&ubicacion='+ ubicacion +
'&codigo_centro_beneficio='+ codigo_centro_beneficio + '&nombre=' + nombre + '&proyecto='
+ proyecto + '&departamento='+ departamento + '&tipo_activo=' + tipo_activo
+'&proveedor='+ proveedor +'&modelo=' + modelo + '&numero_serie=' + numero_serie +'&marca='
+ marca + '&numero_remision='+ numero_remision;
e.preventDefault();
if(cuenta_sap==''||ubicacion==''||codigo_centro_beneficio==''
||nombre==''||proyecto==''||departamento
==''||tipo_activo==''||proveedor==''||modelo==''
||numero_serie==''||marca==''||numero_remision=='')
{
alert("Formato incompleto!");
return false;
}
$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //
success:function(result){
$("#responds").delay(10000).fadeIn();
$("#responds").append("<li class='res'>"+result+"</li>");
$('.res').remove();
$("#proyecto").val(''); //empty text field on successful
$("#departamento").val(''); //empty text field on successful
$("#tipo_activo").val(''); //empty text field on successful
$("#modelo").val(''); //empty text field on successful
$("#numero_serie").val(''); //empty text field on successful
$("#marca").val(''); //empty text field on successful
$("#numero_remision").val(''); //empty text field on successful
$("#cuenta_sap").val(''); //empty text field on successful
$("#ubicacion").val(''); //empty text field on successful
$("#nombre").val(''); //empty text field on successful
$("#codigo_centro_beneficio").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
<div class="content_wrapper" id="wrapepr">
<div class="form_style">
<input name="hidden" id="hidden" type="text"></input>
<br>
<a>Datos</a>
<br>
<input name="cuenta_sap" id="cuenta_sap" placeholder="cuenta sap" class="input"></input>
<select name="departamento" class="input" id="departamento">
<option value = "">seleccione departamento</option>
<?php
include("db.php");
$stmt = $db->prepare("SELECT `id`, `departamento` FROM `departamentos`");
$stmt->execute();
$stmt->bind_result($id,$departamento);
while ($stmt->fetch()){
echo "<option value='$id'>$departamento</option>";
}
?>
</select>
<select name="proyecto" class="input" id="proyecto" >
<option value = "" >seleccione proyecto</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`proyecto` FROM `proyectos`");
$stmt->execute();
$stmt->bind_result($id,$proyecto);
while ($stmt->fetch()){
echo "<option value='$id'>$proyecto</option>";
}
?>
</select>
<select name="tipo" class="input" id="tipo_activo">
<option value = "" class="input" >tipo de activo</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`tipo` FROM `tipo_activo`");
$stmt->execute();
$stmt->bind_result($id,$tipo_activo);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$tipo_activo</option>";
}
?>
</select>
<select name="proveedor" class="input" id="proveedor">
<option value = "" class="input" >seleccione proveedor</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`nombre` FROM `proveedores`");
$stmt->execute();
$stmt->bind_result($id,$nombre);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$nombre</option>";
}
?>
</select>
<input name="codigo_centro_beneficio" id="codigo_centro_beneficio" placeholder="codigo centro
beneficio" class="input"></input>
<input name="nombre" id="nombre" placeholder="nombre" class="input"></input>
<input name="modelo" id="modelo" placeholder="modelo" class="input"></input>
<input name="numero_serie" id="numero_serie" placeholder="numero_serie" class="input">
</input>
<input name="marca" id="marca" placeholder="marca" class="input"></input>
<input name="numero_remision" id="numero_remision" placeholder="numero remision" class="input">
</input>
<input name="upload" id="upload" class="input" type="file"></input>
<button id="FormSubmit">registrar</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
<ul id="responds" >
</ul>
</div>
</body>
</html>'
and uploadify.php
'
$targetFolder = '/uploads'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$now = time();
$name = $_POST('name')FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
if(file_exists($targetFile)){
++$now;
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
$name $targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo $name;
}
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
}
else {
echo 'Invalid file type.';
}
?>'
I found the answer to this, after a while of searching and reading uploadify manuals, it turns out if you use onUploadComplete, and you just upload one single fine, the method will never excecute, and it will keep waiting for more files, instead for one file only, you have to use onUploadSuccess, and read the data returned by it using file,data,response as parameters.

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')) {

Ajax ready state not stuck on 1

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);
}
}
}

Resources