Jquery UI Progressbar filling reduced progress - javascript

$.get('jobs', {
}, function (responseText) {
rt = JSON.parse(responseText);
console.log(rt);
for (i = 0; i < rt.length; i++)
{
$("#jobs").append("<tr><td><div id='progressbar"+i+"' class='progressbar'></div></td></tr>");
pval = (rt[i][2] / rt[i][1]) * 100;
$("#progressbar"+i).progressbar({
value: pval,
max: 100
});
}
});
I have written this code to make progressbar on a td of each row of a table. When i was doing it for 1 row it worked fine, but after I've added multiple rows in my Db, the values are not coming to be accurate.
even when value of pvalis 100, it is filling like 1/4th of the progress bar.

I was unable to replicate the issue. You may want to edit your post and include more details, example data, and any errors generated by Console.
I created the following test: https://jsfiddle.net/Twisty/0v4q5a8z/
HTML
<div class="ui-widget">
Get Progress
<table id="jobs" width="100%">
<tbody>
</tbody>
</table>
</div>
JavaScript
var progress = [
["p1", 100, 100],
["p2", 100, 75],
["p3", 100, 22]
];
function getProgress(source, target) {
/* Ajax Post used for Example purposes
** Example response:
** Array [
** ["p1", 100, 100],
** ["p2", 100, 80],
** ["p3", 100, 75]
** ]
*/
$.ajax({
url: source,
data: {
json: JSON.stringify(progress)
},
type: "POST",
dataType: "json",
success: function(responseText) {
var rt, pval;
rt = responseText
console.log(rt.toString());
for (i = 0; i < rt.length; i++) {
target.append("<tr><td><div id='progressbar-" + i + "' class='progressbar'></div></td></tr>");
pval = (rt[i][2] / rt[i][1]) * 100;
$("#progressbar-" + i).progressbar({
value: pval,
max: 100
});
}
}
});
}
$(function() {
$(".button").button();
$("#getProgress").click(function(e) {
e.preventDefault();
getProgress("/echo/json/", $("#jobs"));
});
});
This test works as expected. Your code could be less intense. The function could be:
function getProgress(source, target) {
$.getJSON(source, function(responseText) {
var rt, pval;
rt = responseText
for (i = 0; i < rt.length; i++) {
target.append("<tr><td><div id='progressbar-" + i + "' class='progressbar'></div></td></tr>");
pval = (rt[i][2] / rt[i][1]) * 100;
$("#progressbar-" + i).progressbar({
value: pval,
max: 100
});
}
}
});
}

Related

How to draw a line on a highcharts graph from an AJAX call?

