File uploader using jquery ajax - javascript

I want to upload file using jQuery, but I am getting an exception saying undefined is not a function at $('#myFile').ajaxForm({
HTML
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="jquery-1.11.1.min.js"></script>
<script src="x.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="/FileUploadUI5/upload"
method="POST" id="myFile">
<input type=file name=upfile><br> <input type="submit"
name="Upload" value="Upload" id="ubutton" />
</form>
</body>
</html>
X.js
$(document).ready(function() {
$(function() {
$('#myFile').ajaxForm({
beforeSend : function() {
},
uploadProgress : function(event, position, total, percentComplete) {
alert(position + "|" + total + "|" + percentComplete);
},
complete : function(xhr) {
// status.html(xhr.responseText);
}
});
});
$('#ubutton').click(function(e) {
$('#myFile').submit();
});
});

I believe sending files is not available in pure jquery. I did it few days ago using plugins;
http://rubaxa.github.io/jquery.fileapi/
or
https://github.com/blueimp/jQuery-File-Upload
The first one is really impressive; i was able to do it in no time and visual progress indicatior and ability to use webcam for images is astonishing.
more in the topic You can find here, i think: How can I upload files asynchronously?
hope it helps :-)

Related

How do I run JS code when a user uploads files?

I want the message You uploaded a file! to pop up after I select a file.
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#uploadme").click(function() {
alert("You uploaded a file!")
});
});
</script>
</head>
<body>
<input type="file" id="uploadme"/>
</body>
</html>
Please consider adding a comment if you think this post can be improved.
I managed to solve this problem using a listener.
<input type="file" id="uploadme">
<script>
const fileSelector = document.getElementById('uploadme');
fileSelector.addEventListener('change', (event) => {
alert('You uploaded a file!')
});
</script>

JavaScript function $ is not defined

Hi i'm a beginner in JavaScript i have this code below that allows me to upload a file and send it to the Server to get back a response, that part works fine but the problem is that i after i get back the data i don't want to be redirected to the API link i want to make it so that i stay in the current page and get the data in the alert i'm not sure if there's anything wrong with my function but it keeps giving me this error in the console ReferenceError: $ is not defined. Any help would be much appreciated thank you!
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<form action=" API link " class="upload" id="file-upload" method="post"
enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload file" name="submit">
</form>
<script>
$(function()
{
$('#file-upload').upload({
maxFiles: 1,
acceptedFiles: ".pdf,.doc,.docx,.html",
dataType: "json",
success : function(data) {
alert(data.xhr.response);
}
});
});
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</body>
</html>
You are referring to jQuery, after you define functions.
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head></head>
<body>
<form action=" API link " class="upload" id="file-upload" method="post"
enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload file" name="submit">
</form>
NO IT IS NOT. :D Edited after the comment by #rncrtr -->
$(function()
{
$('#file-upload').upload({
maxFiles: 1,
acceptedFiles: ".pdf,.doc,.docx,.html",
dataType: "json",
success : function(data) {
alert(data.xhr.response);
}
});
});
Remember, browser always render the content in the order of Left to Right, then Top to Bottom. This means, by the time it tries to execute the jQuery snips you have written, it should know about jQuery of $. Otherwise, it will say that $ is undefined. This actually means that reference to your jQuery library file, should appear at the top of the document, that you are having jQuery snips in it.
EDIT: Moved the jQuery reference to the bottom after the suggestion by #rncrtr.
Add onclick event in button:
<input type="submit" value="Upload file" name="submit" onclick="uplaod(); return false">
Add this in Script File:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function uplaod()
{
$('#file-upload').upload({
maxFiles: 1,
acceptedFiles: ".pdf,.doc,.docx,.html",
dataType: "json",
success : function(data) {
alert(data.xhr.response);
}
});
}
</script>
This is because you are loading jquery library after the code snippet.Load it before any other code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function()
{
$('#file-upload').upload({
maxFiles: 1,
acceptedFiles: ".pdf,.doc,.docx,.html",
dataType: "json",
success : function(data) {
alert(data.xhr.response);
}
});
});
</script>
Load jQuery in head and add your script tag at the end of body tag
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
For reference https://www.w3schools.com/jquery/jquery_get_started.asp

jQuery Validation Plugin - remove 'http://' requirement with URL's

