Croppie returns black images after cropping - javascript

I am working on a project in which I want to implement croppie js with modal. For that i found a codepen which suits my requirement. But the problem is that after performing crop the resulted image is black.
Can anyone help me with this. The link of the codepen is provided below: https://codepen.io/asrulnurrahim/pen/WOyzxy
// Start upload preview image
$(".gambar").attr("src", "https://user.gadjian.com/static/images/personnel_boy.png");
var $uploadCrop,
tempFilename,
rawImg,
imageId;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.upload-demo').addClass('ready');
$('#cropImagePop').modal('show');
rawImg = e.target.result;
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 150,
height: 200,
},
enforceBoundary: false,
enableExif: true
});
$('#cropImagePop').on('shown.bs.modal', function(){
// alert('Shown pop');
$uploadCrop.croppie('bind', {
url: rawImg
}).then(function(){
console.log('jQuery bind complete');
});
});
$('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
$('#cancelCropBtn').data('id', imageId); readFile(this); });
$('#cropImageBtn').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
format: 'jpeg',
size: {width: 150, height: 200}
}).then(function (resp) {
$('#item-img-output').attr('src', resp);
$('#cropImagePop').modal('hide');
});
});
// End upload preview image
label.cabinet{
display: block;
cursor: pointer;
}
label.cabinet input.file{
position: relative;
height: 100%;
width: auto;
opacity: 0;
-moz-opacity: 0;
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);
margin-top:-30px;
}
#upload-demo{
width: 250px;
height: 250px;
padding-bottom:25px;
}
figure figcaption {
position: absolute;
bottom: 0;
color: #fff;
width: 100%;
padding-left: 9px;
padding-bottom: 5px;
text-shadow: 0 0 10px #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://foliotek.github.io/Croppie/croppie.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://foliotek.github.io/Croppie/croppie.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<div class="container">
<div class="row">
<div class="col-xs-12">
<label class="cabinet center-block">
<figure>
<img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" />
<figcaption><i class="fa fa-camera"></i></figcaption>
</figure>
<input type="file" class="item-img file center-block" name="file_photo"/>
</label>
</div>
</div>
</div>
<div class="modal fade" id="cropImagePop" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">
<?=multiLanguage( "Edit Foto" , "Edit Photo" )?></h4>
</div>
<div class="modal-body">
<div id="upload-demo" class="center-block"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="cropImageBtn" class="btn btn-primary">Crop</button>
</div>
</div>
</div>
</div>

Related

Pass the Message project problem with setTimeout or setInterval

I'm making beginner javascript pass the message project I'm having a problem with this: If no input is submitted, an alert should show (using the ‘show' class in the CSS file) in the “Last Message Delivered” section and then disappear after 2 second. I don't know setTimeout and setInterval methods really good and how to break them but if someone could help.
const adder = document.getElementById('message-form')
const cont = document.querySelector('.boxer')
const feeder = document.querySelector('.feedback')
let counter = 0;
adder.addEventListener('submit', e => {
e.preventDefault();
let texto = adder.oop.value
if (texto.length) {
html = `
<div class="boxerr">
<h5 class="p-2 alert alert-danger my-3 text-capitalize feedback">please enter a value to pass</h5>
<h4 class="text-capitalize my-3">last message delivered</h4>
<h4 class="message-content text-uppercase">${texto}</h4>
</div>
`
cont.innerHTML += html
adder.reset()
} else {
let timer = setTimeout(() => {
counter++
feeder.classList.toggle('show')
if (counter === 2) {
clearTimeout(timer)
}
}, 100);
}
});
:root {
--lightBlue: #95b8d1;
--mainwhite: #f5f5f5;
--mainBlack: #333333;
}
.max-height {
min-height: 100vh;
}
body {
background: var(--lightBlue);
}
.message-container {
background: var(--mainwhite);
}
.message-content {
color: var(--lightBlue);
}
#submitBtn {
background: var(--lightBlue);
color: var(--mainwhite);
}
#submitBtn:hover {
color: var(--lightBlue);
color: var(--mainBlack);
}
.feedback {
display: none;
}
.show {
display: block;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container">
<div class="row max-height align-items-center">
<div class="col-10 mx-auto col-md-8 message-container text-center p-3">
<h4 class="text-capitalize">A messge you would like to pass</h4>
<form id="message-form">
<input type="text" name="oop" id="message" class="w-100 my-3 p-2">
<input type="submit" id="submitBtn" class="btn btn-lg">
</form>
<div class="boxer">
<div class="boxerr">
<h5 class="p-2 alert alert-danger my-3 text-capitalize feedback">please enter a value to pass</h5>
<h4 class="text-capitalize my-3">last message delivered</h4>
<h4 class="message-content text-uppercase">hello world</h4>
</div>
</div>
</div>
</div>
</div>
You can do something like this in the else block:
feeder.classList.add("show");
setTimeout(() => feeder.classList.remove("show"), 2000);
This code will add the show class to the .feedback element and after 2000 milliseconds (i.e. 2 seconds as 1000ms = 1s) the show class will be removed from the .feedback element.
Complete Code:
const adder = document.getElementById('message-form')
const cont = document.querySelector('.boxer')
const feeder = document.querySelector('.feedback')
let counter = 0;
adder.addEventListener('submit', e => {
e.preventDefault();
let texto = adder.oop.value
if (texto.length) {
html = `
<div class="boxerr">
<h4 class="text-capitalize my-3">last message delivered</h4>
<h4 class="message-content text-uppercase">${texto}</h4>
</div>
`
cont.innerHTML += html
adder.reset()
} else {
feeder.classList.add("show");
setTimeout(() => feeder.classList.remove("show"), 2000);
}
});
:root {
--lightBlue: #95b8d1;
--mainwhite: #f5f5f5;
--mainBlack: #333333;
}
.max-height {
min-height: 100vh;
}
body {
background: var(--lightBlue);
}
.message-container {
background: var(--mainwhite);
}
.message-content {
color: var(--lightBlue);
}
#submitBtn {
background: var(--lightBlue);
color: var(--mainwhite);
}
#submitBtn:hover {
color: var(--lightBlue);
color: var(--mainBlack);
}
.feedback {
display: none;
}
.show {
display: block;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container">
<div class="row max-height align-items-center">
<div class="col-10 mx-auto col-md-8 message-container text-center p-3">
<h4 class="text-capitalize">A messge you would like to pass</h4>
<form id="message-form">
<input type="text" name="oop" id="message" class="w-100 my-3 p-2">
<input type="submit" id="submitBtn" class="btn btn-lg">
</form>
<h5 class="p-2 alert alert-danger my-3 text-capitalize feedback">please enter a value to pass</h5>
<div class="boxer">
<div class="boxerr">
<h4 class="text-capitalize my-3">last message delivered</h4>
<h4 class="message-content text-uppercase">hello world</h4>
</div>
</div>
</div>
</div>
</div>

how do i open modal with javascript. without using jquery

How do I make a modal visible with javascript? I don't want to do it using jquery. i just want it with javascript. And I don't want it to open when I click a button. I want it to be opened as a result of some operations in javascript. I made it with modal bootstrap. my codes are below.
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="modal fade" tabindex="-1" id="sonucModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Test Durumu</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="durum"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Çıkış</button>
<button type="button" class="btn btn-primary">2. Aşamaya Geç</button>
</div>
</div>
</div>
</div>
<div class="container" style="height: 100vh;">
<div class="row" style="height: 100vh;">
<div class="col-md-12 d-flex justify-content-center" style="height: 400px;">
<div class="card" style="width: 25rem; margin-top:20vh; ">
<div class="card-body" style="text-align: center;">
<h5 class="card-title text-primary">Soru</h5>
<span class="text-black-50 fs-5" id="soru"></span>
<input class="w-100 form-control mt-4" type="text" id="cevap"/>
<button class="btn btn-outline-primary mt-4 w-100" id="ok">Tamam</button>
</div>
<ul class="list-group list-group-flush">
<li id="anaCan" class="list-group-item fw-bold">Kalan Can: <span id="can"></span></li>
</ul>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
javascript code:
var turkceCumleler = [
"Merhaba",
"İyi Sabahlar",
"İyi Günler",
"İyi Akşamlar",
"İyi Geceler",
"Tekrar Görüşmek Üzere(Yüz yüze)",
"Tekrar Görüşmek Üzere(Tel.)",
"Yakında Görüşürüz",
"Güle Güle"
];
var almancaCumleler = [
"hallo",
"guten morgen",
"guten tag",
"guten abend",
"gute nacht",
"auf wiedersehen",
"auf wiederhögen",
"bis bald",
"tschüss"
]
var sayilar = [];
var healt = 3;
const getQuestion = () =>{
document.getElementById('can').textContent=healt;
let rastgele = Math.floor(Math.random()*turkceCumleler.length);
if(sayilar.indexOf(rastgele) === -1){
sayilar.push(rastgele)
document.getElementById('soru').textContent = turkceCumleler[rastgele];
document.getElementById('cevap').value = ""
}else{
getQuestion();
}
if(sayilar.length === turkceCumleler.length){
//here i want modal to open
}
}
const compareQuestionAnswer = () =>{
if(document.getElementById('cevap').value === ''){
alert("boş geçilemez")
}else{
let deger = almancaCumleler.indexOf(document.getElementById('cevap').value.toLowerCase());
if(deger === -1){
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}else{
let deger1 = turkceCumleler.indexOf(document.getElementById('soru').textContent);
if(deger === deger1){
getQuestion();
}else{
healt--;
document.getElementById('can').textContent=healt;
if(healt === 0){
document.getElementById('anaCan').style.color='red';
document.getElementById('ok').disabled = true;
}
}
}
}
}
window.onload = getQuestion;
document.getElementById('ok').addEventListener('click',compareQuestionAnswer);
document.getElementById('anaCan').style.color='green';
Bootstrap depends on jQuery, and you're already including jQuery in your code.
But if you want to create a modal without Bootstrap and jQuery, you can do so with CSS and JavaScript. Use an event listener to listen for whatever JavaScript event you desire, then show the modal when that event occurs.
Here is a simple example:
// Show the modal when you hover over the red box
trigger.onmouseover = () => {
modal.style.display = "block";
}
// Hide the modal when you click the close button
document.getElementsByClassName("close")[0].onclick = () => {
modal.style.display = "none";
}
// Hide the modal if you click outside of the modal area
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
}
#trigger {
height: 100px;
width: 100px;
background-color: red;
}
.modal {
display: none; /* Hidden Initially */
position: fixed;
z-index: 1; /* Higher Z-Index To Sit On Top */
left: 0;
top: 0;
width: 100%; /* Full Width */
height: 100%; /* Full Height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div id="modal" class="modal">
<!-- Modal Content -->
<div class="modal-content">
<span class="close">x</span>
<p>Modal content here</p>
</div>
</div>
<div id="trigger">
Move mouse into this box to trigger modal.
</div>
You just need to declare a new modal object, like:
const sonucModal= document.getElementById('sonucModal');
const modalEl = new bootstrap.Modal(sonucModal);
and then call it like this whenever you need to open it:
modalEl.show();
Here is a JSFiddle for reference, the modal opens automatically after 2 seconds.

How to use Cropper.js with images that are already uploaded to my server instead of cropping and then uploading image to correct folder

Hi I'm new to Js so not really sure how to figure this one out. I have a user pictures gallery on my website and I use simple php file upload script to upload pictures for my users. I have a button under each picture to set given image as a profile pic but I'm in need of getting this picture cropped to correct aspect ratio so I tried using Cropper.js. The problem is I can't find a way to pass an image to cropper.js. else than creating an upload form. I've spent days trying to google the way I could use cropperjs without this upload form but can't seem to find a way. It's my first question on stackoverflow any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>PHP Crop Image Before Upload using Cropper JS</title>
<meta name="_token" content="{{ csrf_token() }}">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha256-WqU1JavFxSAMcLP2WIOI+GB2zWmShMI82mTpLDcqFUg=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" integrity="sha256-jKV9n9bkk/CTP8zbtEtnKaKf+ehRovOYeKoyfthwbC8=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js" integrity="sha256-CgvH7sz3tHhkiVKh05kSUgG97YtzYNnWt6OXcmYzqHY=" crossorigin="anonymous"></script>
</head>
<style type="text/css">
img {
display: block;
max-width: 100%;
}
.preview {
overflow: hidden;
width: 160px;
height: 160px;
margin: 10px;
border: 1px solid red;
}
.modal-lg{
max-width: 1000px !important;
}
</style>
<body>
<div class="container">
<h1>PHP Crop Image Before Upload using Cropper JS - NiceSnippets.com</h1>
<form method="post">
<input type="file" name="image" class="image">
</form>
</div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">PHP Crop Image Before Upload using Cropper JS - NiceSnippets.com</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<div class="row">
<div class="col-md-8">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
<div class="col-md-4">
<div class="preview"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var $modal = $('#modal');
var image = document.getElementById('image');
var cropper;
$("body").on("change", ".image", function(e){
var files = e.target.files;
var done = function (url) {
image.src = url;
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
$("#crop").click(function(){
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
$.ajax({
type: "POST",
dataType: "json",
url: "upload.php",
data: {image: base64data},
success: function(data){
console.log(data);
$modal.modal('hide');
alert("success upload image");
}
});
}
});
})
</script>
</body>
</html>

Ajax post request to .NET Core action and getting result not working

I need to implement email sending modal popup and I'm almost done except ajax send request not hit to success or failure
When I click the send button (id:end-email) It successfully hit the .NET Core action and action return status correctly.
But the problem is my ajax call not waiting for the result and automatically closing popup which is not required. I need to show the message instead of closing popup.
<div id="sendemail-window" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="sendemail-window-title">
<div class="modal-dialog" style="width: 50%;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" style="font-weight:600;" id="sendemail-window-title">Shipment Request Email </h4>
</div>
<form id="InStockPendingShipments" name="InStockPendingShipments">
<input type="hidden" id="selectedPOIds" name="selectedPOIds" value="" />
<div class="form-horizontal">
<div class="modal-body">
<div class="form-group">
<div class="col-md-2">
<nop-label asp-for="SendEmail.Subject" />
</div>
<div class="col-md-9">
<nop-editor asp-for="SendEmail.Subject" />
<span asp-validation-for="SendEmail.Subject"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<nop-label asp-for="SendEmail.Message" />
</div>
<div class="col-md-9">
<nop-textarea asp-for="SendEmail.Message" />
<span asp-validation-for="SendEmail.Message"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-1">
</div>
<div class="col-md-10">
<ul id="selected-po-list" class="selected-po-list">
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<div class="input-group input-group-short">
<label id="lblSaveResult" name="lblSaveResult" style="margin-top: 10px;font-weight: 500;"></label>
</div>
<div class="form-group">
<div class="col-md-1">
</div>
<div class="col-md-10">
<button class="btn btn-primary" id="send-email">
Send Email
</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#send-email').click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("SendInStockRequestEmail","InStockPendingShipments")',
data: emailData(),
success: function (msg) {
alert("111 success");
},
error: function (req, status, error) {
alert(22225,error);
}
})
.done(function () {
alert("success");
})
.fail(function () {
alert(44444,"error");
});
});
});
function emailData() {
var data = {
SelectedPOIds: $("#selectedPOIds").val(),
Message: $('##Html.IdFor(model => model.SendEmail.Message)').val(),
Subject: $('##Html.IdFor(model => model.SendEmail.Subject)').val()
};
addAntiForgeryToken(data);
return data;
}
$('#sendemail-window').on('show.bs.modal', function () {
$('#SendEmail_Message').val('');
document.getElementById("SendEmail_Message").innerHTML = "";
getInStockProductListByIds($("#selectedPOIds").val());
});
function getInStockProductListByIds(selectedPOsIds) {
var idListData = {
Ids: selectedPOsIds
};
addAntiForgeryToken(idListData);
$.ajax({
cache: false,
type: "POST",
url: "#(Url.Action("getInStockProductListByIds", "InStockPendingShipments"))",
data: idListData,
success: function (result) {
if (result.Data != null || result.Data != '') {
$('#selected-po-list').html('');
$('#selected-po-list').delegate('li');
$('#selected-po-list').append('<li class="list-header"><table><tr>' +
'<td style="width: 10%;font-weight: 600;"> SKU </td>' +
'<td tyle="font-weight: 600;">ProductNane</td>' +
'<td style="font-weight: 600;width: 20%;font-weight:600;text-align: right;position: relative;">Quantity</td>' +
'</tr></table ></li> ');
for (var i = 0; i < result.Data.length; i++) {
console.log('electedPOs', result.Data[i].SKU);
$('#selected-po-list').append('<li><table><tr>' +
'<td style="width: 10%;"> <a target="_blank" href="/admin/Product/Edit/' + result.Data[i].ProductId + '">' + result.Data[i].SKU + '</a></td>' +
'<td>' + result.Data[i].ProductNane + '</td>' +
'<td style="width: 20%;font-weight:600;text-align: right;position: relative;"> <div class="product-count">' + result.Data[i].Quantity + '</div></td>' +
'</tr></table ></li> ');
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to find dispatch information.');
return null;
}
});
}
</script>
<style>
.selected-po-list {
list-style: none;
padding-left: 0;
margin-top: 30px;
max-height: 280px;
overflow-y: auto;
}
.selected-po-list li {
height: 50px;
padding: 10px;
margin-bottom: 5px;
border: 1px solid #00c0ef47;
}
.selected-po-list li table {
width: 100%;
}
.product-count {
position: absolute;
color: white;
height: 25px;
top: 0;
right: 10px;
text-align: center;
padding: 2px 0 0 0;
width: 25px;
border-radius: 50px;
background-color: #3c8dbc;
}
.list-header {
background-color: #7cc3ff30 !important;
height: 25px !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
</style>
</div>
</form>
</div>
</div>
</div>
This is my action and it's working fine it returns string message
public virtual IActionResult SendInStockRequestEmail(string SelectedPOIds, string Message, string Subject)
{
var inStockIds = new List<int>(Array.ConvertAll(SelectedPOIds.Split(','), Convert.ToInt32));
string message = _inStockPendingShipmentService.SendInStockShipmentRequestEmail(inStockIds, Message, Subject);
return Json(new DataSourceResult { Data = message });
}
The default type of <button> is submit which submits the form data to the server . You can use input button instead :
<input type="button" class="btn btn-primary" id="send-email" value="Send Email" />

Javascript state change reverting

I have a simple jQuery app to display images from Giphy based on an ajax call, and toggle animate/stop them on mouseclick by toggling the src URL and data-state attributes.
I'm also displaying a different set of images based on user input.
I have a bug where it only animates gifs displayed after the first ajax call. It doesn't animate gifs displayed by subsequent calls. console-logging for each condition makes me think that for the latter it changes the state and changes it back, but I can't wrap my head around why.
Screencap: https://screencast.com/t/uZCzH6E6hZ8n
$('document').ready(function () {
//array with topics
var topics = [
"Ronaldinho",
"Zidan",
"Messi",
"Maradona",
"Pele"
]
//function loop to display all topics in buttons
function displayTopics() {
for (var i = 0; i < topics.length; i++) {
$('#buttons').append('<div class="btn btn-info get-giphy" data-attribute=' + topics[i] +
'>' + topics[i] +
'</div>');
}
}
//call function to display all the topic buttons
displayTopics();
//on clicking button
$('#buttons').on('click', '.get-giphy', function () {
$('#gifs-appear-here').empty();
//set topic to the clicked button's data-attribute
var topic = $(this).attr('data-attribute');
//set query URL to picked topic
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic +
"&api_key=O2X0wRMnWEjylyUypx1F5UVxCz5Jp8kr&limit=10";
//ajax call to Giphy API
$.ajax({
url: queryURL,
method: 'GET'
}).then(function (response) {
console.log(response);
// Storing an array of results in the results variable
var results = response.data;
// Looping over every result item
for (var i = 0; i < results.length; i++) {
// Only taking action if the photo has an appropriate rating
if (results[i].rating !== "r") {
// Creating a div with the class "item"
var gifDiv = $("<div class='item'>");
// Storing the result item's rating
var rating = results[i].rating;
// Creating a paragraph tag with the result item's rating
var p = $("<p>").text("Rating: " + rating);
// Creating an image tag
var topicImage = $("<img>");
// Giving the image tag necessary attributes
topicImage.attr({
"class": "topicImage",
"src": results[i].images.fixed_height_still.url,
"data-state": "still",
"data-still": results[i].images.fixed_height_still.url,
"data-animate": results[i].images.fixed_height.url
});
// Appending the paragraph and personImage we created to the "gifDiv" div we created
gifDiv.append(topicImage);
gifDiv.append(p);
// Prepending the gifDiv to the "#gifs-appear-here" div in the HTML
$("#gifs-appear-here").prepend(gifDiv);
}
}
});
$('#gifs-appear-here').on('click', '.topicImage', function () {
var state = $(this).attr("data-state");
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
console.log('still --> animate');
} else if (state === "animate") {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
console.log('animate --> still');
}
else {
return false;
}
});
});
//add buttons
$('button[type="submit"]').click(function () {
var inputValue = $('.form-control').val().trim();
//don't add buttons if they're already in topics array
if (topics.includes(inputValue)) {
$('.modal').modal('show');
$('.modal-body').html('You already have a button for <b>' + inputValue +
'</b>. Use it or add something else');
setTimeout(function () {
$('.modal').modal('hide');
}, 4000);
//add buttons if they aren't in the topics array
} else {
topics.push(inputValue);
$('#buttons').empty();
displayTopics();
}
});
//get form input on pressing "enter key"
$('.form-control').keypress(function (e) {
if (e.which == 13) { //Enter key pressed
$('button[type="submit"]').click(); //Trigger search button click event
}
});
});
.row {
margin-top: 30px;
}
.col {
background-color: #eee;
padding: 15px;
border-radius: 10px;
}
.get-giphy {
margin: 0 15px 15px 0;
}
.topicImage {
max-width: 100%;
}
#media all and (min-width: 768px) {
#buttons {
border-right: 15px solid #fff;
}
#formWrap {
border-left: 15px solid #fff;
}
}
#media all and (max-width: 768px) {
#buttons {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
#formWrap {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
}
#media all and (max-width: 575px) {
.row {
margin-left: 0;
margin-right: 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="main.js"></script>
<title>Homework 6</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col col-12">
<h1>Who's your favorite Futbol star?</h1>
</div>
</div>
<div class="row">
<div id="buttons" class="col col-12 col-md-6 col-lg-6">Click a button!
<br>
<br>
</div>
<div id="formWrap" class="col col-12 col-md-6 col-lg-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="You can also add more buttons!">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<div class="row">
<div id="gifs-appear-here" class="col col-12">
Your gifs will appear here
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="answerModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Not so fast!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
<script type="text/javascript">
</script>
</body>
</html>
As it stands, ('#gifs-appear-here').on('click', '.topicImage', ...) is executed inside the buttons' onclick handler, causing that delegated click handler to accumulate every time one of the buttons is clicked.
To fix, simply move ('#gifs-appear-here').on('click', '.topicImage', ...) out of the buttons' onclick handler.
Here it is (significantly tidied) :
$('document').ready(function () {
var topics = [
"Ronaldinho",
"Zidan",
"Messi",
"Maradona",
"Pele"
];
function displayTopics() {
for (var i = 0; i < topics.length; i++) {
$('#buttons').append('<div class="btn btn-info get-giphy" data-attribute=' + topics[i] + '>' + topics[i] + '</div>');
}
}
displayTopics();
$('#buttons').on('click', '.get-giphy', function () {
$('#gifs-appear-here').empty();
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + $(this).data('attribute') + "&api_key=O2X0wRMnWEjylyUypx1F5UVxCz5Jp8kr&limit=10";
$.ajax({
'url': queryURL,
'method': 'GET'
}).then(function (response) {
var results = response.data;
for (var i = 0; i < results.length; i++) {
if (results[i].rating !== "r") {
var gifDiv = $("<div class='item'/>").prependTo("#gifs-appear-here");
$("<img class='topicImage'/>").attr({
'src': results[i].images.fixed_height_still.url
}).data({
'state': 'still',
'images': results[i].images
}).appendTo(gifDiv);
$('<p/>').text("Rating: " + results[i].rating).appendTo(gifDiv);
}
}
});
});
$('#gifs-appear-here').on('click', '.topicImage', function () {
var data = $(this).data();
if (data.state === 'still') {
$(this).attr('src', data.images.fixed_height.url);
data.state = 'animate';
} else {
$(this).attr('src', data.images.fixed_height_still.url);
data.state = 'still';
}
});
//add buttons
$('button[type="submit"]').click(function () {
var inputValue = $('.form-control').val().trim();
//don't add buttons if they're already in topics array
if (topics.includes(inputValue)) {
$('.modal').modal('show');
$('.modal-body').html('You already have a button for <b>' + inputValue + '</b>. Use it or add something else');
setTimeout(function () {
$('.modal').modal('hide');
}, 4000);
//add buttons if they aren't in the topics array
} else {
topics.push(inputValue);
$('#buttons').empty();
displayTopics();
}
});
//get form input on pressing "enter key"
$('.form-control').keypress(function (e) {
if (e.which == 13) { //Enter key pressed
$('button[type="submit"]').click(); //Trigger search button click event
}
});
});
.row {
margin-top: 30px;
}
.col {
background-color: #eee;
padding: 15px;
border-radius: 10px;
}
.get-giphy {
margin: 0 15px 15px 0;
}
.topicImage {
max-width: 100%;
}
#media all and (min-width: 768px) {
#buttons {
border-right: 15px solid #fff;
}
#formWrap {
border-left: 15px solid #fff;
}
}
#media all and (max-width: 768px) {
#buttons {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
#formWrap {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
}
#media all and (max-width: 575px) {
.row {
margin-left: 0;
margin-right: 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="main.js"></script>
<title>Homework 6</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col col-12">
<h1>Who's your favorite Futbol star?</h1>
</div>
</div>
<div class="row">
<div id="buttons" class="col col-12 col-md-6 col-lg-6">Click a button!
<br>
<br>
</div>
<div id="formWrap" class="col col-12 col-md-6 col-lg-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="You can also add more buttons!">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<div class="row">
<div id="gifs-appear-here" class="col col-12">
Your gifs will appear here
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="answerModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Not so fast!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
<script type="text/javascript">
</script>
</body>
</html>

Categories