I'm trying to upload a file in IE7 and IE8 browser using FileAPI library, but unfortunately it is not working. It is working in all the other browser but not in IE7, IE8 and it is my business requirement to make it work in IE7, IE8 too.
Here is my js code
jQuery(function ($){
$(document)
.on('click', '.imageLabel', function (evt){
imageUploadId = $(this).attr("id").split("_")[1];
previewImage = document.getElementById('previewHolderDiv_' + imageUploadId);
$("#imageError_" + imageUploadId).html("");
errorMessageUl = document.getElementById('imageError_' + imageUploadId);
removeImageIcon = document.getElementById('removeImage_' + imageUploadId);
})
var form = document.forms.vehicleDocumentForm;
var input = form.vehicleImage;
var uploadOpts = {
url: '/save-vehicle-document',
data: {},
name: 'vehicleImage',
activeClassName: 'upload_active'
};
var _onSelectFile = function (evt/**Event*/){
var file = FileAPI.getFiles(evt)[0];
if( file ){
_uploadFile(file, imageUploadId);
}
};
var _uploadFile = function (file){
uploadOpts.data = {"imageId" : imageUploadId};
var opts = FileAPI.extend(uploadOpts, {
files: {},
upload: function (){
form.className += ' '+uploadOpts.activeClassName;
},
complete: function (err, xhr){
//enableSellYourButtons();
form.className = (' '+form.className+' ').replace(' '+uploadOpts.activeClassName+' ', ' ');
var response = JSON.parse(xhr.responseText);
if( response.result == "fail"){
previewImage.html = "";
$("#imageError_" + imageUploadId).html("<li>" + response.message + "</li>");
} else {
$("#imageError_" + imageUploadId).html("");
$("#vehicleImageName_" + imageUploadId).attr("value", response.message);
}
}
});
opts.files[opts.name] = file;
FileAPI.upload(opts);
};
FileAPI.event.on(input, "change", _onSelectFile);
}); // ready
I'm getting an error
SCRIPT445: Object doesn't support this action
File: FileAPI.min.js, Line: 2, Column: 11608
My FileAPI version is 2.0.11
Any help would be greatly appreciated.
Thank you.
According to caniuse, the FileApi is not compatible with IE7/8.
Related
The script makes an ajax call to a PHP file on input change, but the JSON isn't parsing and I don't know why
Here's the Javascript
input.addEventListener("input", (event) => {output.innerHTML = "Cerca " + document.getElementById("tophead-searchbar").value + " su Nevent";
var searchqueryajax = new XMLHttpRequest;
ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
searchqueryajax.addEventListener("load", innerhtmlqueries());
searchqueryajax.open("GET", ajaxquerylink);
searchqueryajax.send();
function innerhtmlqueries() {
queriesarray = JSON.parse(searchqueryajax.responseText);
}
});
The input is document.getElementById("tophead-searchbar") and the output is the Result1, it says the value of the input
Here is the PHP Script:
$query = $_REQUEST["query"];
$queryresults = mysqli_query($name, "SELECT * FROM search_queries WHERE MATCH(ID, QUERY) AGAINST('$query') LIMIT 7");
if ($queryresults->num_rows > 0) {
$autocompleteresults = array();
while($row = mysqli_fetch_array($queryresults)) {
$results["ID"] = $row["ID"];
$results["value"] = $row["QUERY"];
$results["type"] = $row["TIPO"];
array_push($autocompleteresults, $results);
}
}
echo json_encode($autocompleteresults);
There are no PHP errors on the log and i don't see the PHP File on Network Tab of the browser F12 editor
I tried to do some things on Javascript code but i still don't notice the request on Network Tab
Edit: I also have another ajax call like this in the same file and it works
var checkajaxiflogged = new XMLHttpRequest();
checkajaxiflogged.addEventListener("load", checkajaxiflogged_function);
checkajaxiflogged.open("GET", "topbarprofileinformation.php");
checkajaxiflogged.send();
function checkajaxiflogged_function() {
topheadjsonresponse = JSON.parse(checkajaxiflogged.responseText);
document.getElementById("tophead-account-img").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
if (topheadjsonresponse.isloggedin == "yes") {
document.getElementById("tophead-accedi-btn").style.display = "none";
document.getElementById("tophead-account-img").style.display = "block";
document.getElementById("Immagine-Profilo-Menu-Principale").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
document.getElementById("Nome-Profilo-Menu-Principale").innerHTML = topheadjsonresponse.displayname;
document.getElementById("Username-Profilo-Menu-Principale").innerHTML = "#" + topheadjsonresponse.username;
}
}
You can use jquery for simplified get request
input.addEventListener("input", (event) => {
output.innerHTML = "Cerca " + document.getElementById("tophead-
searchbar").value + " su Nevent";
getData(); //Call the get function
});
// Ajax function to get data using jquery
function getData() {
let ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
$.ajax({
url : ajaxquerylink,
type : "GET",
success : function(data)
{
let response = JSON.parse(data);
console.log(response);
}
});
}
I solved by myself, in this row
searchqueryajax.addEventListener("load", innerhtmlqueries);
I removed the () in innerhtmlqueries() and now the call response works
Thanks anyway for the support!
I'm have some serious problems getting any response data through from the mediawiki api.
I'm trying to do the freecodecamp wikipedia viewer challenge and I'm coding it here:
https://codepen.io/dceaser334/pen/zpQXOJ
All i'm trying to do so far is GET the data and print it to the console using the following request:
$('.search-button').on('click', function() {
var searchInput = $('.search-input').val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + searchInput + '&format=json&callback=?', function(data) {
console.log(data);
});
});
All i'm trying to do so far is GET the data and print it to the console using the that request.
I'm getting this error in firefox:
Loading failed for the with source
“https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=jordan&format=json&callback=jQuery32105036538970753343_1518470620925&_=1518470620926”.
index.html:1
Nothing loads to the console and it seems like the request is blocked.
I've tried using origin=* which also makes no difference.
I'm a bit lost because this project has similar code for the GET request and works perfectly:
https://codepen.io/luckyguy73/pen/GqPzZO?editors=1010
$("#searchWiki").click(function(){
var q = document.getElementById("searchid").value;
$('#results').html('');
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=" + q, function(data){
$('#results').append('<h2>Top 15 Wiki Search Results for "' + q + '"</h2>');
$.each(data.query.pages, function (i) {
$('#results').append("<p><a href='https://en.wikipedia.org/?curid=" + data.query.pages[i].pageid +
"' target='_blank'>" + data.query.pages[i].title + "</a></p>");
});
});
});
Any ideas on what I'm doing wrong here?
Thanks
I did it like this. Maybe you will be inspired by analyzing my code?
( function ( $ ) {
"use strict";
$(document).ready(function(){
function loadData() {
$(".information").text(""); // Reset data before new search.
$(function whiteFirst() {
const query = $(".wiki_query").val();
const myFirstWikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&search=";
const mySecondWikiUrl = "&format=json&callback=wikiCallback";
const wikiUrl = myFirstWikiUrl + query + mySecondWikiUrl;
// MY WIKIPEDIA AJAX GOES HERE - TOP
const wikiRequestTimeout = setTimeout(function() {
$(".small-information").html("An error occurred! Application couldn't get Wikipedia resources!");
}, 5000); // This is 5 seconds!
$.ajax({
url: wikiUrl,
dataType: "jsonp",
type: "GET",
}).done(function(result) {
const itemsOne = [];
const itemsTwo = [];
const itemsThree = [];
$(result[1]).each(function(index, value) {
itemsOne.push(value);
});
$(result[2]).each(function(index, value) {
itemsTwo.push(value);
});
$(result[3]).each(function(index, value) {
itemsThree.push(value);
});
$(".information").hide();
$(".results").hide();
for (let i = 0; i < itemsOne.length; i++) {
$(".information").append("<a class='title' href=" + itemsThree[i] + " target='_blank'><div class='result'><p class='title' id='boldTitle'>" + itemsOne[i] + "</p><p>" + itemsTwo[i] + "</p></div></a>");
}
if (itemsOne.length === 0) {
$(".information").html("Nothing found!");
}
$(".results").show();
$("body,html").animate({
'scrollTop': $(".results").offset().top
}, 2000);
$(".information").fadeIn("slow");
clearTimeout(wikiRequestTimeout); // This will prevent timeout from happening!
});
// MY WIKIPEDIA AJAX GOES HERE - BOTTOM
});
return false;
};
$(".whiteButton").click(loadData);
$(".results").hide();
$(function() {
const offset = -50; // Optional offset
$(".back").click(function() {
$("html, body").animate({
scrollTop: $(".cover").offset().top + offset
}, 750);
});
});
});
} ( jQuery ) );
I am REALLY new to Jasmine and am trying to write a unit test that checks if a URL is constructed properly from variables defined by the environment.
describe('URL is built properly', function() {
var newHead = '<!doctype html>' +
'<html class="no-js" lang="">' +
' <head>' +
' </head>' +
'<body>' +
'</body>' +
'</html>';
beforeEach(function() {
ScratchPad.clear();
ScratchPad.add(newHead);
debugger;
spyOn(newSetup.prototype, 'createNewScript');
});
afterAll(function() {
ScratchPad.clear();
});
it('should build Staging', function() {
window.my.env = 'staging';
window.my = {
newScript: {
enabled: true,
location: 'google-com'
}
};
var options = {
windowWidth: 640
};
this.newScript = new newScriptSetup(options);
var newHTML = ScratchPad.find('script')[0].src;
debugger;
expect(newHTML.src).toEqual('http://my.site.com/google-com/myScript.min.js');
});
});
The problem I seem to be having is that;
expect(newHTML.src).toEqual('http://my.site.com/google-com/myScript.min.js');
this bit of the script isn't getting populated, I've tried debugging it and the var newHead is being created, it's just not being seen by the rest of the unit test... I think. Could someone help me out, I've been looking at it all day :(
var newHTML = ScratchPad.find('script')[0].src;
debugger;
expect(newHTML.src)..
You are already getting the src in newHTML. You are trying to check .src.src with the url you provide. Try this:
var newHTML = ScratchPad.find('script')[0].src;
expect(newHTML).toBe(..
Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
I modified an existing AngularJS-App, which lists customers, by adding a button, that allows to download the customer information as a vcard. I create the vcard in Javascript directly on click. The download-button calls the following function on click with the customer-item as argument:
function transcodeToAnsi(content){
var encoding = "windows-1252";
var nonstandard = {NONSTANDARD_allowLegacyEncoding: true};
return new TextEncoder(encoding, nonstandard).encode(content);
}
$scope.download = function(item) {
var filename = 'contact.vcf';
var aId = "vcard";
var content = createVCard(item);
var encoded = transcodeToAnsi(content);
var blob = new Blob([ encoded ], { type : 'vcf' });
var url = (window.URL || window.webkitURL).createObjectURL(blob);
$("body").append('<a id="' + aId + '" href="' + url + '" download=' + filename + ' class="hidden"></a>');
$timeout(function(){
document.getElementById(aId).click();
$("#" + aId).remove();
})
return false;
}
In the createVCard-function I just create the file content as a String, so it should not enter into the problem. The transcoding is done by this library: https://github.com/inexorabletash/text-encoding
The function works without problem in Firefox and Chrome, but not in IE11. The following error is given in the console:
Error: Permission denied
at Anonymous function (http://***/Contacts2015/js/contacts.js:169:9)
at Anonymous function (http://***/static/9bojdXAkdR8XdVMdSTxZAgzEwGWhHMwgpuONdU2Y8F4.js:14305:11)
at completeOutstandingRequest (http://***/static/9bojdXAkdR8XdVMdSTxZAgzEwGWhHMwgpuONdU2Y8F4.js:4397:7)
at Anonymous function (http://***/static/9bojdXAkdR8XdVMdSTxZAgzEwGWhHMwgpuONdU2Y8F4.js:4705:7) undefined
Line 169 is this instruction of the function above:
document.getElementById(aId).click();
The same error is displayed, when this statement is input in the console manually.
I would appreciate every hint about the reason and even more a good workaround.
EDIT
Corrected error-line and typo.
You cannot directly open blobs in Microsoft IE. You must use window.navigator.msSaveOrOpenBlob. There's also msSaveBlob if that's what you need.
$scope.download = function() {
//etc... logic...
var blob = new Blob([encoded], {type: 'vcf'});
//for microsoft IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else { //other browsers
var a = document.createElement('a');
a.style = "display:none";
a.href = URL.createObjectURL(blob);
a.download = "filename.jpg";
a.click();
}
}
One last thing: the previous code won't work on firefox because firefox doesn't support click(). You can prototype its behavior using this snippet:
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}