I have in my html page a highcharts graph that I want to update dynamically. I have some input boxes that once they get updated by the user, trigger an AJAX post request. The request does some calculations and I want the output to be used to re-draw the line of my chart's second serie . That line represents a simple y = x function, the 'x' variable being calculated during the AJAX call.
Here is my html/JS code for the chart:
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'line',
animation: Highcharts.svg,
marginRight: 10,
},
title: {
text: 'Strategy Payoff'
},
xAxis: {
//type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'PnL',
data: (function () {
var data = [],
time = (new Date()).getTime(),
i;
var V = document.getElementById('V').value;
var Q = document.getElementById('Q').value;
var S = document.getElementById('S').value;
var K = document.getElementById('K').value;
var Type = document.getElementById('Type').value;
if (Type == 'Call') {
direction = 1;
} else {
direction = -1;
}
if (S >= 5000) {
stepSize = 500;
} else if (S >= 500) {
stepSize = 50;
} else {
stepSize = 1;
}
for (i = 0; i <= S * 2; i+=stepSize) { // i+=stepSize
data.push({
x: i,
y: Math.max(-V * Q, -V * Q + Q * direction * (i-K))
});
}
return data;
})()
}, {
name: 'Current Option Strategy PnL',
data: (function pnl(value=10) {
var data2 = [],
time2 = (new Date()).getTime(),
i;
var S = document.getElementById('S').value;
if (S >= 5000) {
stepSize = 500;
} else if (S >= 500) {
stepSize = 50;
} else {
stepSize = 1;
}
for (i = 0; i <= S * 2; i+=stepSize) {
data2.push({
x: i,
y: value
});
}
return data2;
})()
}]
});
});
});
</script>
Here are the input boxes that trigger the AJAX request when updated by the user:
<div class="chart" id="container"></div>
<div class="slider-wrapper">
<span>Option 1 Imp. Vol.</span>
<input class="toChange" id="rangeInput" name="rangeInput" type="range" value="{{Sigma}}" min="0.1" max="150" lang="en_EN" step="0.1" oninput="amount.value=rangeInput.value" />
<input class="toChange" id="amount" type="number" value="{{Sigma}}" min="0.1" max="150" lang="en_EN" step="0.1"oninput="rangeInput.value=amount.value" />
</div>
Finally, here is the AJAX request itself:
<script type="text/javascript">
function inputChange () {
var Sigma = document.getElementById("rangeInput").value;
var Type = document.getElementById('Type').value;
var S = document.getElementById('S').value;
var K = document.getElementById('K').value;
var t = document.getElementById('t').value;
var r = document.getElementById('r').value;
var V = document.getElementById('V').value;
var Q = document.getElementById('Q').value;
$.ajax({
url: '/optionstrategies/',
type: 'POST',
data: {
'Type': Type,
'S': S,
'K': K,
'r': r,
't': t,
'Sigma': Sigma,
},
success: function(optionVal) {
alert((optionVal - V) * Q);
document.getElementById("oPrice").innerHTML = optionVal;
document.getElementById("PnL").innerHTML = (optionVal - V) * Q;
// pnl(12);
}
});
}
$(".toChange").change(inputChange);
</script>
The AJAX call works well as the alert shows the expected value. I now need to use that value to update my chart. So for instance, if the value is equal to 12, I need the second serie of my chart to draw a line representing the y = 12 function.
I've named the function dealing with my second serie 'pnl' as you can see. I've been trying to call that function in the 'success' part of my AJAX request by writing something like 'pnl(12);', but it didn't do anything. Could anybody please help?
Use the series.update feature inside the success call and set the new data on it. Please check the available demos under below link.
API: https://api.highcharts.com/class-reference/Highcharts.Series#update
If this clue wouldn't help, please reproduce a simplified version of your code on some online editor which I could work on.

How to capture the value in array in javascript and return the value in Yii2 controller?

