Refresh Jsson gallery after Ajax query - ajax

I am developing a Jssor gallery in which I change the path of the images dynamically with Ajax. It turns out that everything works fine until I load the new images without refreshing the page. The styles are not loaded well. I have read that it is necessary to re-initialize Jssor after the modifications but I do not get it. Let's see if someone can help me. Thank you very much and sorry for my bad English.
Jssor function:
function ScaleSlider() {
var jssor_1_slider;
jssor_1_slider_init = function() {
var jssor_1_options = {
$AutoPlay: 1,
$SlideshowOptions: {
$Class: $JssorSlideshowRunner$,
$TransitionsOrder: 1
},
$ArrowNavigatorOptions: {
$Class: $JssorArrowNavigator$
},
$ThumbnailNavigatorOptions: {
$Class: $JssorThumbnailNavigator$,
$Rows: 2,
$SpacingX: 14,
$SpacingY: 12,
$Orientation: 2,
$Align: 156
}
};
jssor_1_slider = new $JssorSlider$("jssor_1", jssor_1_options);
var MAX_WIDTH = 960;
var containerElement = jssor_1_slider.$Elmt.parentNode;
var containerWidth = containerElement.clientWidth;
if (containerWidth) {
var expectedWidth = Math.min(MAX_WIDTH || containerWidth, containerWidth);
jssor_1_slider.$ScaleWidth(expectedWidth);
}
else {
window.setTimeout(ScaleSlider, 30);
}
$Jssor$.$AddEvent(window, "load", ScaleSlider);
$Jssor$.$AddEvent(window, "resize", ScaleSlider);
$Jssor$.$AddEvent(window, "orientationchange", ScaleSlider);
}
};
Ajax script:
$(document).ready(function() {
$('#btnchange').on('click', function(){
$.ajax({
type: "POST",
url: "alternative.php",
data: $("#data1").serialize(),
success: function(response) {
$('#jssor_1').html(response);
//At this point is where I try to start it but I do not get it
}
});
});

Helo Jssor, I have solved my code in this way. Thank you so much for all your help.
HTML:
I preload the images in the first category. With the 2 buttons I will call Ajax to modify the folder with the images of the gallery
<div class="gallery">
<input type="hidden" id="data1" name="category" value="cat1">
<button id="btn1" class="btn-gal"><span>Category 1</span></button>
<input type="hidden" id="data2" name="category" value="cat2">
<button id="btn2" class="btn-gal""><span>Category 2</span></button>
</div>
<div id="jssor_1" style="position:relative;margin:0 auto;top:0px;left:0px;width:980px;height:480px;overflow:hidden;visibility:hidden;">
<div data-u="loading" class="jssorl-009-spin" style="position:absolute;top:0px;left:0px;width:100%;height:100%;text-align:center;background-color:rgba(0,0,0,0.7);">
<img style="margin-top:-19px;position:relative;top:50%;width:38px;height:38px;" src="img/spin.svg" />
</div>
<div data-u="slides" style="cursor:default;position:relative;top:0px;left:0px;width:980px;height:380px;overflow:hidden;">
<?php
$directory = 'images/gallery/cat1/';
$dirint = dir($directory);
while (($archivo1 = $dirint->read()) !== false){
if (preg_match("/jpg/i", $archivo1)){
echo '<div>
<a href="'.$directory.$archivo1.'" >
<img data-u="image" src="'.$directory.$archivo1.'"/>
</a>
<img data-u="thumb" src="'.$directory.$archivo1.'"/>
</div>';
}
}
$dirint->close();
?>
</div>
<div data-u="thumbnavigator" class="jssort101" style="position:absolute;left:0px;bottom:0px;width:980px;height:100px;background-color:#000;" data-autocenter="1" data-scale-bottom="0.75">
<div data-u="slides">
<div data-u="prototype" class="p" style="width:190px;height:90px;">
<div data-u="thumbnailtemplate" class="t"></div>
<svg viewbox="0 0 16000 16000" class="cv">
<circle class="a" cx="8000" cy="8000" r="3238.1"></circle>
<line class="a" x1="6190.5" y1="8000" x2="9809.5" y2="8000"></line>
<line class="a" x1="8000" y1="9809.5" x2="8000" y2="6190.5"></line>
</svg>
</div>
</div>
</div>
<!-- Arrow Navigator -->
<div data-u="arrowleft" class="jssora106" style="width:55px;height:55px;top:162px;left:30px;" data-scale="0.75">
<svg viewbox="0 0 16000 16000" style="position:absolute;top:0;left:0;width:100%;height:100%;">
<circle class="c" cx="8000" cy="8000" r="6260.9"></circle>
<polyline class="a" points="7930.4,5495.7 5426.1,8000 7930.4,10504.3 "></polyline>
<line class="a" x1="10573.9" y1="8000" x2="5426.1" y2="8000"></line>
</svg>
</div>
<div data-u="arrowright" class="jssora106" style="width:55px;height:55px;top:162px;right:30px;" data-scale="0.75">
<svg viewbox="0 0 16000 16000" style="position:absolute;top:0;left:0;width:100%;height:100%;">
<circle class="c" cx="8000" cy="8000" r="6260.9"></circle>
<polyline class="a" points="8069.6,5495.7 10573.9,8000 8069.6,10504.3 "></polyline>
<line class="a" x1="5426.1" y1="8000" x2="10573.9" y2="8000"></line>
</svg>
</div>
</div>
<script type="text/javascript">jssor_1_slider_init();</script>
**The image folders in my system are "images/gallery/cat1" and "images/gallery/cat2"
Script:
Here are the functions for the buttons. Below is the gallery code. Each one that configures it with the options that he wants. I think it would be too much text if I write everything.
var jssor_1_slider;
$(document).ready(function() {
$('#btn1').on('click', function(){
$.ajax({
type: "POST",
url: "alternative.php",
data: $("#data1").serialize(),
success: function(response) {
jssor_1_slider.$ReloadSlides(response);
}
});
});
$('#btn2').on('click', function(){
$.ajax({
type: "POST",
url: "alternative.php",
data: $("#data2").serialize(),
success: function(response) {
jssor_1_slider.$ReloadSlides(response);
}
});
});
});
jssor_1_slider_init = function() {
var jssor_1_SlideshowTransitions = [
...
...
...
];
var jssor_1_options = {
...
...
...
};
jssor_1_slider = new $JssorSlider$("jssor_1", jssor_1_options);
var MAX_WIDTH = 980;
function ScaleSlider() {
...
...
...
}
ScaleSlider();
$Jssor$.$AddEvent(window, "load", ScaleSlider);
$Jssor$.$AddEvent(window, "resize", ScaleSlider);
$Jssor$.$AddEvent(window, "orientationchange", ScaleSlider);
};
alternative.php:
I scroll through the selected folder and upload the corresponding images in the gallery. The code selects all the JPG files in the folder.
<?php
$cat = $_POST['category'];
$directory = 'images/gallery/'.$cat.'/';
$dirint = dir($directory);
$response_slide='';
while (($archivo1 = $dirint->read()) !== false){
if (preg_match("/jpg/i", $archivo1)){
$response_slide.='<div><img data-u="image" src="'.$directory.$archivo1.'"/><img data-u="thumb" src="'.$directory.$archivo1.'"/></div>';
}
}
$dirint->close();
echo $response_slide;?>
I hope to help someone with this solution.

Please use the $ReloadSlides api method.
$(document).ready(function() {
$('#btnchange').on('click', function(){
$.ajax({
type: "POST",
url: "alternative.php",
data: $("#data1").serialize(),
success: function(response) {
//remove all slides and reload new slides
var slidesHtml = '<div><img data-u="image" src="url" /></div>';
slidesHtml += '<div><img data-u="image" src="url" /></div>';
jssor_1_slider.$ReloadSlides(slidesHtml);
}
});
});
Reference:
https://www.jssor.com/development/api-methods-properties-events.html

I am testing the solution you gave me and it works, but what I was trying to do is something more complicated.
When adding the new images I wanted to load all the .jpg files in a directory. I have done it with PHP in this way:
<?php
$directory = 'images/gallery/dir1/';
$dirint = dir($directory);
while (($archivo1 = $dirint->read()) !== false){
if (preg_match("/jpg/i", $archivo1)){
echo '<div>
<a href="'.$directory.$archivo1.'" >
<img data-u="image" src="'.$directory.$archivo1.'"/>
</a>
<img data-u="thumb" src="'.$directory.$archivo1.'"/>
</div>';
}
}
$dirint->close();
?>
But I do not know how to combine it with the sentences you told me:
var slidesHtml = '<div><img data-u="image" src="url" /></div>';
slidesHtml += '<div><img data-u="image" src="url" /></div>';
jssor_1_slider.$ReloadSlides(slidesHtml);
Let's see if you can think of something. Thank you.

Related

Chart.js 4.0.1 Uncaught ReferenceError: Chart is not defined

I wrote an AJAX Javascript code for my ESP32 datalogger which worked so far using old versions of Chart.js. The website hosted by the ESP32 is not working anylonger if I use a more recent of Chart.js.
The error message I caught is:
Uncaught ReferenceError: Chart is not defined at datalogin.html
The line in the code involved is this one
const myChart = new Chart(ctx, config);
Something in the interpretation seems to occur at a very early stage. But I could not identify what. See code below.
I already tried different Chart.js repository in order to have it working. It had absolutly no influence. I actively looked using different browser regarding this specific problematic and I could not find any way of solving this problem.
Thanks a lot for your support
<!DOCTYPE html>
<html lang="en">
<head>
<title>EFM Meter loggin interface</title>
<link rel="icon" type="image/x-icon" href="lightning.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script type="module" src="https://github.com/cdnjs/cdnjs/blob/master/ajax/libs/Chart.js/4.0.1/chart.js" ></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns#2.0.1/dist/chartjs-adapter-date-fns.bundle.js"></script>
<style>
.jumbotron {
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div class="jumbotron text-center">
<h1>Elektrofeldmeter Data Logging Page</h1>
</div>
<div class="container">
<div class="border border-2 m-2">
<div class="row">
<div class="col-sm-12 ">
<div class="container-sm">
<canvas id="myChart" style="" height="152"></canvas>
</div>
</div>
</div>
</div>
<div class="row">
<div class="border border-2 m-2">
<div class="col-sm-12">
<h3> Parameters setup</h3>
</div>
</div>
<div class="border border-2 m-2">
<div class="row">
<div class="col-sm-12">
<label for="customRange1" class="form-label" id="labelPWM">PWM of motor: 190</label>
<input type="range" class="form-range" min="0" max="190" step="1" value="190" onchange="rangeValue(this)" id="customRange1">
</div>
<div class="col-sm-6">
<label for="customRange2" class="form-label" id="labelYmin">Y min: -5000</label>
<input type="range" class="form-range" min="-5000" max="5000" step="1" value="-5000" onchange="rangeY()" id="Ymin">
</div>
<div class="col-sm-6">
<label for="customRange2" class="form-label" id="labelYmax">Y max: +5000 0</label>
<input type="range" class="form-range" min="-5000" max="5000" step="1" value="5000" onchange="rangeY()" id="Ymax">
</div>
<div class="col-sm-12">
<button type="button" class="btn btn-primary" onclick="saveAs()">*.CSV</button>
</div>
</div>
</div>
</div>
</div>
<script>
function rangeValue(element) {
console.log(element.value);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/pwm?value="+element.value, true);
xhr.send();
document.getElementById("labelPWM").innerHTML = "PWM of motor: " + element.value;
};
function rangeY() {
myChart.options.scales.y.max = document.getElementById('Ymax').value;
myChart.options.scales.y.min = document.getElementById('Ymin').value;
myChart.update();
};
function clkOrientation(element) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/clk?value="+element.checked, true);
xhr.send();
}
const animation = { };
const config = {
type: 'line',
data: {
datasets: [{
borderColor: '#fc9905',
borderWidth: 2,
radius: 0,
data: 0
}
]
},
options: {
animation,
interaction: {
intersect: false
},
plugins: {
legend: false
},
scales: {
x: {
type: 'time',
title: {
display: true,
text: 'time',
color: '#000000',
font: {
size: 20
}
},
ticks :
{
color: '#000000',
font: {
size: 12
}
}
},
y: {
type: 'linear',
title: {
display: true,
text: 'Electrical field [V/m] # PWM=190',
color: '#000000',
font: {
size: 20
}
},
ticks :
{
color: '#000000',
font: {
size: 12
}
}
}
},
plugins: {
title: {
display: true,
text: 'Electrical field value [V/m]'
}
}
}
};
Chart.defaults.font.size = 20;
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, config);
function addData(chart, data) {
for (var i = 0 ; i < data.length; i++){
chart.data.datasets[0].data.push({"x":data[i].x,"y":(data[i].y-32.671)/0.48025});
};
chart.update();
};
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var txt = this.responseText;
var array = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
addData(myChart,array);
}
};
xhttp.open("GET", "readEFM", true); //Handle readADC server on ESP32
xhttp.send();
};
setInterval(function() {
getData();
}, 5000);
txt = '[{"x":1662921606250,"y":35.71},{"x":1662921606450,"y":35.61},{"x":1662921606650,"y":35.70},{"x":1662921606850,"y":35.74},{"x":1662921607050,"y":35.78},{"x":1662921607250,"y":35.45},{"x":1662921607450,"y":35.65},{"x":1662921607650,"y":35.66},{"x":1662921607850,"y":35.78},{"x":1662921608050,"y":35.76}]';
const myArr = JSON.parse(txt);
addData(myChart,myArr);
myChart.update();
function saveAs(){
let csvContent = "data:text/csv;charset=utf-8,";
for (var i = 0 ; i < myChart.data.datasets[0].data.length; i++){
csvContent+=myChart.data.datasets[0].data[i].x + "," + myChart.data.datasets[0].data[i].y + "\n";
}
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "EFM_log.csv");
document.body.appendChild(link);
link.click();
};
</script>
</body>
</html>