I'm looking to validate a URL without requiring the user to enter "http://". How it is in the form below, "http://" must be entered for the form to be submitted. I can't figure out how to do this. Any help would be much appreciated.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and a url.</title>
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="field">Required, URL: </label>
<input class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
url: true
}
}
});
</script>
</body>
</html>
Edit: Took isherwood's advice:
var txt = $('#website').val();
var http = txt.indexOf('http://');
if (http > -1) {
$('#website').val(txt);
} else {
$('#website').val('http://' + txt);
}
Why not add it to the URL for your users? A URL isn't a URL without a protocol anyway (the exception being protocolless URLs, but they still have '//').
$('#myform').on('submit', function() {
var myURL = 'http://' + $('#field').val();
$('#field').val(myURL);
});
you can use addmethod with REGEX, just add the class from the method to your input
http://jqueryvalidation.org/jQuery.validator.addMethod/

How to Send keyboard data to the Server using getJSON

I am using getJSON to send a request to server and fetch response. When I send an string of text like 'firstname=x' to the server, it works fine, but when I use '$('#input').val()' as input data to the server, it returns nothing as response.
Here is the jquery code
<!DOCTYPE html>
<html>
<head>
<title>Request in getJSON</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(){
var req=$('#query').val();
var data='firstname=req';
$.getJSON('http://..../server.php?callback=?', data,function(res){
alert('Your name is '+res.fullname);
});//getJSON
}); //onclick
});//on document ready
</script>
</head>
<body>
<h1> Enter Name </h1>
<input type='text' id='query' />
<input type="button" id="button" value="submit" />
<div id="results"></div>
</body>
</html>
Hope you can help me
Thank you
Try with this one:
$(document).ready(function(){
$('#button').click(function(e){
e.preventDefault();
var data={firstname : $('#query').val()}; //<--------try like this
$.getJSON('http://..../server.php?callback=?', data,function(res){
alert('Your name is '+res.fullname);
});//getJSON
}); //onclick
});//on document ready

My Javascript Ajax request works in Phonegap index.html but not in any other pages, how can I fix this?

The request I have made works in the index.html file but not in any others which is greatly frustrating. I think it is to do with the onDeviceReady function but I am not sure how to change or fix this?
Here is the separate page (not index.html) code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;" />
<script src="cordova-1.8.1.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/load-whites.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
</head>
<body>
<div data-role="page" id="whites">
<div data-role="header" data-position="fixed">
<h1>White Wines</h1>
</div>
<div data-role="content">
<div data-role="collapsible-set" data-theme="c" data-content-theme="d">
<div id="whites"></div>
</div>
</div>
</div>
</body>
Here is the request that works for the index.html file but not for any other .html files in my phonegap project (Cordova 1.8.1). How could I change it so that it does work? the file below is load-whites.js:
$(document).ready(function(){
$(document).bind('deviceready', function(){
onDeviceReady();
});
function yourCallback(button) {
if (button == 2) {
dataRequest();
}
}
function dataRequest() {
var output = $('#whites').text('Loading white wines and their deta1ils, please wait...');
$.ajax({
url: 'http://localhost/whites.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
output.empty();
$.each(data, function(i,item){
var whites = '<div data-role="collapsible"><h3>'+item.Name+'</h3>'
+'<b>Price:</b> £'+item.Price+'<br />'
+'<b>Vintage:</b> '+item.Vintage+'<br />'
+'<b>Country:</b> '+item.Country+'<br />'
+'<b>Grape:</b> '+item.Grape+'<br />'
+'<b>Alcohol:</b> '+item.Alcohol+'%<br /><br />'
+item.Description+'</p></div>';
output.append(whites);
$('#whites').trigger('create');
});
},
error: function(){
output.text('The Wines could not be loaded at this time.');
navigator.notification.confirm(
'Please check your internet connection. Would you like to retry?',
yourCallback,
'Something went wrong',
'No,Yes'
);
}
});
}
dataRequest();
});
Any help would be greatly appreciated. Thanks again.
I see you are using JQuery mobile. Its possible it could be similar to a problem I had today and JQuery mobile was the culprit. http://jquerymobile.com/demos/1.1.1/docs/pages/page-scripting.html
If you are declaring the Javascript file in the header another page other than the index, it will ignore it. If this is your problem, declare the JS file load-whites.js in the index then..
$( document ).delegate("#PAGENAME", "pageinit", function() {
//do work here
});
Not sure if this is your problem, but could be!

Categories

Resources