|
I am trying to rewrite this jQuery code to Typescript.
export class EditIntSliderCustomElement {
parentVM: any;
@bindable
label: string;
editSlider: HTMLInputElement;
readOnlySlider: HTMLInputElement;
@bindable
min : number;
@bindable
max :number;
@bindable
step: number = 1;
@bindable({ defaultBindingMode: bindingMode.twoWay })
value: number;
@bindable
editOnly: boolean = false;
@bindable
hideMinMax: boolean = false;
valueChanged(newValue) {
let editSlider = $(this.editSlider).data("ionRangeSlider");
if (editSlider && editSlider.old_from != newValue){
editSlider.update({ from: newValue });
}
let readOnlySlider = $(this.readOnlySlider).data("ionRangeSlider");
if (readOnlySlider && readOnlySlider.old_from != newValue) {
readOnlySlider.update({ from: newValue });
}
}
constructor() {
}
bind(bindingContext, overrideContext) {
this.parentVM = bindingContext;
}
userChanged(newVal: number){
if (this.value != newVal) {
this.value = newVal;
}
}
attached() {
$(this.editSlider).ionRangeSlider({
min: this.min,
max: this.max,
from: this.value,
step: this.step,
hide_min_max: this.hideMinMax,
onChange: (data) => {
this.userChanged(data.from);
}
});
$(this.readOnlySlider).ionRangeSlider({
min: this.min,
max: this.max,
from: this.value,
step: this.step,
hide_min_max: this.hideMinMax,
disable: true,
onChange: (data) => {
this.userChanged(data.from);
}
});
}
}
<pre> <div show.bind="editOnly || parentVM.editMode != 0" class="form-group">
<label-for>
<small>${label}</small>
</label-for>
<input ref="editSlider" value.two-way="value" type="text">
</div>
<div show.bind="!editOnly && parentVM.editMode == 0">
<small>${label}</small>
<input ref="readOnlySlider" value.two-way="value" type="text">
</div>
modified 8-Dec-21 16:55pm.
|
|
|
|
|
You seem to have forgotten to ask a question.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
The vanilla version of jQuery's .data('blah') is to use getAttribute('data-blah') directly.
Jeremy Falcon
|
|
|
|
|
I have this very long process that creates a JSON array of projects. It takes 10 minutes to generate the JSON.
I'm trying to extract my projects array from within this JSON, and have converted the JSON string to an JavaScript object.
Suppose to be able to call jsonObject.projects and loop it, but it keeps coming up with an error "projects is undefined". When I parse again projects, I get "JSON.parse unexpected character at line 1"
I've done this so many times, but this time has me baffled.
This is my code:
function loadProjectsUpdated(partId) {
const projectsContainer = document.getElementById('projectsContainer');
const jsonProjectElement = document.getElementById('updateProjectCost_jsonProjectResponse');
const jsonObject = JSON.parse(jsonProjectElement.value);
console.log('jsonObject', jsonObject);
const projects = jsonObject.projects;
console.log('projects', projects);
for (const project of projects) {
console.log('projectNumber', project.projectNumber)
if (project.partId === partId) {
console.log('we have a match');
}
}
}
And my console results:
I can see I have a object here.
jsonObject
Array [ {…} ]
0: Object { partId: "REF_EL_003", vendorId: "7", projects: (411) […] }
partId: "REF_EL_003"
projects: Array(411) [ {…}, {…}, {…}, … ]
[0…99]
0: Object { projectNumber: "4725", projectStage: "construction", projectVersion: 7, … }
partId: "REF_EL_003"
projectCostDifference: 0
projectCreated: "2019-02-05"
projectCustomerName: "XXX - DXXX"
projectNewActualCost: 89912.66
projectNumber: "4725"
projectOriginalActualCost: 89912.66
projectStage: "construction"
projectVersion: 7
taskId: "XX_XX_022"
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Your jsonObject is an array. You can't access the properties of members of that array directly on the array itself; you have to specify which member of the array you want to use.
console.log('jsonObject', jsonObject);
const projects = jsonObject[0].projects;
console.log('projects', projects);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I didn't think of that. To me it's weird until I fully understand. I figured it would be a straight object, and the projects would be the array. I wonder if it has to do with how I packaged the JSON.
I can loop the projects now. Wonder if find and indexOf will work now.
Thanks
[{
"partId": "REF_EL_003",
"vendorId": "7",
"projects": [{
"projectNumber": "4725",
"projectStage": "construction",
"projectVersion": 7,
"projectCreated": "2019-02-05",
"projectCustomerName": "XXX - Debbie",
"projectOriginalActualCost": 89912.66,
"projectNewActualCost": 89912.66,
"projectCostDifference": 0,
"taskId": "XK_EL_022",
"partId": "REF_EL_003"
}, {
"projectNumber": "4736",
"projectStage": "construction",
"projectVersion": 2,
"projectCreated": "2019-03-05",
"projectCustomerName": "XXX and Brian",
"projectOriginalActualCost": 53866.232,
"projectNewActualCost": 53866.232,
"projectCostDifference": 0,
"taskId": "XX_EL_022",
"partId": "XXX_EL_003"
}, {
"projectNumber": "4756",
"projectStage": "construction",
"projectVersion": 3,
"projectCreated": "2019-04-23",
"projectCustomerName": "XXX & Elizabeth",
"projectOriginalActualCost": 61620.74,
"projectNewActualCost": 61620.73999999999,
"projectCostDifference": -7.275957614183426e-12,
"taskId": "XX_EL_022",
"partId": "XX_EL_003"
},
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Your JSON starts with [ , which means it's an array, not a single object.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Oh, I didn't catch that. So it is my JSON format.
Thanks. Oh that's what I get for not using JSON.stringify to build the JSON. I'll mess with this today.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
I thought this would be easy, but didn't consider my for each loop just running and calling fetch really fast, when I need to call fetch one at a time until it finishes. Or maybe not if I consider the web server being able to process that many fetches, say 30 to 60, but I would hate to load up the web server with that many jobs.
I have this long process, that may take 2 or 3 minutes each, and didn't want to send a large payload of jobs to the API, so I broke the payload down into individual jobs to send to the API one at a time. I extracted the payload and ran each payload in a loop. I'm not sure if I need to tell the loop to wait, or tell fetch to wait. I've never done this before in JavaScript and I'm not sure how to approach this. Tried a few things, but I probably need to write test code that reflects the principals first and confirm that it works, and then adjust my code. Everything I found on the Internet didn't really match what I wanted to do.
I pasted my function so you can see what I'm trying to achieve. I've worked with promise before in Angular, waiting for google API to validate my google credentials but that was a single transaction.
async function runProjectUpdateCostAsync() {
const vendorId = document.getElementById('updateProjectCost_vendorId').value;
const bodyPayload = JSON.parse(document.getElementById('updateProjectCost_jsonPayload').value);
const priceLists = JSON.parse(bodyPayload.priceLists);
let apiUri = document.getElementById('updateProjectCost_apiUri').value;
apiUri += '?updateProjectCost=true';
let promise = Promise.resolve();
for await (const priceList of priceLists) {
const statusElement = document.getElementById(priceList.statusElement);
const img = new Image();
img.src = '/assets/images/Gear-0.2s-32px.gif';
img.alt = 'wait';
statusElement.innerHTML = '';
statusElement.appendChild(img);
const newBodyPayload = JSON.stringify({
"vendorId": vendorId,
"priceLists": "[" + JSON.stringify(priceList) + "]"
});
const span = document.createElement('span');
span.classList.add('font-weight-bold');
span.classList.add('mx-2');
promise = promise.then(fetch(apiUri, {
method: 'POST',
body: newBodyPayload,
headers: {'Content-type': 'application/text; charset=utf-8'}
})
.then(response => response.json())
.then(data => {
span.classList.add('text-success');
span.innerHTML = 'Success';
statusElement.innerHTML = '';
statusElement.appendChild(span);
})
.catch(e => {
span.classList.add('text-danger');
span.innerHTML = 'Failed';
statusElement.innerHTML = '';
statusElement.appendChild(span);
console.error("runProjectUpdateCost Error: ", e);
}));
}
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
The Promise.resolve() method[^] returns an already-resolved promise object. I don't understand why you think you need that?
Using .then in an async method is a definite code-smell. Why aren't you using await instead?
const response = await fetch(apiUrl, { ... });
if (!response.ok){
span.classList.add('text-danger');
span.innerHTML = 'Failed';
statusElement.innerHTML = '';
statusElement.appendChild(span);
const errorMessage = await response.text();
console.error("runProjectUpdateCost Error: ", response.status, response.statusText, errorMessage);
} else {
const data = await response.json();
span.classList.add('text-success');
span.innerHTML = 'Success';
statusElement.innerHTML = '';
statusElement.appendChild(span);
}
Also, priceLists doesn't look like an async iterable, so I don't think you need the for await (...) syntax:
for await...of - JavaScript | MDN[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
It had been awhile since I had written a promise, and I knew that fetch is a promise when called once. I can see that I just need to wait for fetch and just let the loop run which is what I was hoping would be the proper way to handle this. So wait for Fetch to return it's result, and based on the external result then trigger my UI decorations.
The promise.resolve came from just being brain dead, after spending time trying to figure out why I can JSON.parse my JSON, yet not get an object deeper inside what I just parsed, thus the double JSON.parse on priceLists .
Thanks Richard!
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Recommended Apps to learn java for student?
|
|
|
|
|
Java and Javascript are very different languages The former runs on a computer, the latter runs in your browser.
What helps with one will not help with the other ...
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
|
|
Best android app to learn java is Reddit and Learn Java
|
|
|
|
|
Hi,
I want to upload an image file using JQuery AJAX and send it to php code for further processing including image cropping. I tried this code for Js:
<script type="text/javascript">
$(document).ready(function() {
$('#uploadstatus1').hide();
$('#uploadstatus2').hide();
$('#btnupload').click(function() {
var file = $('#formFile')[0].files[0];
var filename = file.name;
var filedata = $('#formFile').prop('files')[0];
var formdata = new FormData();
formdata.append("file", filedata);
formdata.append("filename", filename);
$.ajax({
url: "../app/model/saveimage.php",
type: "POST",
dataType: 'script',
cache: false,
processData: false,
data: formdata,
success: function(data2) {
if (data2 == 1) {
location.reload();
} else {
alert(data2);
$('#uploadstatus1').show();
}
}
});
});
});
</script>
Uploading modal:
<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Upload image</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="" method="POST" enctype="multipart/form-data">
<p>Upload file:</p>
<div class="mb-3">
<label for="formFile" class="form-label">Only Jpeg files are supported.</label>
<input class="form-control" type="file" id="formFile" name="formFile" required>
</div>
</form>
<div class="alert alert-danger" id="uploadstatus1" role="alert">
Upload failed!
</div>
<div class="alert alert-success" id="uploadstatus2" role="alert">
File uploaded successfully!
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" name="btnupload" id="btnupload">Upload</button>
</div>
</div>
</div>
</div>
saveimage.php:
if (isset($_POST['file'])) {
try {
$crop = new Crop();
$crop->img_name = $_FILES['file']['name'];
$crop->tmp_img_name = $_FILES['file']['tmp_name'];
$crop->folder = "../public/assets/uploadIMG/";
$crop->ext = pathinfo($crop->img_name, PATHINFO_EXTENSION);
$crop->new_name = $this->RandomStringGenerator() . "." . $crop->ext;
$this->new_name = $crop->new_name;
move_uploaded_file($crop->tmp_img_name, $crop->folder . $crop->new_name);
$this->RegisterIntoDatabase();
$crop->RunCrop();
unset($_POST);
echo '1';
} catch (\Throwable $th) {
echo '2';
}
}else{
echo '2';
}
The problem is that
if (isset($_POST['file'])) returns false.
How can I solve this problem?
|
|
|
|
|
Alex Dunlop wrote:
var file = $('#formFile')[0].files[0];
var filedata = $('#formFile').prop('files')[0]; Why are you accessing the file twice, using two slightly different syntaxes? Just use:
const file = document.getElementById("formFile").files[0];
const formdata = new FormData();
formdata.append("file", file);
$.ajax({
url: "../app/model/saveimage.php",
type: "POST",
processData: false,
contentType: false,
data: formdata,
success: function(data2) {
...
}
});
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I applied those changes:
<script type="text/javascript">
$(document).ready(function() {
$('#uploadstatus1').hide();
$('#uploadstatus2').hide();
$('#btnupload').click(function() {
const file = document.getElementById("formFile").files[0];
const formdata = new FormData();
formdata.append("file", file);
$.ajax({
url: "../app/model/saveimage.php",
type: "POST",
processData: false,
contentType: false,
data: formdata,
success: function(data2) {
if (data2 == 1) {
location.reload();
} else {
alert(data2);
$('#uploadstatus1').show();
}
}
});
});
});
</script>
it still returns false for if (isset($_POST['file']))
|
|
|
|
|
Try replacing:
if (isset($_POST['file'])) { with:
if (isset($_FILES['file'])) {
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Regardless of whether your using jQuery which was obsoleted back in 2016 or so, or JavaScript, you need to read the file and convert the binary data to a base64 string, and then just HTTP POST that base64 string to the PHP API. The PHP API would convert the base64 string back to binary data, and just write the binary data as a image file. I found using base64 strings more reliable that sending binary data to the web server.
As far as cropping goes, that another story for the PHP world and PHP image processing that you would add to the API, in the form of coordinates.
On the PHP side, grabbing the HTTP POST payload would be, well I would of used this instead for PHP 7.4+.
$imagePayload = file_get_contents('php://input');
You don't need to try the payload, it's either there or not.
I forgot how to write jQuery, that was years ago for me. I just use plain vanilla JavaScript now.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
jkirkerx wrote: ... you need to read the file and convert the binary data to a base64 string, and then just HTTP POST that base64 string to the PHP API
Or use FormData , which will let the PHP code handle the file upload in the same way as a normal form submission.
Using FormData Objects - Web APIs | MDN[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I didn't know about FormData.
I've been working on this PHP project for quite some time now, writing a bunch of SPA type pages writing JavaScript and PHP APIs. And never before had to use the browser so much to look at my HTTP request and responses to make sure my payloads are correct. Quite interesting how the browser packages all the input elements into a nice payload and sends it off to the server as a POST, and the format that it uses for packaging, pretty much how FormData is constructed.
I was thinking the OP on this post could actually just build a JSON payload with his crop coordinates, filename, and a base64 string and post it to his API page. Then his API can just grab the payload, parse it and he would have all the data he needs to finish the image in one tidy package. But he has to start somewhere and just posting binary data to his API is a good start to get him rolling with something successful.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
how do you paint objects with two different colors in the for repetition structure, as shown in the code below
For(var o=0;i<2;i++){
Var xElias Books = [Elias]
Var Author = "Elias Araújo"
Var recommendbook1 = true;
Var recommendbook2 = true;
Var recommendbook3 = false;
fill(255,60,50)
fill(100,50,50)
Rect(xElias Books[0]+150*i,20,90,100)
//I can't get the two objects to be painted different colors like you do.
}
-- modified 30-Oct-21 9:47am.
|
|
|
|
|
You are using the same values both times round the loop. Select one colour for each value of your loop count.
if (count == 0){
fill(
}
else {
fill(
}
|
|
|
|
|