I try to send a request from javascript with the code below,
but the problem is that php server didn't receive data in $POST or $_GET. I tried many solutions but i didn't find one.
request: function(query, type = "POST", data, async = false, callback) {
var xhttp = new XMLHttpRequest();
var args = [];
if(arguments.length > 4)
for (var i = 5; i < arguments.length; i++)
args.push(arguments[i]);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(async) {
msg = this.responseText;
console.log(msg);
msg = JSON.parse(msg);
//Context.update(msg.extended);
var array = [msg];
for (var i = 0; i < args.length; i++)
array.push(args[i]);
console.log(args);
callback.apply(this,array);
} else {
msg = this.responseText;
console.log(msg);
msg = JSON.parse(msg);
console.log(msg);
}
}
};
xhttp.open(type, query, async);
xhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
if(Object.keys(data).length > 0)
xhttp.send(JSON.stringify(data));
else
xhttp.send();
if(typeof(msg) !== "undefined")
return msg;
}
Maybe use an existing solution to make request, like fetch.
It will help you to no lose time on badly rewriting existing solution and focus on your real application goal.
Example code from the doc
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
Related
I tried to find a solution online and on stackoverflow but i think the answers from the other posts focus on other things.
My problem is the error when i try to fetch more then 1 Hubspot api call.
The error message:
body used already for: https://api.hubapi.com/crm/v3/objects/deals?limit=100&archived=false
(returns list of deals)
var data = [];
let Timestamp = new Date().toISOString();
let Webhook = inputData.Webhook.trim();
let Method = inputData.Method.trim();
let JSONObject = {}
let Options = {
method: Method,
headers: {
'Authorization': `Bearer Hidden Key`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(JSONObject)
}
const Request = await fetch(Webhook, Options); // HTTP POST Request
const Response = await Request.json() // HTTP POST Response
data.push(Response);
Response.push(await Request.json());
let Webhook2 = Response.paging.next.link;
if ('paging' in Response) {
for (let i = 0; i < 10; i++) {
if (Webhook2 != "") {
let Options2 = {
method: Method,
headers: {
'Authorization': `Bearer Hidden Key`,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(JSONObject)
}
const Request2 = await fetch(Webhook2, Options2); // HTTP POST
const Response2 = await Request2.json();
data.push(Response2);
if ('paging' in Response2) {
let Webhook2 = Response2.paging.next.link;
} else {
let Webhook2 = "";
}
}
}
}
output = data;
If someone could help me with this error i would really appriciate it.
Thanks in advance people.
I am trying to use a shell script to save data to mongodb then send the same to elasticsearch for analysis.
Below is a psudo code in the shell script that illustrate the issue.
mongo $mongo_conn --eval "
// other javascritp code
db.collection.insertOne(insertData);
http_post_to_elasticsearch(url,insertData);
function http_post_to_elasticsearch(url,insertData){
// which http_post() method can work here?
// both fetch and xhr are undefined
// tried installing npm install -g xmlhttprequest but 'require' is also undefined
}
Below are the functions that have tried but seem not to be supported
async function http_post(url = '', data = {}) {
print('starting http_post()')
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
async function xhr_post(url = '', data = {}) {
const xhr = require('xmlhttprequest').XMLHttpRequest;
// const xhr = new XMLHttpRequest();
// listen for `load` event
xhr.onload = async () => {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) {
// parse JSON
const response = JSON.parse(xhr.responseText);
printjson(response);
// return response;
}
};
// create a JSON object
const json = data;
// open request
xhr.open('POST', url);
// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json');
// send rquest with JSON payload
xhr.send(JSON.stringify(json));
}
mongo shell does not provide a browser nor a nodejs-compatible runtime.
You can look through the server js tests to see if there is anything there that resembles an http client.
See also ReferenceError: require is not defined in MongoDB shell.
I have a questionnaire on javascript(post request) and need to acquire the user's answers and then transform them into a JSON file, so far, I've tried this but I have no idea how to proceed, my code is down below.
exports.answers= (req, res) =>{
async function getISS(){
const response = await fetch(req);
const data =await response.json();
console.log(data);
}
getISS();
console.log(req.text);
let resultado =[data];
res.send(resultado);
};
The answers come from a survey like this
this is the survey
There are a number of ways to send the form data to the server.
const form = document.getElementById('my-form'),
url = 'https://reqres.in/api/users';
form.onsubmit = submit;
function submit(e) {
e.preventDefault();
const formData = new FormData(form),
data = {};
// Get a JSON object from the form data
formData.forEach((value, key) => {
data[key] = value;
});
// Using fetch and await/async
postData(url, data)
.then(res => {
console.log('Fetch await/async response is: ' + JSON.stringify(res)); // JSON data parsed by `response.json()` call
});
// Using fetch / then
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
}).then(
res => res.json()
).then(json => console.log('Fetch / then response is: ' + JSON.stringify(json)));
// Using XMLHttpRequest
const req = new XMLHttpRequest();
req.open('POST', url, true);
req.setRequestHeader('Content-type', 'application/json');
req.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 201) {
console.log('XMLHttpRequest response is: ' + req.response);
}
}
req.send(JSON.stringify(data));
}
/*
* This is the example function on the MDN site for fetch
* https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
*/
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
<form action="survey" id="my-form">
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="job">Job</label>
<input type="text" name="job" id="job">
<button>Submit</button>
</form>
Any of the above methods should work to send your form data to the server as JSON. I have used an online API to demonstrate.
trying to direct to external url by fetch
front end side:
var params
urlFetch(new_url)
.then(params=function() {
var obj=decodeFormParams(params)
console.log("decode value is " + obj); ...
backend side:
export function urlFetch(url ) {
console.log(url );
const request = async () => {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, *cors, same-origin
credentials: 'omit', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8 ',
"Access-Control-Allow-Origin": "*"
},
// body: JSON.stringify() // body data type must match "Content-Type" header
}).then(await function(Response) {
if (Response.ok) {
return Response.text();
}
else {
return Promise.reject("Fetch did not succeed");
}
} )
}
}
CONSOLE.LOG IS:
https://icom.yaad.net/cgi-bin/yaadpay/yaadpay3new.pl?action=pay&PassP=pb&Masof=4500563228&sendemail=True&UTF8=True&UTF8out=True&ClientName=ASG&ClientLName=Shg&cell=&email=SGD&Amount=500&Info=%D7%91%D7%99%D7%AA%20%D7%97%D7%91%22%D7%93%20%D7%A7%D7%A1%D7%A8%20%D7%93%D7%99%D7%95%D7%95%D7%99&tmp=8&Coin=1&PageLang=HEB&Postpone=False&Tash=36&FixTash=True&SendHesh=True
returend value is function params() {
console.log("returend value is " + _params);
var obj = decodeFormParams(_params);
console.log("decode value is " + obj);
AS YOU CAN SEE THE URL IS CORRECT AND SUPPOSE TO REDIRECT TO THAT PAGE BUT NOTING HAPPENDS AND THE FUNCTION DOESNT WAIT
If IT DIDNT WORK WhY IM NOT GETTING THE LOG OF THE ERROR:
else {
return Promise.reject("Fetch did not succeed");
im sending parameters to a page for payment system and the user has to fill the card info there and if it succeeds i should get code=0 as results but nothing hapends
I'm quite new to using fetch and I dont know if I'm doing this right since it works fairly well with POST. If I use the normal fetch method, and not the function I made, the server responds with the data. But if I use this, the data becomes undefined. Any ideas on how I can fix this?
network_requests.js
export const getData = (url, data) => {
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json',
'Authorization': 'Token '+ localStorage.token
},
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()); // parses response to JSON
};
sample usage: (doesnt work)
fetchDrivers() {
return getData('/members/drivers').then(data => {
if (!data["error"]) {
//for each entry in drivers data, append data as a dictionary in tableData
//ant tables accept values {"key": value, "column_name" : "value" } format
//I cant just pass the raw array since its a collection of objects
const tableData = [];
//append drivers with their ids as key
data["drivers"].forEach(item => tableData.push({
"key": item.id,
"name": item.name
}));
this.setState({drivers: tableData});
} else {
console.log(data["error"]);
}
});
}