I am trying to use Dropzone to upload an image file. When the file is selected, I have it checking on the server with an ajax request to see if the file already exists. If so, prompt the user if they want to overwrite.
This all works. If they choose OK to overwrite, it happens, if not , it doesn't happen.
My problem is, they choose not to overwrite, the file doesn't clear from the preview pain. I am using this.removeFile(file) but it stays visible.
var ImageDropzone = new Dropzone("div#ImageDropzone", {
url: "upload.php",
maxFiles: 1,
accept: function(file, done) {
FileExists(file.upload.filename, function(resp) {
if (resp == true)
{
alertify.confirm("This file already exists. Overwrite?", function (e) {
if (e) {
alert("Overwrite");
return done();
}
else {
alert("Dont overwrite");
this.removeFile(file);
return done();
}
})
}
else
return done();
});
},
success: function (file,resp){
alert("Result = " + resp);
var Obj = JSON.parse(resp);
if (Obj.Result == "OK")
{
alert("OK");
// $("#ImageDropzone").hide();
}
else
{
alert(Obj.Message);
}
}
});
You should be fine doing ImageDropzone.removeFile(file) rather than this
Related
I have a following ajax operation that is intended to (1) show spinner gif before sending ajax request, and after after the request is complete, (2) hide the gif and 3 display appropriate alert messages.
Finally (4) reload the page.
Here's the code:
$.ajax({
url: rUrl,
data: {
id: rID,
requisitionStatus: rStatus,
comment: rComment
},
type: "POST",
cache: false,
beforeSend: function() {
$("#requisitionStatusDialog").dialog('close');
$('#ajax_loader_my').show();
},
success: function(data, resp) {
var json = data;
var obj = JSON && JSON.parse(json) || $.parseJSON(json);
if (obj.status == "success") {
alert('Success! ' + obj.message);
location.reload();
} else if (obj.status == "error") {
alert('Error!' + obj.message);
}
},
error: function(data, resp) {
$("#updateDialog").dialog('close');
console.log(resp);
},
complete: function() {
$('#ajax_loader_my').hide();
}
});
But in this case, alert pops up first while the spinner gif still shows up, and reloads the page after clicking OK.
I even tried hiding the gif in success callback itself instead of using complete:
success: function(data, resp) {
var json = data;
var obj = JSON && JSON.parse(json) || $.parseJSON(json);
if (obj.status == "success") {
$('#ajax_loader_my').hide();
alert('Success! ' + obj.message);
location.reload();
} else if (obj.status == "error") {
alert('Error!' + obj.message);
}
},
Both gives the same result.
The reason your alert pops up before the spinner is hidden is the success code runs before complete which hides the spinner. The reason it reloads is because after the alert you send location.reload();
Check that $('#ajax_loader_my').hide(); is actually hiding the spinner. The element that is or contains the spinner in your html must be have its id set to ajax_loader_my.
If you open Chrome or Firefox Dev tools you should be able to send $('#ajax_loader_my').hide() and see what happens.
Rewrite the code this way, this will put your alert and location related code in event queue which will run when it will be free.
if(obj.status=="success") {
$('#ajax_loader_my').hide();
setTimeout(function(){
alert('Success! '+obj.message);
location.reload();
},0);
}
Hi you should try to use promises here is the documentation Jquery promises, I made this on the fly it can have some errors but is just an example:
$( function() {
function AjaxCall(rID,rStatus,rComment){
return $.ajax({
url: 'request.php',
data: {
id: rID,
requisitionStatus: rStatus,
comment: rComment
},
type: "POST",
cache: false,
beforeSend: function() {
$("#requisitionStatusDialog").dialog('close');
$('#ajax_loader_my').show();
}
})
}
$( "#requisitionStatusDialog" ).dialog();
$("#yourbuttonInputId").on('click',function(event) {
AjaxCall().done(function(data,response){
var obj = JSON.parse(data);
if (obj.status == "success") {
alert('whe are on done!');
}
}).fail(function(data,response){
$("#updateDialog").dialog(' close');
}).always(function(data){
if(confirm('You have finished the request. Click OK if you wish to continue ,click Cancel to reload the page.'))
{
$('#ajax_loader_my').hide();
$("#requisitionStatusDialog").dialog('open');
}else{
location.reload();
}
});
});
} );
EDIT: Check this jsfiddle it will guide you to elaborate your code
Hope it Helps
I would rather suggest to use an empty div or span with an Id.
Than display success in the html of that div.
For Example:
$('#ajax_loader_my').hide();
setTimeout(function () {
$('#successDiv').html('Success! ' + obj.message);
location.reload();
}, 2000);
I am trying to return the url of the uploaded image and make it equal to uploadedurl. This is all in a function that is triggered when a photo is dropped into the upload box. uploadedurl is currently being set to null and is returning this error The provided value 'undefined' is not a valid enum value of type XMLHttpRequestResponseType. in the client console. I am using amazon S3 to store the images That part works the images are stored in the S3 and do have usable urls under the domain. What did I do wrong?
var user = Meteor.user();
var uploadedurl;
Images.insert(newFile, function (error, fileObj) {
if (error) {
//do error
} else {
fileObj.once("uploaded", function () {
uploadedurl=fileObj.url();
document.getElementById("phototag").innerHTML = '<img src="'+uploadedurl+'" >';
});
}
});
});
},
CollectionFS objects include a url() method. In your case use:
fileObj.url();
Note that it may take awhile for large files to finish uploading. fileObj.isUploaded() will be true when the upload is done. fileObj.url() will be null until that time.
In this github ticket #aldeed mentions attaching an event handler to the fileObj to be able to get a callback once the file uploads. This is better than polling with a setTimeout. In your case:
fileObj.once("uploaded", function () {
uploadedurl=fileObj.url();
});
try this..It worked for me
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function(err, fileObj) {
if (err) {
console.log(err);
} else {
var cursor = Images.find(fileObj._id);
var liveQuery = cursor.observe({
changed: function(newImage, oldImage) {
if (newImage.isUploaded()) {
liveQuery.stop();
$("#image" + postId).attr("fileId", fileObj._id);
var fielname = fileObj.original.name;
setTimeout(function() {
var imageUrl = '/cfs/files/images/' + fileObj._id + '/' + fielname;
$("#imagefile" + postId).attr("src", imageUrl);
$("#imagediv" + postId).show();
}, 5000);
}
}
});
}
});});
I am new in client side scripting as well as stackoverflow. I want to change an image(Image URL is coming from the server everytime) of a div on click of a button or anchor. Here is My code for changing image.
$scope.captchaChange = function () {
$http({
method: "POST",
url: 'http://localhost:8080/Project/captcha/captcha',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function (response) {
if (response.imgUrl.length > 0) {
document.getElementById("captchaImg").src = response.imgUrl;
document.getElementById("captchatext").value = response.imgToken;
} else {
alert('no captcha Image Avalable');
}
}).error(function (response) {
//alert("response" + response)
$scope.codeStatus = response || "Request failed";
return false;
});
}
Assuming you're trying to load a new image from the server and replace the current image in the div, you can do it like this:
$('#img-change-btn').click(function() {
var path = response.imgUrl // Or some path;
$('#img-display-div img').attr('src', path)
.attr('alt', $('img', this).attr('title'));
});
Here's working code: http://jsfiddle.net/yV6e6/6/
Note: I've used a bit of JQuery (.click, .empty,.append, etc), you can remove that and use only Javascript if you aren't using the JQuery Library.
I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine for my code as it works differently in different browsers. This is my code so far:
var check_connectivity={
is_internet_connected : function(){
var dfd = new $.Deferred();
$.get("/app/check_connectivity/")
.done(function(resp){
return dfd.resolve();
})
.fail(function(resp){
return dfd.reject(resp);
})
return dfd.promise();
},
}
I call this code in different file as:
if(!this.internet_connected())
{
console.log("internet not connected");
//Perform actions
}
internet_connected : function(){
return check_connectivity.is_internet_connected();
},
The is_internet_connected() function returns a deferred object whereas I just need an answer in true/false. Can anybody tell me about how to achieve this?
$.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.
var check_connectivity = {
...
is_internet_connected: function() {
return $.get({
url: "/app/check_connectivity/",
dataType: 'text',
cache: false
});
},
...
};
Then :
check_connectivity.is_internet_connected().done(function() {
//The resource is accessible - you are **probably** online.
}).fail(function(jqXHR, textStatus, errorThrown) {
//Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
});
As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.
In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.
Do you mean to check the internet connection if it's connected?
If so, try this:
$.ajax({
url: "url.php",
timeout: 10000,
error: function(jqXHR) {
if(jqXHR.status==0) {
alert(" fail to connect, please check your connection settings");
}
},
success: function() {
alert(" your connection is alright!");
}
});
100% Working:
function checkconnection() {
var status = navigator.onLine;
if (status) {
alert('Internet connected !!');
} else {
alert('No internet Connection !!');
}
}
This piece of code will continue monitoring internet connection
click bellow "Run code snippet" button and see it in action.
function checkInternetConnection(){
var status = navigator.onLine;
if (status) {
console.log('Internet Available !!');
} else {
console.log('No internet Available !!');
}
setTimeout(function() {
checkInternetConnection();
}, 1000);
}
//calling above function
checkInternetConnection();
try this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
if (! window.jQuery) {
alert('No internet Connection !!');
}
else {
// internet connected
}
Jquery Plugin for Detecting Internet Connection
you cannot get simple true or false in return, give them a callback handler
function is_internet_connected(callbackhandler)
{
$.get({
url: "/app/check_connectivity/",
success: function(){
callbackhandler(true);
},
error: function(){
callbackhandler(false);
},
dataType: 'text'
});
}
I just use the navigator onLine property, according to W3C http://www.w3schools.com/jsref/prop_nav_online.asp
BUT navigator only tells us if the browser has internet capability (connected to router, 3G or such).
So if this returns false you are probably offline but if it returns true you can still be offline if the network is down or really slow.
This is the time to check for an XHR request.
setInterval(setOnlineStatus(navigator.onLine), 10000);
function setOnlineStatus(online)
{
if (online) {
//Check host reachable only if connected to Router/Wifi/3G...etc
if (hostReachable())
$('#onlineStatus').html('ONLINE').removeAttr('class').addClass('online');
else
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
} else {
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
}
}
function hostReachable()
{
// Handle IE and more capable browsers
var xhr = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP");
var status;
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open("HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
// Issue request and handle response
try {
xhr.send();
return (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304));
} catch (error) {
return false;
}
}
EDIT: Use port number if it is different than 80, otherwise it fails.
xhr.open("HEAD", "//" + window.location.hostname + ":" + window.location.port + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
It's working fine for me.
<div id="status"></div>
<script>
window.addEventListener("offline", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "OFFline";
});
window.addEventListener("online", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "Online";
});
</script>
This is my code, which sometimes works and sometimes doesn't.
var resolve_ajax_login=function(){
$.ajaxSetup({cache:false });
var loginvar=$("#inputlogin").attr("value");
var senhavar=$("#inputsenha").attr("value");
$.post("../model/php/login_ajax.php",
{login:loginvar, senha:senhavar},
function(responseText){
if (responseText=="ok"){
window.location="areatrab.php";
}else{
$("#inputlogin").attr("value","");
$("#inputsenha").attr("value","");
$("#divmensagem").html("<span style='color:red;font-size:70%;'>"+responseText+"</span>");
}
}
);
return false;
};
Ok. It's in portuguese but I think you get the general picture. Sometimes this works, no problem, but some other times (only in IE, no problem whatsoever in Firefox) it throws a javascript error in my jquery.js file (minified). The error description is as follows:
Object doesn't support this property or method: jquerymin.js line 123 character 183..
which amounts to...
{return new A.XMLHttpRequest}
somewhere in the middle of the jquery.js file. It seems to be very IE-specific, as I had no such problems on Firefox. This guy apparently had the same problem as I did, but got no responses yet.
Has anyone else seen this? Thanks in Advance
P.S.: I run IE 8
Have you tried using a full URL instead of ../model...? For example: http://www.mysite.com/model/login_ajax.php
Also, maybe try modifying the 'xhr' property using jQuery's .ajax method... something like:
var loginvar = $("#inputlogin").val();
var senhavar = $("#inputsenha").val();
var ajax_obj = null;
var resolve_ajax_login = function() {
if(ajax_obj !== null) {
try {
ajax_obj.abort();
} catch(e) {
}
}
ajax_obj = $.ajax({
type: 'POST',
cache: false,
url: '../model/php/login_ajax.php',
data: {login:loginvar, senha:senhavar},
dataType: 'text',
timeout: 7000,
success: function(data)
{
if(response == 'ok') {
alert("right on!");
} else {
alert("not ok");
return;
}
},
error: function(req, reqStatus, reqError)
{
alert("error");
return;
},
'xhr': function() {
if(ajax_obj !== null) {
return ajax_obj;
}
if($.browser.msie && $.browser.version.substr(0,1) <= 7) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return new XMLHttpRequest();
}
}
});
}
It's something to do with the order in which you try all the different types of browsers in order to create the right kind of XMLHTTP REQUEST object.. I'll explain it in more detail in the following page:
AJAX inconsistency in IE 8?