Loading image using AJAX Request won't work - javascript

I need to use an AJAX request to load a gif image from this source:
http://edgecats.net
Everytime I try to do so and use the response on the image source as:
$('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + data);
It won't work!
When copying the response using firefox's devtools and using:
data:image/gif;base64,<PASTE_HERE>
Everything works like a charm!
How can I figure out how to turn my response into an image correctly?
This is my AJAX request code:
function getCatImg() {
return $.ajax({
type: 'GET',
url: 'http://edgecats.net',
datatype:"image/gif"
});
}
getCatImg().success(function(data) {
$('#cat-thumb-1').attr('src', 'data:image/gif;base64,' + data);
});

You don't need to use Ajax on this particular task. But, if you insist, you must use a trick to make this work:
$(document).ready(function() {
$.ajax('http://edgecats.net', {
success: function(r) {
var reader = new FileReader();
reader.onload = function(e) {
$('img').prop('src', e.target.result);
};
reader.readAsDataURL(new Blob([r]));
}
});
});

I am not familiar with the cats on the edge, but as I've looked at the site, the response was not base64 encoded, so it won't work that way.
How about setting the image src to edgecats.net
$('#cat-thumb-1').attr('src', 'http://edgecats.net');

Related

How to get the Dropzone.js return value?

I just implemented Dropzone.js to make file uploads on my website easier. The file uploads fine, and after it finished uploading I give the file an id and return this id to the browser.
This works fine, except for that I don't know how to catch the id that gets returned from the server. In this SO answer I found some code that should supposedly do that, but it doesn't work for me. The code I have now is pasted below.
Does anybody know how I can get the value that is returned by the server? All tips are welcome!
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="/static/js/external/dropzone.min.js"></script>
<link href="/static/css/external/dropzone.css" rel="stylesheet">
<script type="text/javascript">
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
console.log('WE NEVER REACH THIS POINT.');
alert(response);
}
};
});
</script>
</head>
<body>
<form action="/doc"
class="dropzone"
id="my-awesome-dropzone"></form>
</body>
</html>
Looking at the source code of dropzone.js, it seems that there is a lot of events you can listen to.
events: [
"drop"
"dragstart"
"dragend"
"dragenter"
"dragover"
"dragleave"
"addedfile"
"removedfile"
"thumbnail"
"error"
"errormultiple"
"processing"
"processingmultiple"
"uploadprogress"
"totaluploadprogress"
"sending"
"sendingmultiple"
"success"
"successmultiple"
"canceled"
"canceledmultiple"
"complete"
"completemultiple"
"reset"
"maxfilesexceeded"
"maxfilesreached"
]
Here the "success" event seems to be appropriate.
A good starting point would be to bind an event listener to your dropzone and see what data you get on such event.
$('#my-awesome-dropzone').on('success', function() {
var args = Array.prototype.slice.call(arguments);
// Look at the output in you browser console, if there is something interesting
console.log(args);
});
$("#dropzoneForm").dropzone({
maxFiles: 2000,
url: "../Uploader/HttpUploadHandler.ashx?param=" + result.prjID,
success: function(file, response){
//alert("Test1");
}
});
Does this help?
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
this.on("success", function(file, responseText) {
var responseText = file.id // or however you would point to your assigned file ID here;
console.log(responseText); // console should show the ID you pointed to
// do stuff with file.id ...
});
}
};
For example, I have mine set up to attach the server path to the image name and pass this as a value into a form field on submit. As long as you define responseText to point to the file ID you should get a return on this.
This link might be helpful as well: https://github.com/enyo/dropzone/issues/244
Try this:
Dropzone.options.myAwesomeDropzone = {
success: function(file, response){
//alert(response);
console.log(response);
}
};
It works for me
$(function() {
var myDropzone = new Dropzone(".dropzone");
myDropzone.on("success", function() {
alert('Uploaded!');
});
});
I am using jQuery and this is what worked for me:
var dz = $(".my-awesome-dropzone").dropzone()[0];
dz.dropzone.on("success", function (file, response) { ... }));
Note that the dropzone() method adds an dropzone attribute to the DOM object. You have to call on() on that object - not the jQuery on().
I wanted to add this as a comment, but I can't, since I have a low reputation.
For those of you who still have trouble retrieving the response from the server, if you're using chunking, Dropzone is hard-coding a blank response in this situation:
https://github.com/enyo/dropzone/blob/caf200c13fd3608dd6bed122926d5848927f55b4/dist/dropzone.js#L2344
if (allFinished) {
_this14.options.chunksUploaded(file, function () {
_this14._finished(files, '', null);
});
}
So retrieving the response doesn't seem to be supported for chunked uploads.

