Ionic calling submit method in another method is not working properly - javascript

Below mentioned is my submit method will post some data to the server when I click on a submit button.
it is working well when the action is performed manually. but I don't want to press submit button every time I want to call this after input texts were filled for this I'm calling this method in another method at that time it is not posting anything it is giving undefined can anyone help me on this
start() {
SMSReceive.startWatch(
() => {
document.addEventListener('onSMSArrive', (e: any) => {
var IncomingSMS = e.data;
this.smsaddress = IncomingSMS.address;
this.smsbody = IncomingSMS.body;
if (this.smsbody.includes("HELLO") || this.smsbody.includes("HI")) {
alert("Data : " + this.smsbody + this.smsaddress);
const obj={
smsbody:this.smsbody,
smsaddress:this.smsaddress
}
this.submit(obj);
} else {
alert("resetting")
this.resetdata();
}
})
},
() => { console.log('watch start failed') }
)
}
submit(msg) {
let headers = new Headers();
headers.append('content-Type', 'application/json');
this.http.post(this.ip + "/api/route", { headers: headers }).pipe(map(res => res.json()))
.subscribe(data => {
alert(JSON.stringify(data));
this.presentToast('Message has been submitted successfully', false, 'bottom');
this.resetdata();
})
}; ```

You forget to pass data in post request
submit(msg) {
let headers = new Headers();
headers.append('content-Type', 'application/json');
this.http.post(this.ip + "/api/route",msg, { headers: headers },).pipe(map(res => res.json()))
.subscribe(data => {
alert(JSON.stringify(data));
this.presentToast('Message has been submitted successfully', false, 'bottom');
this.resetdata();
})

Related

How to code a checkbox that saves changes after refreshing page

I'm trying to change the checkbox data on the server using the patch method, but I can't do it. Give me an advise, please, how to do it correctly.
I send a patch request, 202 code is returned. In the preview (developer tools in the browser) it is shown that the changed data is returned from the server, but for some reason the changes do not occur in the db.json file. After I check the checkbox and refresh the page it’s like I never checked the box.
I need an input checkbox that will send a PATCH request to the server to change the TODO-list state.
What I have so far:
async function editCheckbox(id) {
try {
checkbox = {
completed: document.querySelector(`[data-id="${id}"]` + ' input[type="checkbox"]').checked
}
await fetch('http://localhost:8080/todo/' + id, {
method: 'PATCH',
body: JSON.stringify(checkbox),
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
} catch (err) {
console.log(err);
}
}
And I use a patch on the route:
app.patch("/todo/:id", (req, res) => {
const { id } = req.params;
let rawdata = fs.readFileSync("db.json", "utf8");
let content = JSON.parse(rawdata);
if (!content.find((i) => i.id == id)) {
return res.status(404).json({ message: "Todo with that id not found" });
} else {
const newTodo = req.body;
const toWrite = content.map((i) => {
if (i.id === id) {
return newTodo;
}
return i;
});
fs.writeFileSync("db.json", JSON.stringify(toWrite), (err) => {
if (err) {
console.error(err);
}
});
res.status(202).json(newTodo);
}
});

Using fetch from JavaScript to get one meal recipe form an API "TheMealDB" I can´t access=>erro 404

/* Create an event loader to all of the events */
document.addEventListener("DOMContentLoaded", () =>{
let button = document.querySelector("#button");
let firstCont = document.querySelector(".container2");
let secondCont = document.querySelector(".container3");
button.addEventListener("click", () => {
dataRenovation(firstCont, secondCont);
firstCont.classList.remove("hidden");
secondCont.classList.remove("hidden");
})
});
function dataRenovation(first, second){
const option = {
method: "GET",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "https://www.themealdb.com/"
}
};
fetch("www.themealdb.com/api/json/v1/1/random.php", option)
.then(response => {
alert(response.url);
if(response.ok) {
return response.json;
}else {
throw new Error(response.status);
}
})
.then(data => {
alert("Data: " + data);
})
.catch(err => {
alert("Error: " + err.message);
});
}
It return error: 404. I have noticed that the url returned is not the original, Js return the normal url preceded by my actual domain direction at this case http://127.0.0.1:5500/ as the normal domain.
I readed something about corss and added "Access-Control-Allow-Origin": "https://www.themealdb.com/" to can access to the normal API but I don´t know if that´s the correct inplementation.
I´d like to get some help and if you can let me some links to learn more about API and Corss.
Thank you.

How to a read a string value after post response with fetch api

I am trying to get the response and be able to read the value of the post it returns either as null or has data to verify the post before moving on to the next section, I am using the fetch api method I got the response and got it working with the form but I cant get the javascript to read if the response is null or not but got it on the console. Here is the code.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Origin", "*");
var acct = JSON.stringify({"acct":account});
var requestOptions = {
method: 'POST',
mode: 'cors',
headers: myHeaders,
body: acct,
//credentials: "include",
redirect: 'follow'
};
const doAjax = async () => {
const response = await fetch('http://myrestapi', requestOptions);
if (response.ok) {
const aVal = await response.text();
return Promise.resolve(aVal);
//return aVal;
}
else
{
return Promise.reject('*** PHP file not found');
}
}
function postData() {
if(response => response == null){
console.log("I am Null ");
}
else
{
console.log("I am ALIIIIIIVE ");
}
}
doAjax()
.then(response => console.log(response))
.finally(response => postData())
.catch(error => console.log('error', error + account));
You probably want to pass the response to postData like this:
function postData(response) {
if(response === null) {
console.log("I am Null ");
} else {
console.log("I am ALIIIIIIVE ");
}
}
doAjax()
.then(response => postData(response))
.catch(error => console.log('error', error + account));

Make Multiple Post Requests In Axios then get all the response to make another request

i have already make 2 request.., but i want to make a patch request using the id from each response...
the other one will be put in the first one and the second one will be in the data
can we maybe pass it to the var ? idk how to do that..
for reference i use gatsbyjs and i use directusCMS
let url3 = `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/items/pendaftar/:id (the id should be from the first response that we just made)?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`;
axios.patch(url3, data, {
data: JSON.stringify(
{
featured_image: 1 (id of the second response whcih is an image),
}),
})
event.preventDefault();
const data = new FormData()
data.append('file', this.state.selectedFile)
console.warn(this.state.selectedFile);
console.log(data);
// console.log("User Email :" + this.state.email)
// console.log("User nama :" + this.state.name)
// console.log("User telepon :" + this.state.telepon)
// console.log("User program :" + JSON.stringify([this.state.program]))
// console.log("User tanggal :" + this.state.tanggal_lahir)
// console.log("User tempat :" + this.state.tempat_lahir)
let url = `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/items/pendaftar?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`;
let url2 = `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/files?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`;
let url2 = `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/files?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`;
axios(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: JSON.stringify({
status:"published",
nama: this.state.name,
// email: this.state.email,
// telepon: this.state.telepon,
// program: [1],
// tanggal_lahir: this.state.tanggal_lahir,
// tempat_lahir: this.state.tempat_lahir,
})
})
.then(res => {
console.log(res)
return axios.post(url2, data, {
data: JSON.stringify(
{
data: data,
}),
})
})
.then(res => {
console.log(res.data.data.id)
return axios.patch( url3, {
})
})
.catch(error => {
console.log(error)
});
I made a very simplified example of what you're trying to accomplish using async/await syntax since .then() would be messier to read; basically you can store the result of each post request in a variable to use in your patch request. I'm not sure what your response object looks like, so you may have to do some additional property extraction.
//simulates 1st post request
const post1= new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000)
});
//simulates 2nd post request
const post2= new Promise((resolve, reject) => {
setTimeout(() => resolve(2), 1000)
});
const groupedRequests = async() => {
//represents calling your 1st post request;
let id1 = await post1;
//represents calling your 2nd post request
let id2 = await post2;
//represents your patch request
console.log(id1, id2)
}
groupedRequests();
Edit: I went ahead and did the .then() version so you could see the comparison.
//simulates 1st post request
const post1= new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000)
});
//simulates 2nd post request
const post2= new Promise((resolve, reject) => {
setTimeout(() => resolve(2), 1000)
});
//stores first result
let id1;
//represents callings 1st post request
post1
.then(result => {
id1 = result;
//represents calling 2nd post request
return post2;
}).then(result => {
let id2 = result;
//represents your patch request
console.log(id1, id2)
})

Dynamically adding post at the site using Observables (Angular)

I need to display posts dynamically on my home page. I have textarea above the post lists and my goal is to display new post immediatelly after it would be added, on the top of the post list. Component with textarea form is called add-post-component and it use onSubmit event:
onAddPostSubmit() {
if (this.authService.loggedIn()) {
const post = {
content: this.content,
creator_username: JSON.parse(localStorage.getItem('user')).username,
rate: 0
};
this.postsService.addPost(post).subscribe(data => {
if (data.success) {
console.log('Post added');
this.router.navigate(['/']);
} else {
console.log('Post not added' + JSON.stringify(data));
this.router.navigate(['/']);
}
});
} else {
console.log('Not logged');
return false;
}
}
Component of my main page is called Feed-component
this.postsService.getPosts().subscribe(response => {
this.posts = response.posts.reverse();
}),
err => {
console.log(err);
return false;
};
this.subscription = this.postsService.fetchPost().subscribe(post => {
this.postsService.getPosts().subscribe(response => {
this.posts = response.posts.reverse();
}),
err => {
console.log(err);
return false;
};
});
Both components use posts service:
getPosts() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/posts/fetch', {headers: headers})
.map(res => res.json());
}
addPost(post) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.subject.next({post});
return this.http.post('http://localhost:3000/posts/add', post, {headers: headers})
.map(res => res.json());
}
fetchPost(): Observable<any> {
return this.subject.asObservable();
}
As you can see, I use Observable methodology to process data between components. The problem which I have is that post list is updating after I add post to database, but without the last added post. So if I would add two posts - 1) 'abc' and 2) 'cba', after send 'abc' anything happened, and when I add 'cba' list will be updated with 'abc' on the top.
I think the case is that addPost method is calling after getPosts and fetchPost.
How to fix that?

Categories

Resources