Update div (&PHP variable) upon success of ajax call - javascript

I have an ajax function that is working. I have pasted the onComplete piece of the function below. It correctly returns the image in the following class(es): .paidpromopic .paidpromo-image .thumb.
onComplete: function (filename, json) {
if (json.error) {
App.error(json.error);
$('.paidpromopic .paidpromo-image .thumb').show();
} else if (json.success) {
var image = new Image();
image.src = json.success;
image.onload = function () {
$('.paidpromopic .paidpromo-image .thumb').attr('src', image.src).show();
$('.avatar-next').show();
}
[HERE IS WHERE I'M HOPING TO WRITE ONE LINE TO UPDATE $currentimage]
}
Following (.paidpromopic .paidpromo-image .thumb), I have a div (id="new_image_name"). Inside that div, I have the variable $currentimage.
I would like to update the variable $currentimage. The php function called by the ajax function creates a session variable named 'newimage_name'. In the same php function, I have also set $currentimage = 'newimage_name'.
Is there are line of code I can include in the onComplete piece above that will update div id="new_image_name"

Related

Run another function after loading the Image

$(document).on('change', '#id_edit_profile_photo', e => {
uploadPhoto(avatarElem, previewPPContainer, avatarUploadElem)
});
function uploadPhoto(elem, preview, uploadElem) {
elem.addClass('d-none');
preview.removeClass('d-none');
preview.find('img').attr('src', '');
let blobUrl = URL.createObjectURL(uploadElem.files[0]);
preview.find('img').attr('src', blobUrl);
// call this fuunction after completing the above task
ImageLoaded();
}
function ImageLoaded() {
_IMAGE_WIDTH = $("#drag-image").width();
_IMAGE_HEIGHT = $("#drag-image").height();
_IMAGE_LOADED = 1;
alert('Image Loaded');
}
The uploadPhoto function runs when value of the file input tag #id_edit_profile_photo changes. Inside the uploadPhoto blobUrl variable stores the url of the loaded file. The url is then set to an img tag. How do I allow the ImageLoaded function to run only after the img tag has loaded the image.
Any help is appreciated.
Thank you.

Unable to declare variable within callback in Rails App

I'm currently working on a Rails 6 application using trubolinks. I'm working on a function to reaplace an avatar placeholder with the image selected upon upload. However, something weird is happening I'm declaring two variables, one is stated with a value the over does not.
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
/**
* Display the image in the file input when added to the form.
* Replace avatar with image selected.
*/
const profileAvatarBlock = document.getElementById('profile-avatar');
function showImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
let avatarPreview = document.getElementById('profile-avatar-preview');
let img =avatarPreview.children[1].setAttribute("src", e.target.result);
debugger;
['width', 'height'].forEach(attribute => {
img.removeAttribute(attribute)
});
debugger;
};
reader.readAsDataURL(input.files[0]);
}
}
profileAvatarBlock.addEventListener('change', function() {
showImage(this);
})
}
});
At first I thought that it was because of turbolinks so I add "turbolinks:load", but this didn't change anything. When I check for avatarPreview I get back back in the debugger but when I check img I get undefined. if I run avatarPreview.children[1].setAttribute("src", e.target.result); I also get it returned but if I assigned it to img is not working.
Why I cant declare a variable inside the callback? I want to understand dont care much about getting it to work.
You are calling setAttribute to assign e.target.result to the src attribute of the element. Then, you are assigning the return value from that function (which is always undefined) to img.
Try instead:
let img = e.target.result
If you really want to get the value from the children, you can try
let img = avatarPreview.children[1].getAttribute('src')`

function(evt) Javascript File API

I'm having a problem with the Javascript File API. First I'm checking if a form input is valued, and if the form input type=file name is image, I want it to get the image:
function checkIfValued() {
$("form input, textarea").change(function() {
// ifs ....
else if (name === "image") {
checkQrCode();
}
// else ifs ....
});
}
Getting the image:
function checkQrCode(evt) {
var qrcode = evt.target.files[0]; // create a FileList and take the first one
if (!qrcode.type.match("image.*")) { // check to see if it is an image
var $parentDiv = $(this).parent().parent();
$parentDiv.removeClass("has-success");
$parentDiv.addClass("has-error");
return;
}
var reader = new FileReader(); // create a FileReader
reader.onload = function (evt) {
var img = new Image(); // create a new image
img.src = event.target.result; // set the src of the img to the src specified
if ($("#qrcode").siblings().length != 0) { // if qrcode has siblings (function already executed)
$("#qrcode").siblings().remove(); // remove the siblings
}
$("#qrcode").parent().append(img); // append the img to the parent
$("#qrcode").siblings("img").addClass("img-thumbnail");
$("#qrcode").siblings("img").css("float", "left");
}
reader.readAsDataURL(qrcode);
}
When I used :
$("#qrCode").change(checkQrCode);
It worked, but when I use the first code it doesn't. I guess it has something to do with the event in the checkQrCode function (in the last code, the event is tied directly to the function and in the second code it has an if statement in the way).
Anyway, how can I fix it and if someone could explain the event/evt option, it would be very appreciated.
Your checkQrCode function expects to receive the triggered event, which is given as an argument in the event callback.
When you call it like this:
$("#qrCode").change(checkQrCode);
... then that even is being passed to the function by the callback. However in your first example you're ignoring the event and calling your event-expecting function with no arguments.
You'd want it to look more like this:
$("form input, textarea").change(function(evt) {
// ...
checkQrCode(evt);

jQuery, update content when necessary

I'm trying to update contents of a chat located in div (div1) but only when the contents of div1 change (a message was submitted into db and picked up in div1).
I tried the solution from here but my get fails to compare the data.
This solution works perfectly but without content comparison:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
jQuery('#div1').load('index.php #div1 > *');
}
This is the modification based on this, which fails:
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",2000);
}
function startTime()
{
var $main = $('#div1');
$.get('chat.php #div1', function (data)
{
if ($main.html() !== data) $main.html(data);
});
}
I tried various modifications of this code but to no avail...
I can't reload the entire page and I don't want to do this if not necessary since it makes the chat harder to read if you have to scroll trough the messages.
How can this be fixed?
UPDATE
Based on #T.J's suggestions I modified the code which now works perfectly:
window.onload = startInterval;
function startInterval()
{
setInterval(startTime,3000);
scrolDown();
}
function startTime()
{
var $main = $('#div1');
$.get('#div1', function (data)
{
elements = $(data);
thisHTML = elements.find("#div1").html();
if ($main.html() !== thisHTML) {
$main.html(thisHTML);
scrolDown();
}
});
}
The other problem was that get required library:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
which apparently was not required by the load which I used previously.
You want to use get, but you want the fragment feature of load, so you'll have to do that work yourself. Then remember what you got last time, and only update if it's not the same:
var lastHTML;
function startTime()
{
var $main = $('#div1');
$.get('chat.php', function (data) // <== Or index.php, the question has both
{
var elements, html;
// Turn the HTML into elements
elements = $(data);
// Get the HTML of *only* the contents of #div1
html = elements.find("#div1").html();
// If that has changed, use it
if (lastHTML !== thisHTML) {
lastHTML = thisHTML;
$main.html(thisHTML);
}
});
}
Note that that's a fairly basic implementation of the fragment feature (it doesn't, for instance, strip out scripts the way load does). You may want to look at how load does its fragment stuff and replicate that (the joy of open source).

How to stop Ajax image load calling a new function?

I'm doing something like this ->
$("<img>").attr("src", "path/to/image.jpg").load(function(){
$("#thediv").append(this);
});
so i can append the new image when the image is completely loaded
I have a timer to call this function with new parameters every 6 seconds.... but I want to call a function to load a new set of images but I have this old set running in background ( asynchronous ) and i need to stop that load so the image won't append beacuse i don't want that image and I'm trying to load a whole new different set of images... I was thinking on something like :
function loadNewSet(){
window.stop(); // i don't quite know if this exist or works but
//should stop all ajax request taking place at that time
loadImages(); // call some function to load the new set
}
/*//*///*///*///*///*///*/
To be more specific:
I have a div called thediv where I'll be placing my images
then I have set of images or an array
set1 = ['img1','img2','img3']
and
set2 = ['img4','img5','img6']
and i have thetimer set on the
$(document).ready(function(){
thetimer=setTimeout("nextSlide()",6000);
});
then i have nextSlide()
function nextSlide(){
//this is where i load the next image on the active set (set 1 or set 2)
img.load(function(){
thetimer=setTimeout("nextSlide()",6000); // and then i set the timer again
});
}
but when the nextSlide() function is called it'd be like idle while the new image is loading and after it loads it'd the things it's supposed to do on load() but what it while loading i call this function loadNewSet()
function loadNewSet(set){
clearTimeout(thetimer);
//this is wheere i want to stop any image loading called by any other function
stopAllImagesLoading();//example
//then change activeset
activeSet=set; // set1 or set2
nextSlide();
}
Don't quite know if I'm doing this the right way and may be I can't put down the procces here the way I'm doing it.
Thanks for your responses.
You can spawn up "worker processes" by using setTimeout.
var proc;
somefunc();
function somefunc() {
//do stuff
proc = setTimeout(somefunc, 6000);
}
//...
clearTimeout(proc); //Cancel the looping somefunc from executing.
What if instead of appending, you do something like....
<div id="myDiv">
<img id="myImg" style="display: none">
</div>
...
function loadImg(url){
$("#myImg").attr("src", url).load(function(){
if(url == $(this).attr(url)){
// The currently requested image has loaded. Show it.
$(this).show();
}
else{
// Finished loading an image that we don't need anymore. Do nothing.
}
});
}
So if you called:
loadImg("a.jpg");
loadImg("b.jpg");
a.jpg might or might not finish first, but it doesn't matter because once a.jpg finishes, nothing happens.
Try using a global variable to turn on or off the timer. For instance (pseudo-code only):
var gKeepRunning = true; //KEY TO ANSWER HERE
myRepeatingImageLoader(); //this is the method that will repeat
function myRepeatingImageLoader(){
$("<img>").attr("src", "path/to/image.jpg").load(function(){
$("#thediv").append(this);
});
if( gKeepRunning == true ) //KEY TO ANSWER HERE - WILL STOP WHEN SET TO FALSE
var junk = setTimeout('myRepeatingImageLoader();', 6000); //Repeat again
}
function loadNewSet(){
gKeepRunning == false; //KEY TO ANSWER HERE
loadImages();
}
Found the anwser here:
Javascript: Cancel/Stop Image Requests
if(window.stop !== undefined)
{
window.stop();
}
else if(document.execCommand !== undefined)
{
document.execCommand("Stop", false);
}

Categories

Resources