Ajax callback appending desired url to existing url

I am trying to make a ajax call back to a Drupal 7. The problem I am encountering is that the url I want to use to make the callback is appended to the current page the user is viewing. I am not sure why this is happening and am wondering if some can point out my error for me. Here is the javascript code I am using to make the call:
(function($) {
function todaysHours(context) {
var callbackFunction = window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
content = $("#todays-hours").find(".block");
nIntervId = setInterval(checkTime, 300000);
function checkTime() {
request = $.ajax({
url: callbackFunction,
dataType: "json",
type: "GET"
});
request.done(function( result ) {
content.text(result[0].data);
})
}
}
Drupal.behaviors.library_hours = {
attach: function(context) {
todaysHours(context);
}
}
})(jQuery);
The url I expect to use is http://mydomain.com/ajax/get-time but what is actually being used in the ajax call is http://mydomain.com/current-page/mydomain.com/ajax/get-time even though the callbackfunction variable is set to mydomain.com/ajax/get-time.
Why is this happening and how do I fix it? Thanks.
Problem:
Protocol is not defined in the url
Solution:
update the following part in the code
(function($) {
function todaysHours(context) {
var callbackFunction = '//'+window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
// rest code
})(jQuery);

How To Call Function on page Loading

I'm Using Web service using AJAX Call In My HTML Page . Web Service Returning Data Nearly 30 to 40 second's .
During This Loading Time I Need to Use Some Loading Gif Images After Data Completely Received Form Web Service The Loading Image Must Be Hide.
I'm Using Only HTML,JAVASCRIPT,CSS,J Query.
Any Idea Or Samples Needed.
I'm Using Following Code
$(document).ready(function () {
document.write('<img src="http://www.esta.org.uk/spinner.gif">');
});
$( window ).load(function() {
//This following Function Related To My Design
jQuery(".chosen").data("placeholder", "Select Frameworks...").chosen();
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
});
In The Above Code My Problem Is On Page Load Gif Image Show But It's Not Hide Only Gif Image Only Showing.
Put a hidden image on your page and as soon as your ajax call is made, make that image visible
$('#image').show();
$.ajax({
complete: function(){
$('#image').hide();
}
});
and hide that image again on Complete of Ajax call.
Use your ajax request callback (on success/failure) instead of page load.
When sending the request just show a gif animation by setting the Display to block
then when you have the data set the display to none
or use jquery
function showHourGlass()
{
$("#gifimage").show();
}
function hideHourGlass()
{
$("#gifimage").hide();
}
You ask for ideas, I have one sample -
http://www.myntra.com/shoes
load scroll down fastly this is the ajax jquery request which is exact output which you have mentioned in your question
Check source code
Jquery Ajax loading image while getting the data
This what the html looks like:
<button id="save">Load User</button>
<div id="loading"></div>
and the javascript:
$('#save').click(function () {
// add loading image to div
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
// run ajax request
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.github.com/users/jveldboom",
success: function (d) {
// replace div's content with returned data
// $('#loading').html('<img src="'+d.avatar_url+'"><br>'+d.login);
// setTimeout added to show loading
setTimeout(function () {
$('#loading').html('<img src="' + d.avatar_url + '"><br>' + d.login);
}, 2000);
}
});
});
I hope this will help you.

