|
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(
}
|
|
|
|
|
var book = {
title: "The Giver",
stars: 4
};
// draw shelf
fill(173, 117, 33);
rect(0, 120, width, 10);
// draw one book
fill(214, 255, 219);
rect(10, 20, 90, 100);
fill(0, 0, 0);
text(book.title, 15, 29, 70, 100);
for (var i = 0; i < book.stars; i++) {
image(getImage("cute/Star"), 13 + i * 20, 90, 20, 30);
}
for (var i=0; i<2; i++){
var xLivrosElias = [150];
var Autor = "Elias Araujo";
var recomendarlivro1 = true;
var recomendarlivro2 = true;
var recomendarlivro3 = false;
var count = i;
var cout = i[1];
rect(xLivrosElias[0]+150*i,20,90,100);
//Autor do tres Livros
fill(0, 0, 0);
text(Autor,15+140,29+60);
text(Autor,15+290,29+60);
text(Autor,15+1,29+60);
//Titulo do Livros
//2Livro
text("O guardião",15+290,29+30);
//3 Livro
text("O assasino do Futuro",15+140,29+10,100,30);
if(recomendarlivro1 === true){
text("O livro e bom",25,100);
}else{
text("O livro e ruim",25,100);
}
if(recomendarlivro2 === true){
text("O livro e bom",315,89);
}else{
text("O livro e ruim",315,89);
}
if(recomendarlivro3 === false){
text("O livro e ruim",165,89);
}else{
text("O livro e bom",165,89);
}
if(count ===0){
fill(196, 68, 68);
}else{
fill(156, 97, 97);
}
}
//Segunda estante de livros
fill(173,117,33);
rect(0,250,width,10);
var autor= "Alexandre";
//draw book one
//book one
fill(140,89,89);
rect(140-130,50+100,90,100);
//autor
fill(0, 0, 0);
text(autor,20,240);
//nome do livro
text("Isadora 1 O incio",20-5,240-80,90,45);
//livro 2
fill(147, 198, 230);
rect(140+20,150,90,100);
//autor
fill(0,0,0);
text(autor,20+150,240);
//nome do livro
text("Isadora 2 a procura do Rei",165,240-80,90,45);
//livro 3
fill(46,209,62);
rect(140+160,150,90,100);
//autor
fill(0,0,0);
text(Autor,20+290,240);
//nome do livro
text("Isadora 3 a consquista de
um novo Reino",305,240-80,90,40);
Richard, I still don't understand why I painted only book 3, book 2 is blank, could you say where I'm wrong to fix it
|
|
|
|
|
Look closely at the error message, it will tell you the file name, the line number and probably the column number as well. Then use your editor to go to that line - moset editors accept CTRL+G as "go to line number" - and look closely at the line it refers to. Without knowing that, it's guess work!
But my guess is this line:
document.getElementById('double_your_btc_stake').value = stake.toFixed(8); What the heck is that at the start?
"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!
|
|
|
|
|
Given he's posted what looks like heavily-obfuscated Javascript malware in QA as both a question with the same title as this message, and a "solution" to a question from January, I suspect he's a troll.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
So do I ... but it didn't cost me anything to be polite just in case...
"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!
|
|
|
|
|
Hi guys ... I'm at the first programming experiences ... I'm trying to make a personal website to have updates of various data ... now, I would like to insert in HTML H1 the import of a value via API. .. unfortunately with what I wrote nothing works ... you can help me. Thank you
modified 1-Oct-21 7:13am.
|
|
|
|
|
First and foremost, never share the credentials on public websites. Your bearer token can be used by bots to cost you money; try to avoid that.
Secondly, I see that you have defined a function onInterval but you never call that function. You can either call that as a response to some event (button click, input, page load complete, etc.) or you can create a self-calling function.
(function onInterval() {
})(); You can see that I just wrapped the function and then called it in-place.
Lastly, you created a candleData object but you never rendered it anywhere. Maybe you can put it inside the h3 or p.u-text-palette-3-base using your container variable.
container.innerText = JSON.stringify(candleData); You should be able to see something. I have skipped the complete code because I want you to give it a try.
Learn more here:
JSON.stringify() - JavaScript | MDN
closures - What is the purpose of a self executing function in javascript? - Stack Overflow
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
Quote: how to take the last given that of Close You can do that using the last index. Does this work?
const lastClose = candleData[candleData.length - 1];
Quote: I can not insert it in H2 To insert in the h2, use the query selector for h2 (right now you have of the paragraph).
The sh*t I complain about
It's like there ain't a cloud in the sky and it's raining out - Eminem
~! Firewall !~
|
|
|
|
|
no, nothing works .. I'm disappointed in myself
|
|
|
|
|
hello, why the number that I recover in the object is not written in H1 ??? I do not understand, I do not understand even why the number I recover in object I cannot round it with .toFixed (3) and then write it in H1
<pre><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script>
const intervalTime = 10 * 1000;
const container = document.getElementsByClassName("u-text u-text-palette-3-base u-title u-text-3");
const endpoint =
"https://api.adalo.com/v0/apps/3c14481f-42d8-4944-b7a8-80ca77c16b91/collections/t_e0fz278ravbshx11g4iq7w1j0?offset=0&limit=unlikely";
function onInterval() {
fetch(endpoint, {
method: "GET",
headers: { Authorization: "Bearer cbqm69e5q48tl8v3gava0fjv6" }
})
.then((res) => res.json())
.then((data) => {
const candleData = data.records.map((a) => {
return{
close: (a.close)
};
});
const lastClose = candleData[candleData.length - 1];
console.log(lastClose);
});
}
onInterval();
window.setInterval(onInterval, intervalTime);
</script>
</head>
<body>
<h2><p class="u-text u-text-palette-3-base u-title u-text-3"></p>
</h2>
</body>
</html>
|
|
|
|
|
I'm scratching my head on this. I type in 125.00 and the decimal is cleared and becomes 12500
I see the \. which I would assume keeps the decimal point.
document.addEventListener("keydown", (e) => {
const el = e.target;
if (el.classList.contains("currency")) {
console.debug(el.id, el.value);
el.value = formatCurrency(el.value);
}
});
function formatCurrency(value) {
if (!value) return value;
return value.replace(/^[0-9]+\.[0-9]{2}/, "");
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
jkirkerx wrote: value.replace(/^[0-9]+\.[0-9]{2}/, "");
Aren't you replacing those characters with a space? I avoid regex when possible but I am surprised you even get 12500 because it looks like you are replacing characters 0-9 and . with an empty space. When I run this is JSFiddle I get an empty string so I am not sure what you are doing.
|
|
|
|
|
I was thinking the same thing at first. Maybe I need to rethink this.
It's a html element textbox, so like a phone number formatter, it's a currency formatter where you type in say 125.00 or 65.47
It will reject alphabet letters.
I copied it from my phone number formatter, and used the same principals, well at least I think I did.
function formatPhoneNumber12(value) {
if (!value) return value;<br />
const phoneNumber = value.replace(/[^\d]/g, "");<br />
const phoneNumberLength = phoneNumber.length;
if (phoneNumberLength < 4) return phoneNumber;
if (phoneNumberLength < 7) {
return <code>${phoneNumber.slice(0, 3)}-${phoneNumber.slice(3)}</code>;
}
return <code>${phoneNumber.slice(0, 3)}-${phoneNumber.slice(
3,
6
)}-${phoneNumber.slice(6, 9)}</code>;
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
|
I'm back to working on this today. This works in Chrome, but not in firefox. I lose the decimal in firefox.
So in Chrome, I can type 1.23, but in Firefox it types 123
This is a filter or sort of a mask for input element of a number step .01
I thought it was the regex, and monkeyed around for about an hour with it. But it seems to have something to do with the keydown event in Firefox.
I tried this pattern
const pattern = "/^[0-9]+\\.[0-9]{2}/g";
Tried this function style
function formatCurrency(value) {
if (!value) return value;
const pattern = "/^[0-9]+\.[0-9]{2}/g";
return value.replace(pattern, "");
}
And now I'm here. It's just the dot or decimal in FireFox. Maybe it is my regex.
I thought maybe it was the textbox, so I did a console output, same thing.
Oh, I know this function looks weird, like why would I replace what I want to keep. I have no answer for that.
I am stumped... Calling it quits for today. Maybe it's a PHP issue?
document.addEventListener("keydown", (e) => {
const el = e.target;
if (el.classList.contains("currency")) {
el.value = formatCurrency(el.value);
}
});
function formatCurrency(value) {
if (!value) return value;
const pattern = '^(\d+(.\d{0,2})?|.?\d{1,2})$';
console.log('value replace=', value.replace(new RegExp(pattern)));
return value.replace(new RegExp(pattern));
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Changed the input to a textbox, and removed the step attr, and it worked on Firefox
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
I'm taking the w3schools tutorial on javascript. In the tutorial it is discussing numerical sort. It says since javascript doesn't sort numerals you need to use a trick of employing a comparison function with sort.
<pre><!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the button to sort the array in ascending order.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
</body>
</html>
How does function(a, b) get the input a and b? If you could give a detailed message because I'm not getting how it all works.
|
|
|
|
|