I am send dropzone file through ajax but it show ERROR : "You did not select a file to upload" in Codeigniter 3

View
Image
<!------------------------ Bootstarp Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/bootstrap.min.css');?>" >
<!------------------------ Dropzone Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/dropzone.min.css');?>" >
<label class="form_lable">Select Image </label>
<div class="dropzone-container col-md-6" id="demo-dropzone" >
`your text`
<p >
<div class="dz-default dz-message" >
<div class="dz-icon">
<i class="demo-pli-upload-to-cloud icon-5x"></i>
</div>
<div>
<span class="dz-text">Drop files to upload</span>
<p class="text-sm text-muted">or click to pick manually</p>
</div>
</div>
<div class="fallback">
<input type="file" name="userfile" id="userfile" />
</div>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submit_btn">Submit</button>
</div>
</form>
">
">
">
$('#demo-dropzone').dropzone({
url:"",
autoProcessQueue: false,
addRemoveLinks: true,
multiple:false,
uploadMultiple:true, // uplaod files in a single request
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 500,
acceptedFiles: ".jpg, .png, .jpeg",
init: function() {
var myDropzone = this;
myDropzone.on('maxfilesexceeded', function(file) {
this.removeAllFiles();
this.addFile(file);
});
this.on("removedfile", function(file) {
});
// Update selector to match your button
$("#submit_btn").click(function(e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on("successmultiple", function(file, response) {
if (response && file) {
console.log(response);
}
});
}
});
# Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image_upload extends CI_Controller
{
public function index(){
$this->load->view('image_send');
}
`File upload funxction`
public function do_upload(){
$image_name = $_FILES['file']['name'][0];
$target= $_FILES['file']['tmp_name'][0];
$target_file = basename($image_name);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$custom_file=basename(uniqid().'.'.$imageFileType);
if(is_dir('upload_image')){
echo "is present";
}
else{
mkdir('upload_image');
}
$config['upload_path'] = 'upload_image/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $image_name;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if ($this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
?>
First of all you need to fix your view to have tag to warp out your input.
<form role="form" id="yourFormId" action="#" method="post" enctype='multipart/form-data'></form>
Second, get your form id and set the ajax like this
var frm = $('#yourFormId');
frm.submit(function (e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#yourFileInputID').prop('files')[0];
form_data.append('file', file_data);
$.ajax({
type : "POST",
url : TheUrl,
processData : false,
contentType : false,
cache : false,
data : form_data,
dataType : 'json',
success: function (data) {
//Your Code Goes Here..//
}, error: function () {
// Your Code Goes Here //
}
});
});

how to Upload files with progress bar in Ajax with asp.net core

I wrote the file upload codes with Ajax and they work fine, but I could not write the percentage of file upload progress. I want to use a progress bar for the percentage of progress. Please write a sample of my code with the progress bar. Thanks
I wrote the file upload codes with Ajax and they work fine, but I could not write the percentage of file upload progress. I want to use a progress bar for the percentage of progress. Please write a sample of my code with the progress bar. Thanks
<td class="d-flex justify-content-around">
<div>
<label asp-for="mostanadPath" class="btn btn-outline-info">
انتخاب تصویر
<span class="oi oi-file h5 text-dark"></span>
</label>
<span class="text-center mt-2" id="spnImageCartMlie" style="color: black;font-size: 12px"></span>
</div>
<div>
<input type="button" onclick="UploadImage()" value="آپلود فایل" class="btn btn-outline-danger" id="btnUpLoad" />
<div id="divmessage" class="text-center hidden m-2"></div>
<input class="d-none" value="#ViewBag.proID" name="id" />
</div>
<input id="newCartMlieImagePathName" name="newCartMlieImagePathName" hidden />
<input id="mostanadPath" asp-for="mostanadPath" type="file" class="d-none">
<div class="mt-5 col-6">
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>
</div>
</td>
<script>
$("#mostanadPath").change(function () {
var filename = this.files[0].name;
$("#spnImageCartMlie").html(filename);
});
</script>
<script>
var UploadImage = function () {
var data = new FormData;
var file = $("#mostanadPath").get(0);
var files = file.files;
//کنترل سایز فایل
if (files[0].size >= 5120000) {
$("#spnImageCartMlie").removeClass('hidden');
$("#spnImageCartMlie").text('حجم فایل بیش از 500 کیلوبایت است');
$("#spnImageCartMlie").css("color", "red");
return false;
}
for (var i = 0; i < files.length; i++) {
data.append('filearray', files[i]);
data.append('filesize', files[i].size);
}
data.append('path', "img\\mostandat\\");
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete + '%');
$('.progress-bar').html(percentComplete + '%');
}
}, false);
return xhr;
},
url: '#Url.Action("UploadImageFile", "Project")',
type: "POST",
data: data,
contentType: false,
processData: false }).done(function (result) {
if (result.status == "success") {
toastr.success('فایل با موفقیت آپلود شد', {
timeOut: 2000,
closeButton: true,
});
$("#newCartMlieImagePathName").val(result.imagename);
}
}).fail(function (result) {
if (result.status != "success") {
toastr.warning('در حین آپلود مشکلی بوجود آمد', {
timeOut: 2000,
closeButton: true,
});
}
});
}
</script>
public IActionResult UploadImageFile(IEnumerable<IFormFile> filearray, String path)
{
String fileName = _uploadFiles.UploadFilesFunc(filearray, path);
return Json(new { status = "success", imagename = fileName });
}
You can use this JQuery code in your <script>:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
},
url: yoururl,
type: "POST",
data: data,
contentType: false,
processData: false
success: function(result) {
console.log(result);
}
});
and Add this code in your page
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>
then you can see the progress bar when you upload file.
===============================================
If you want only one button,you can use this code:
<input type="file" id="files" />
<script>
$("#files").change(function () {
$.ajax({
//........
});
})
</script>
=================================================
I just add the code I gave you above to ajax
<div class="container mt-4 col-2">
<table class="table table-bordered">
<tbody class="text-center">
<tr>
<td>
<label asp-for="mostanadPath" class="btn btn-outline-info">
Image selection
<span class="oi oi-file h5 text-dark"></span>
</label>
</td>
</tr >
<tr>
<td>
<span class="text-center" id="spnImageCartMlie" style="color: black;font-size: 12px"></span>
<input id="newCartMlieImagePathName" name="newCartMlieImagePathName" hidden />
</td>
</tr>
<tr>
<td>
<input type="button" onclick="UploadImage()" value="Upload and display the image" class="btn btn-outline-danger" id="btnUpLoad" />
</td>
</tr>
<tr>
<td>
<div id="divmessage" class="text-center hidden"></div>
</td>
</tr>
</tbody>
</table>
<input asp-for="mostanadPath" type="file" class="d-none" >
</div>
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>
#section Scripts {
<script>
$("#mostanadPath").change(function () {
var filename = this.files[0].name;
$("#spnImageCartMlie").html(filename);
});
</script>
<script>
var UploadImage = function () {
var data = new FormData;
var file = $("#mostanadPath").get(0);
var files = file.files;
//File size control
if (files[0].size >= 512000) {
$("#spnImageCartMlie").removeClass('hidden');
$("#spnImageCartMlie").text('The file size is more than 500 KB');
$("#spnImageCartMlie").css("color", "red");
return false;
}
for (var i = 0; i < files.length; i++) {
data.append('filearray', files[i]);
data.append('filesize', files[i].size);
}
data.append('path', "img\\mostandat\\");
$.ajax({
//add here......
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
},
type: "post",
url: '/Home/UploadImageFile',
data: data,
contentType: false,
processData: false
}).done(function (result) {
if (result.status == "success") {
$("#divmessage").text("Upload was successful.");
$("#divmessage").css("color", "green");
$("#divmessage").removeClass("hidden");
$("#newCartMlieImagePathName").val(result.imagename);
}
}).fail(function (result) {
if (result.status != "success") {
$("#divmessage").css("color", "red");
$("#divmessage").removeClass("hidden");
$("#divmessage").text("There was a problem uploading.");
}
});
}
</script>
}