jquery $.ajax force POST

I have an ajax function that creates a link that triggers another ajax function. For some reason the second ajax function refuses to go through POST event if I've set type: "POST"
The two functionas are below:
function HandleActivateLink(source) {
var url = source.attr('href');
window.alert(url)
$.ajax({
type: "POST",
url: url,
success: function (server_response) {
window.alert("well done")
}
});
return false;
}
function HandleDeleteLink() {
$('a.delete-link').click(function () {
var url = $(this).attr('href');
var the_link = $(this)
$.ajax({
type: "POST", // GET or POST
url: url, // the file to call
success: function (server_response) {
if (server_response.object_deleted) {
FlashMessage('#form-success', 'Link Deleted <a class="activate-link" href="' + url.replace('delete', 'activate') + '">Undo</a>');
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
the_link.parent().hide();
} else {
var form_errors = server_response.errors;
alert(form_errors)
}
}
});
return false;
});
}
You'll notice HandleDeleteLink creates a new link on success, and generates a new click event for the created link. It all works butHandleActivateLink sends the request to the server as GET. I've tried using $.post instead with no luck.
Any pointers, much appreciated.
In the second event you do not inform the client to prevent the default behaviour.
One way to do this would be to change:
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
to:
$('a.activate-link').click(function(){
return HandleActivateLink($(this));
});
(This works because HandleActiveLink already returns false.)
A nicer way to do this is to pass in the event argument to the click function and tell it to preventDefault
$('a.activate-link').click(function(e){
e.preventDefault();
HandleActivateLink($(this));
});
what is your url?
btw You can't send a cross-domain post via javascript.

Desktop image drag&drop upload crashing browser

I got a form for uploading images through ajaxForm. I have implemented a function so users can drop photos from desktop (HTML5 drag&drop). Every thing works fine if photo is "small" - lets say 2mb. The problem occuress when I try to upload photos that are larger then 4mb. Chrome browser crashes.
AjaxForm
$(document).ready(function() {
$("#uploadForm").ajaxForm({
iframe: true,
dataType:"json",
beforeSubmit: function () {
$("#post .button.save").prop("disabled",true).val("Uploading...");
},
success: function (result) {
$("#FilePhotoString").val("");
$("#post").css({
"background": 'url(' + result + ') no-repeat center center',
"display": "block",
"height": $("body").height(),
"background-size": "cover"
});
$("img").attr("src",result).load(function() {
$('input[name="ImageFilePath"]').attr('value', result);
$("#post .button.save.now").prop("disabled",false).val("Publish now");
$("#post .button.save.later").prop("disabled",false).val("Publish later");
});
}
});
});
Drop
document.body.addEventListener('dragover',function(event) { event.preventDefault(); },false);
document.querySelector('#content').addEventListener('drop', function(event) {
event.preventDefault();
var reader = new FileReader();
reader.onload = function(evt) {
$("#FilePhotoString").val(evt.target.result);
$("#uploadForm").submit();
};
reader.readAsDataURL(event.dataTransfer.files[0]);
}, false);
Result returned on success is just path of uploaded photo. Any ideas what can I do so browser will not crash?
How about taking another approach, like using FormData and sending a file instead of a string.
var data = new FormData(document.getElementById('#uploadForm'));
data.append('theNameYouWantToSend', event.dataTransfer.files[0]);
then send an ajax request
$.ajax({
url:'theurl',
type:'post',
data: data,
contentType:false,
processData:false,
...
});
I think it isnt a jquery/ajax/browser problem. If you are using an apache server for example check the "upload_max_filesize = 2M" located at your php.ini.
The default size is 2mb so it fits you're problem well. The server send a timeout if you try to upload more than 2mb.

Categories

Resources