I am trying to generate multiple barcode at a time and save the generated barcode numbers in my database . Still now i have generated
multiple barcode but i had a problem while saving it to database .
My code till now :-
function getbarcode(num,barcode)
{
for (var i = 1; i <= num; i++) {
var barcodenum = parseInt(barcode)+parseInt(i);
var patron= barcodenum.toString();
var type = "code11";
var settings = {
barWidth: 2,
barHeight: 50,
moduleSize: 5,
addQuietZone: true,
marginHRI: 5,
bgColor: "#FFFFFF",
color: "#000000",
fontSize: 10,
output: "css",
posX: 0,
posY: 0,
fontOptions: "bold",
};
$('#barcoderesult').append('<div id="showBarcode'+ i +'"
style="float:left" />');
$("#showBarcode"+i).barcode(patron, type, settings);
$("#showbarcode"+i).animate({height: "100%", width: "100%"});
}
}
Now in my variable patron , it contains multiple generated barcode number . Now i need to push the barcode number in patron to an array and pass the array in yii2 controller through ajax ? How can i do it ? I didnt have any idea .
First, create one array namely, array_barcode and use JavaScript Array push() Method to fill values into this array. Then, after for loop, pass this array values to controller through AJAX if it's not empty.
<script>
function getbarcode(num, barcode){
var array_barcode = [];
for (var i = 1; i <= num; i++) {
var barcodenum = parseInt(barcode) + parseInt(i);
var patron = barcodenum.toString();
array_barcode.push(patron); //Push generated barcode into array 'array_barcode'
var type = "code11";
var settings = {
barWidth: 2,
barHeight: 50,
moduleSize: 5,
addQuietZone: true,
marginHRI: 5,
bgColor: "#FFFFFF",
color: "#000000",
fontSize: 10,
output: "css",
posX: 0,
posY: 0,
fontOptions: "bold",
};
$('#barcoderesult').append('<div id="showBarcode' + i + '"style = "float:left" / > ');
$("#showBarcode" + i).barcode(patron, type, settings);
$("#showbarcode" + i).animate({height: "100%", width: "100%"});
}
if(array_barcode.length > 0){//If array is not empty
$.ajax({
//url: "/controller-name/controller-action-name",
url: "/MyController/my-action",
type: "POST",
data: {array_barcode : array_barcode},
success: function (data) {
alert("Success");
},
error: function () {
alert("Error Ocurred");
},
});
}
}
</script>
Controller
Since, not much information was provided. So, I assumed controller name as MyController and action name as MyAction. Now, in action MyAction, check whether request coming is of AJAX type or not. Otherwise, throw error. Retrieve array values through Yii::$app->request->post().
<?php
class MyController
{
.
.
.
public function actionMyAction(){
if (Yii::$app->request->isAjax) {
$array_barcode = Yii::$app->request->post('array_barcode');
foreach($array_barcode as $barcode){
/*
* Your Logic
* Save '$barcode' to database
*/
}
}
throw new ForbiddenHttpException("Problem Ocurred");
}
}
?>

How to get a specific piece of data clicked on and send it as part of AJAX data

I have a sliding bar that has different values throughout it depending on which part of the sliding bar is clicked on. The ranges in my javascript represent the values. I am trying to pass the value selected to an ajax script, but cannot figure out how to do this.
I have tried doing this:
var range_selected = $("#sliderInterval").this.ranges.val();
But I get this error for the line above ^^:
Uncaught TypeError: Cannot read property 'ranges' of undefined
What can I do to capture the range the user clicks on and send it through with my AJAX data?
<div id="sliderBar">
<div id="sliderInterval">
<span id="sliderIntervalBudget">BUDGET</span>
</div>
</div>
JS
$(function() {
var ranges = [{
lower: 500,
upper: 1000
}, {
lower: 1100,
upper: 2000
}, {
lower: 2100,
upper: 5000
}, {
lower: 5100,
upper: 10000
}, {
lower: 11000,
upper: 20000
}, {
lower: 21000,
upper: 50000
}, ];
var wslider = $("#sliderBar").width() / (ranges.length);
for (var i = 0; i < ranges.length; i++) {
var range = $('<div class="rangedot"><div class="intervalCircle"></div></div>');
var left = (100 / (ranges.length) * i);
rangeleft = "calc(" + left + "% - 2px)";
range.css({
left: rangeleft,
width: wslider
});
range.on("click", function(idx) {
return function() {
var sliderleft = wslider * idx;
$("#sliderInterval").animate({
left: sliderleft
});
$("#budgetAmount").text("$" + ranges[idx].lower.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + " - " + "$" + ranges[idx].upper.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
};
}(i));
$("#sliderBar").append(range);
$("#sliderInterval").css("width", wslider + "px");
}
//$("#sliderInterval").show().text("BUDGET");
$("#budgetAmount").show().text("$500 - $1,000");
});

imagecreatefromgif() from base64 encoded animated gif in POST

I am trying to make animated GIFs from media streams, videos, or images using the GifShot plugin.
My problem is that the ajax part does not see webcam_image_ajax.php. isn't working. Please do not hate me so the question will be a little longer.
I have to create this ajax function for uploading image:
var pos = 0, ctx = null, saveCB, gif = [];
var createGIFButton = document.createElement("canvas");
createGIFButton.setAttribute('width', 320);
createGIFButton.setAttribute('height', 240);
if (createGIFButton.toDataURL)
{
ctx = createGIFButton.getContext("2d");
gif = ctx.getImageData(0, 0, 320, 240);
saveCB = function(data)
{
var col = data.split(";");
var img = gif;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 4 * 320 * 240)
{
ctx.putImageData(img, 0, 0);
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
function(data)
{
if($.trim(data) != "false")
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: $.base_url+"webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview').attr('id');
var T= M+','+values;
if(T!='undefinedd,')
$("#uploadvalues").val(T);
}
});
}
else
{
$("#webcam").html('<div id="camera_error"><b>Camera could not connect.</b><br/>Please be sure to make sure your camera is plugged in and in use by another application.</div>');
$("#webcam_status").html("<span style='color:#cc0000'>Camera not found please try again.</span>");
$("#webcam_takesnap").hide();
return false;
}
});
pos = 0;
}
else {
saveCB = function(data) {
gif.push(data);
pos+= 4 * 320;
if (pos >= 4 * 320 * 240)
{
$.post("webcam_image_ajax.php", {type: "pixel", gif: gif.join('|')},
function(data)
{
var dataString = 'webcam='+ 1;
$.ajax({
type: "POST",
url: "webcam_imageload_ajax.php",
data: dataString,
cache: false,
success: function(html){
var values=$("#uploadvalues").val();
$("#webcam_preview").prepend(html);
var M=$('.webcam_preview, .gifshot-image-preview-section').attr('id');
var T= M+','+values;
if(T!='undefined,')
$("#uploadvalues").val(T);
}
});
});
pos = 0;
}
};
}
};
}
$("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "js/jscam_canvas_only.swf",
onSave: saveCB,
onCapture: function ()
{
webcam.save();
},
debug: function (type, string) {
$("#webcam_status").html(type + ": " + string);
}
});
});
/**Taking snap**/
function takeSnap(){
webcam.capture();
}
You can see this code in my ajax function:
$.post("webcam_image_ajax.php", {type: "data", gif: createGIFButton.toDataURL("image/gif")},
the webcam_image_ajax.php is created in base64 format and then it upload the gif image from the images folder.
Also when clicked Create GIF button this JavaScript will starting: CLICK.
After that my ajax code have this line webcam_imageload_ajax.php
<?php
include_once 'includes.php';
if(isSet($_POST['webcam']))
{
$newdata=$Wall->Get_Upload_Image($uid,0);
echo "<img src='uploads/".$newdata['image_path']."' class='webcam_preview gifshot-image-preview-section' id='".$newdata['id']."'/>
";
}
?>
the webcam_imageload_ajax.php working with webcam_image_ajax.php.
If webcam_image_ajax.php created image then webcam_imageload_ajax.php echoing image like:
upload/14202558.gif
But now it looks like:
data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAABE...
creat a gif button:
<button type="button" id="create-gif" class="btn btn-large btn-primary create-gif-button camclick" onclick="return takeSnap();">Create GIF</button>
<input type="hidden" id="webcam_count" />
Forget the JavaScript code in the question.
If you want to use this script then use this code from demo.js inside in gifshot plugin.
function create_gif(data){
$.post(
"webcam_image_ajax.php",
{
data: data,
dataType: 'json'
},
function(js_data)
{
var js_d = $.parseJSON(js_data);
$('#gif_preview').attr('src', js_d.path);
if(js_d.id != 'error'){
$("#uploadvalues").val(js_d.id);
$('.webcam_preview, .gifshot-image-preview-section').attr('id', js_d.id);
}
}
);
}
and you can write your own php code for webcam_image_ajax.php.
Simply do like this:
file_put_contents('filename',file_get_contents(str_replace('data:','data://','<your base64 encoded data>')));
This is simply adapting your data:... into the data:// wrapper.
There is no simpler way to do this.
Notice that this is HIGHLY UNSECURE and you should validate the data (using preg_match for example) before usage.

JavaScript Auto Updating Graph

Hello StackOverFlow I hate to bother you guys, but I really struggle with JavaScript and I am looking for a way to simply monitor this Javascript so that the Y variable is grabbed from one of my php files.
Example: http://foo.com/bar.php so I can have a live graph of my user data
Thank you so much for the help I appreciate it
The following code is the example JavaScript code which generates random data I guess.
/* Lines with autodrowing */
$(function () {
// we use an inline data source in the example, usually data would
// be fetched from a server
var data = [], totalPoints = 200;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
data.push(y);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i)
res.push([i, data[i]])
return res;
}
// setup control widget
var updateInterval = 1000;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
if (updateInterval > 2000)
updateInterval = 2000;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
yaxis: { min: 0, max: 100 },
xaxis: { min: 0, max: 100 },
colors: ["#aed267"],
series: {
lines: {
lineWidth: 2,
fill: true,
fillColor: { colors: [ { opacity: 0.4 }, { opacity: 0 } ] },
//"#dcecf9"
steps: false
}
}
};
var plot = $.plot($(".updating"), [ getRandomData() ], options);
function update() {
plot.setData([ getRandomData() ]);
// since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
I'm not sure of what your question is.
If you just want to get Y value from the serveur, do an ajax call :
var yVal;
$.ajax({
url:"/yourserv?action=getYValue",
success: function(data){
yVal = data;
}
});

Categories

Resources