Google chart does not redraw the chart based on a new Ajax filter

How can I make this code update the google chart with new Ajax call data? When I submit from the dropdown list I see the updated data in the echoed results but the chart does not update. It seems like I have place the submit code in the wrong place.
<title>Google Chart in PHP and MySQL</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var drawChart;
$(document).ready(function () {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
$(".submit").click(function() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON",
success: function (result) {google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(function () {drawChart(result);
});
}
});
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
var dataArray = [];
$.each(result, function (i, obj) {
dataArray.push([obj.Gender, parseInt(obj.HowMany)]);
});
data.addRows(dataArray);
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});
</script>
</head>
<body>
<center>
<img src="logo.png" style="width:200px;height:60px;">
</center>
<hr style="border: 4px solid blue;" />
<table class="columns" style="width:120%">
<tr>
<td>
<label>Gender filter</label>
<?php
//Connect to our MySQL database using the PDO extension.
$pdo = new PDO('mysql:host=localhost;dbname=panel', 'root', '');
//Our select statement. This will retrieve the data that we want.
$sql = "SELECT DISTINCT Gender FROM employee GROUP BY Gender";
//Prepare the select statement.
$stmt = $pdo->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$Ngender = $stmt->fetchAll();
?>
<!--Start here -->
<form method="post" action="indexdash2.php">
<select name="filter">
<option value="" disabled selected hidden>Choose a filter</option>
<?php foreach($Ngender as $Ngender): ?>
<option value="<?= $Ngender['Gender']; ?>"><?= $Ngender['Gender']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Find">
</form>
</td>
</table>
<hr style="border: 4px solid blue;" />
<h2>DEMOGRAPHICS</h2>
<table class="columns">
<tr>
<td>
<div id="piechart_div" style="border: 1px solid #ccc"></div>
</td>
</tr>
</table>
</body>
</html>
Any help will be appreciated! I am pretty sure I have missed something basic as I am new to this.
first, google's load method only needs to be called once per page load.
afterwards, you can draw the chart, or charts, as many times as needed.
next, google's load method will also wait on the page to load by default.
so we can use load in place of jquery's ready method.
recommend loading google first,
then make the call to get the data and draw the chart.
see following snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
function getData() {
$.ajax({
url: "datagen2_2.php",
dataType: "JSON"
}).done(function (result) {
drawChart(result);
});
}
$('.submit').click(getData);
getData();
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Gender');
data.addColumn('number', 'HowMany');
$.each(result, function (i, obj) {
data.addRow([obj.Gender, parseInt(obj.HowMany)]);
});
var piechart_options = {
title: 'Gender breakdown',
width: 470,
height: 270,
colors: ['#800080', '#b200ff']
};
var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
piechart.draw(data, piechart_options);
}
});

