I'd like to know how to use XMLHttpRequest to get response from ws.
I tried this code to post my vale:
private prepareSave(): any {
const endpoint = (Api.getUrl(Api.URLS.createContrat));
let XHR = new XMLHttpRequest();
const input: FormData = new FormData();
input.append('contratedate', this.addContratForm.get('contratedate').value);
input.append('contratdesc', this.addContratForm.get('contratdesc').value);
input.append('unit_price', this.addContratForm.get('unit_price').value);
input.append('files', this.addContratForm.get('files').value);
input.append('token', this.auth.getCurrentUser().token);
XHR.addEventListener('load', function (event) {
alert('Yeah! Data sent and response loaded.');
});
XHR.addEventListener('error', function (event) {
alert('Oups! Something went wrong.');
});
XHR.open('POST', endpoint);
console.log(input)
XHR.send(input)
console.log(XHR) // show me XMLHttpRequest.
}
My response is:
{
"StatusCode":0,
"StatusMessage":"OK",
"StatusDescription":
[
{
"error_no":0,
"error_msg":"",
"sqlerrorno":0,
"sqlerror":"",
"lastid":"11E84DE6579F6599A4FBFA163EBBBC1D"}
]
}
I tried something like this code, but no function:
if (XHR.response.StatusCode === 0) {
Materialize.toast('Contrat update successfully', 4000);
this.router.navigate(['/main/contrats']);
return true;
}
Please, can you suggest any solution? Thank you
Try this code:
private prepareSave(): any {
const endpoint = (Api.getUrl(Api.URLS.createContrat));
let XHR = new XMLHttpRequest();
const input: FormData = new FormData();
input.append('contratedate', this.addContratForm.get('contratedate').value);
input.append('contratdesc', this.addContratForm.get('contratdesc').value);
input.append('unit_price', this.addContratForm.get('unit_price').value);
input.append('files', this.addContratForm.get('files').value);
input.append('token', this.auth.getCurrentUser().token);
XHR.addEventListener('load', function (event) {
alert('Yeah! Data sent and response loaded.');
});
XHR.addEventListener('error', function (event) {
alert('Oups! Something went wrong.');
});
XHR.open('POST', endpoint);
console.log(input)
XHR.send(input)
XHR.onload = function () {
let jsonResponse = JSON.parse(XHR.responseText);
if (jsonResponse.StatusCode === 0) {
Materialize.toast('Contrat saved successfully', 4000);
window.location.href = '/main/contrats';
return true;
}
}