I have a little issue with my angularjs script.
I'm trying to post data to server (PHP script which saves values to database).
It works correctly in Chrome, Mozilla, Opera and each other but totally not in IE. I tried IE9, 10 and also 11 (all without add-ons)and still can't figure it out.
In IE my angularjs posts only empty JSON (something like {}).
Here's my angularjs POST script.
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'ajax/newInvoice.php',
data : $scope.invoice, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
getInvoices();
$scope.invoice = {items: [{qty: 1,description: '',cost: 0,taxPerc: 21}],odberatel: '',konecny_prijemce: '',datum_objednavky: new Date(),datum_vystaveni: new Date(),datum_splatnosti: new Date(),datum_zdanitelneho_plneni: new Date(),zpusob_uhrady: 'Platba kartou',dodaci_metoda: 'Osobní odběr'};
});
};
And here's PHP.
<?php
require_once '../includes/db.php'; // The mysql database connection script
$created = date("Y-m-d H:i:s", strtotime("now"));
$query = "SELECT id FROM ang_faktury ORDER BY id DESC";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$last_invoice_id = intval($row["id"]);
$year = date("Y");
$month = date("m");
$idString = str_pad(($last_invoice_id + 1), 5, '0', STR_PAD_LEFT);//id faktury ang_faktury[id], ang_faktury_polozky[id_faktury]
$faCislo = 'OB/'.$year.'/'.$month.'/'.$idString; //cislo faktury ang_faktury[cislo_faktury]
$_POST = json_decode(file_get_contents('php://input'), true);
$dzp = $_POST['datum_zdanitelneho_plneni'];
$datum_zdanitelneho_plneni = substr($dzp, 0, 10);
$dzpForm = date("d.m.Y", strtotime($datum_zdanitelneho_plneni));
$do = $_POST['datum_objednavky'];
$datum_objednavky = substr($do, 0, 10);
$doForm = date("d.m.Y", strtotime($datum_objednavky));
$dv = $_POST['datum_vystaveni'];
$datum_vystaveni = substr($dv, 0, 10);
$dvForm = date("d.m.Y", strtotime($datum_vystaveni));
$ds = $_POST['datum_splatnosti'];
$datum_splatnosti = substr($ds, 0, 10);
$dsForm = date("d.m.Y", strtotime($datum_splatnosti));
foreach($_POST['items'] as $item){
$sumPriceTotal += $item['priceTotal'];
$query2="insert into ang_faktury_polozky (id_faktury,name,cena,ks,dph_proc,dph,total) values('$idString','$item[description]','$item[mjPrice]','$item[qty]','$item[taxPerc]','$item[taxSum]','$item[priceTotal]')";
$mysqli->query($query2);
}
$spt = "{$sumPriceTotal}";
$cbd = (($spt*100)/121);
$dph = $spt - $cbd;
$query3="insert into ang_faktury (id,created_at,cislo_faktury,datum_zdanitelneho_plneni,odberatel,konecny_prijemce,zpusob_uhrady,dodaci_metoda,cislo_objednavky,datum_objednavky,datum_vystaveni,datum_splatnosti,cena_bez_dph,dph,celkem_k_uhrade) values('$idString','$created','$faCislo','$dzpForm','$_POST[odberatel]','$_POST[konecny_prijemce]','$_POST[zpusob_uhrady]','$_POST[dodaci_metoda]','$faCislo','$doForm','$dvForm','$dsForm','$cbd','$dph','$spt')";
$mysqli->query($query3);
mysqli_close($mysqli);
?>
Thanks for any advise.
check your data before sending console.log(data),
and check your data after receiving print_r($_POST) (in myFile.php)
from console (newInvoice.php):
Array
(
[items] => Array
(
[0] => Array
(
[qty] => 1
[description] => MIKI_01
[cost] => 10
[taxPerc] => 21
[priceTotal] => 10.00
[taxSum] => 1.74
[mjPrice] => 8.26
)
[1] => Array
(
[qty] => 1
[description] => MIKI_02
[cost] => 20
[taxPerc] => 21
[priceTotal] => 20.00
[taxSum] => 3.47
[mjPrice] => 16.53
)
)
[odberatel] => MIKI
[konecny_prijemce] =>
[datum_objednavky] => 2016-01-16T13:39:32.554Z
[datum_vystaveni] => 2016-01-16T13:39:32.554Z
[datum_splatnosti] => 2016-01-16T13:39:32.554Z
[datum_zdanitelneho_plneni] => 2016-01-16T13:39:32.554Z
[zpusob_uhrady] => Platba kartou
[dodaci_metoda] => Osobní odběr
)
Console (app.js)
Object {items: Array[2], odberatel: "MIKI", konecny_prijemce: "", datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time), datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)…}
datum_objednavky: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_splatnosti: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_vystaveni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
datum_zdanitelneho_plneni: Sat Jan 16 2016 14:45:18 GMT+0100 (Central Europe Standard Time)
dodaci_metoda: "Osobní odběr"
items: Array[2]
0: Object
$$hashKey: "object:4"
cost: 10
description: "MIKI_01"
mjPrice: "8.26"
priceTotal: "10.00"
qty: 1
taxPerc: 21
taxSum: "1.74"
__proto__: Object
1: Object
$$hashKey: "object:69"
cost: 20
description: "MIKI_02"
mjPrice: "16.53"
priceTotal: "20.00"
qty: 1
taxPerc: 21
taxSum: "3.47"
__proto__: Object
length: 2
__proto__: Array[0]
konecny_prijemce: ""
odberatel: "MIKI"
zpusob_uhrady: "Platba kartou"
__proto__: Object
Related
On the backend I use multer to upload multiple files / images, I have tried using Postman and it works. but when i apply it on the frontend using reactjs, i am confused
sample case:
state = {
name: 'product1',
price: '200',
images: [{name: "1.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
files: [{name: "1.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
}
handleSubmit = () => {
const { name, price, images, files} = this.state
const body = new FormData()
body.append('name', name)
body.append('price', price)
images.map((file, i) => body.append('images[i]', file[i])) // not work
files.map((file, i) => body.append('files[i]', file[i])) // not work
axios.post(`http://localhost:3000/api/v1/add`, body)
.then((res) => res.data.data)
// result {"name":"roduct1","price":"200","images":[{},{}],"files":[{},{}]}
}
You can do the POST request through axios in this way:
var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');
bodyFormData.append('image', imageFile);
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Also its observed many times that localhost does not work with axios. Instead you need to use IP address. If suppose your IP address is 192.23.43.45 than URL becomes http://192.23.43.45:3000/api/v1/add . So, you can try this approach
I'm trying to set the some data inside of cookie using js-cookie.
but somehow it's not setting in the cookie. following is my code:
const setCookie = (name: string, value: string, expires: Date) => {
Cookies.set(name, value, {expires})
}
and this is the result when I console.log this line :
UserId=1; path=/; expires=Thu, 09 Apr 2020 15:26:37 GMT
I thought that path=/ is the problem, so I've tried to set the path as well, but didn't work.
Does anyone have idea why is not setting into the cookie?
Updated:
data passed to name, value, expires are :
UserId, 1, Thu Apr 09 2020 11:26:37 GMT-0400 (Eastern Daylight Time)
Expires parameter should be a number which indicate how much days until your cookie will expire
just update your function as follow
const setCookie = (name: string, value: string, expires: number) => {
Cookies.set(name, value, {expires})
}
I am making an app based on typescript and trying to implement winston-papertrail for logs with a timestamp and custom format. The problem is that when I am consoling it, it is showing exacltly what I want but on papertrail it is showing in an unexpected way. Here is my code on the typescript.
const { Papertrail } = require("winston-papertrail");
const { createLogger, format, transports } = require("winston");
const { combine, timestamp, prettyPrint, printf } = format;
const timezoned = () => {
return new Date().toLocaleString("en-US", {
timeZone: "Asia/Kolkata",
});
};
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const options = {
console: {
level: "debug",
format: combine(
timestamp({format: timezoned}),
myFormat,
) ,
},
};
const winstonPapertrail = new Papertrail({
host: "logs3.papertrailapp.com",
port: 32795,
level: "info",
});
const consoleWinston = new transports.Console(options.console);
export const logger = createLogger({
transports: [winstonPapertrail, consoleWinston],
});
How I am getting it on the console (which is the correct format) :
10/26/2019, 11:15:49 PM info: Fetching offset:16000 count:1000
10/26/2019, 11:15:59 PM info: Products Fetched
10/26/2019, 11:15:59 PM info: Indexing Products
How it is showing on papertrail:
Oct 26 23:15:50 wolborg default info { message: 'Fetching offset:16000 count:1000',
Oct 26 23:15:50 wolborg default info level: 'info',
Oct 26 23:15:50 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:50 wolborg default info [Symbol(message)]:
Oct 26 23:15:50 wolborg default info '{"message":"Fetching offset:16000 count:1000","level":"info"}' }
Oct 26 23:15:59 wolborg default info Products Fetched
Oct 26 23:15:59 wolborg default info { message: 'Products Fetched',
Oct 26 23:15:59 wolborg default info level: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(message)]: '{"message":"Products Fetched","level":"info"}' }
Oct 26 23:15:59 wolborg default info Indexing Products
Oct 26 23:15:59 wolborg default info { message: 'Indexing Products',
Oct 26 23:15:59 wolborg default info level: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(level)]: 'info',
Oct 26 23:15:59 wolborg default info [Symbol(message)]: '{"message":"Indexing Products","level":"info"}' }
With input is file, I can log to console the File as
console.log(file.size)
It gives me:
File(3987) {name: "download.jpeg", lastModified: 1544914267262, lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 3987, …}
lastModified: 1544914267262
lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time) {}
name: "download.jpeg"
size: 3987
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
However when I do console.log(e.target.files[0].size)
It does not even fire.
Full Code as requested. FIle is coming from <input onChange={(e)=>{this.handChangeFile(e.target.files[0])}}/>
this.handleChangeFile = (file) => {
console.log(typeof file)
this.setState({ thefile: file })
let fileData = new FileReader();
fileData.readAsDataURL(file);
fileData.onloadend = () => {
imageBase64 = fileData.result
if (this.state.first == true) {
this.setState({ binary: imageBase64, hide_stock: !this.state.hide_stock, first: false }, () => {
})
}
else
this.setState({ binary: imageBase64 }, () => {
})
}
}
This is my solution on jsfiddle
with jQuery: https://jsfiddle.net/huynhsamha/dqLv83zr/
with React: https://jsfiddle.net/huynhsamha/23fv1te5/
Both they are working. Can you share your code why it is not working?
jQuery
<script async src="//jsfiddle.net/huynhsamha/dqLv83zr/embed/js,html,css,result/dark/"></script>
React
<script async src="//jsfiddle.net/huynhsamha/23fv1te5/embed/js,html,css,result/dark/"></script>
I am processing data read from database on the server using the following code:
module.exports = mongoose.model('Todo', {
text : {type : String, default: ''},
created_at : Date
});
var processTodos = function ( todos ){
for (var i = todos.length - 1; i >= 0; i--) {
// Following update is not happening
todos[i].created_at = "Custom date";
};
console.dir(todos);
return todos;
};
I am not able to figure out how to update this. Is there a syntax issue that is causing this.
I am using MEAN stack for my application.
// Following update is not happening
todos[i].created_at = "Custom date";
What am i missing here.
Here is the console log for "console.dir(todos);":
{ _id: 5489dda3f23f159400475dba,
created_at: Thu Dec 11 2014 23:38:35 GMT+0530 (India Standard Time),
__v: 0,
text: 'Testing sorting at server side' }
{ _id: 5489ddacf23f159400475dbb,
created_at: Thu Dec 11 2014 23:38:44 GMT+0530 (India Standard Time),
__v: 0,
text: 'It works' }
{ _id: 5489f31a12fa54cc127f3e1d,
created_at: Fri Dec 12 2014 01:10:10 GMT+0530 (India Standard Time),
__v: 0,
text: 'time to add more data' }
If you'd like to save the changes you're making to your object, you need to persist the change using the .save() method like so:
var processTodos = function ( todos ){
for (var i = todos.length - 1; i >= 0; i--) {
// Following update is not happening
todos[i].created_at = "Custom date";
todos[i].save();
};
console.dir(todos);
return todos;
};