Image deleted but page not refreshed ajax laravel

Hi there I am having a problem when I click button delete it deletes the folder with image inside and that is what I want but the page it is not refreshed so I do not know that is deleted till I click refresh
this is the code:
#if($question->question_image)
<img src="{{url('/')}}/images/questions/{{ $question->id }}/medium/{{ $question->question_image }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#else
<img src="{{ asset('noavatars/no-image-selected.png') }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#endif
</div>
{{-- <button type="button" class="btn" id="question_upfile"
style="cursor:pointer; padding-left: 24px; padding-right: 15px;">
<i class="fa fa-upload" aria-hidden="true">
</i>#lang('buttons.upload_image')
</button> --}}
<button type="button" value="{{-- {{ $i }} --}}" class="btn btn-flat btn-default btn-sm delete_image" id="delete_image" title="#lang('buttons.remove_option')"><i class="fa fa-trash-o" aria-hidden="true"></i> </button>
and the javascript code is this:
<script>
$(document).on("click", "button[id=delete_image]", function(data){
var questionid = {{$question->id}};
var element = 'questions';
$.ajax({
type: "POST",
url: "{{ action('website\images\ImagesController#deleteImage') }}",
data: {
_token: "{{ csrf_token() }}",
'id':questionid,
'element' : element,
},
success: function(response) {
console.log(response);
},
error: function(response){
alert("fail");
}
});
function readquestionURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#question_image_box')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
});
</script>
The controller is this:
public function deleteImage($element =null, $id = null){
if(request()->ajax()) {
$id = request()->input('id');
$element = request()->input('element');
if($element != null && $id != null){
Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id);
}
return 1;
}
}
How can I achieve to delete the image and be refreshed at the same time. Can someone please help me thank you very much .
You can refresh the page using javascript
location.reload();
You'll need to add that line on your ajax's success method.

Resources