how to capture javascript request payload in php - javascript

I am sending a request payload from a javascript function like such
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
fetch('https://www.eg.com/tq.php', {
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: id // i get the id here.
})
});
return window.location.href = "https://www.https://www.eg.com/tq.php";
});
}
}).render('#paypal-button-container');
In my PHP file I want to retrieve that id. I did :
$data = $_POST['orderID'];
AND
$data = json_decode($data);
echo $data->orderID;
AND
even tried changing the url to x-www-form-urlencoded. Still I do not get the value. When I check on the payload I do see the orderID, I also see a 200 OK. Can someone show me what i'm doing wrong? I did research stackoverflow and still can't get this to work. Please help.

fetch function will send GET request if you don't pass method: POST in config explicitly.
That's why you're not getting orderID from $_POST in server-side.
Insert method: "POST" in config like this.
fetch("https://www.eg.com/tq.php", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
orderID: id // i get the id here.
})
});

Related

How do I get the return statement from JavaScript's Fetch?

Now I'm using Fetch to fetch some data from an API in SpringBoot.
const onSubmit = (data) => {
fetch("http://localhost:8080/addMedicine", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
};
Here is the Java code.
#PostMapping("/addMedicine")
public String addMedicine (#RequestBody Medicine medicine){
return medicineService.addMedicine(medicine);
}
public String addMedicine(Medicine medicine) {
medicineRepository.save(medicine);
System.out.println("Added medicine "+ medicine.getMedicineName());
return "Added medicine "+ medicine.getMedicineName() ;
}
The above methods are from different classes I just put them here to simplify my question.
Now when I use Postman I get the statement like
"Added medicine X"
Now when I post the data from my Frontend app which is in React. I want to get that statement so that I can use it to display something on the page as a confirmation.
How am I going to do it or for more info how does even Postman do it because it looks so easy from them? Please help.
this should work :
const onSubmit = (data) => {
fetch("http://localhost:8080/addMedicine", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}).then(data=>{
// Do something ....
})
};

When sending POST request to backend API via fetch(), the body has only key and no value

When I'm sending a POST request to my backend express server, the req.body contains only the key part where the entire body is the key and the value part is empty
This is the frontend fetch request
let data = {
videoUrl: "dummy text"
}
fetch("/api/getinfo", {
method:"POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: JSON.stringify(data)
})
This is how I handle it in backend (NOTE: I'm using body-parser)
app.post("/api/getinfo", (req,res) => {
console.log(req.body);
}
I expect the output to be
'{ "videoUrl":"dummy text" }'
But what I get is
{ '{"videoUrl":"dummy text"}': '' }
The entire requests body is the key, and the value is empty.
What am I doing wrong?
You are using the wrong Content-Type to send json
Try
"Content-Type": "application/json;charset=UTF-8"
I noticed an issue in your header;
fetch("/api/getinfo", {
method:"POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" //this very line
},
I guess what you meant is
fetch("/api/getinfo", {
method:"POST",
headers: {
'Content-type': 'application/json; charset=utf-8'
},
Note: Your header denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. So you need to be sure of what you're writing in your header else you will end up with an error.
I will suggest you get to read more about What does “Content-type: application/json; charset=utf-8” really mean?
The problem is that you are stringifying the data:
body: JSON.stringify(data)
should be
body: data
That should fix it

Posting data to django rest framework using javascript fetch

I'm trying to post data to my django rest framework using javascript fetch. I've already set up and liked the DRF to my model and got everything set up from the backend. I used the postman app to ensure "get", "post" etc are all working as interned. However, now I'm having problem posting data using javascript to post the data using fetch. I want to add data to my article model which has a "headline", "tag", "content", "background_image" and the user that posted the article.
This is how my code looks like
data = JSON.stringify({
headline: "Testing",
tag: "Testing",
background_image: "Testing",
content: "Testing",
user: 1
})
fetch(
"http://127.0.0.1:8000/api/v1/articlesapi/",
{
method: "post",
headers: {"Authorization":"Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e"},
body: data
}
).then(function(response) {
return response.json();
}).then(function(data) {
console.log("Data is ok", data);
}).catch(function(ex) {
console.log("parsing failed", ex);
})
However, I keep getting the error parsing failed TypeError: Failed to fetch. Does anybody know what I'm doing wrong ?
Please add "Content Type" and "Accept" properties in your header, I think it could be a reason of your error. Let me know if it works :-)
fetch('"http://127.0.0.1:8000/api/v1/articlesapi/', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization':'Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e'
},
body: JSON.stringify({data: "your data"})
}).then(res=>res.json())
.then(res => console.log(res));

Instagram authentication API not returning access token

The instagram "server side workflow" for authenticating a user and giving them a session access token doesn't work. First part works in that I can get a code back from here:
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
However, when posting this code to
https://api.instagram.com/oauth/access_token
in order to obtain the access token, it just response with "YOU MUST PROVIDE A CLIENT ID", even though I have provided this as part of the form data - the same client id I used to get the code in the first place!
Here is the code I am using:
getIgToken: function (igCode) {
let data = {
client_id: config.imported.instagram.client_id,
client_secret: config.imported.instagram.client_secret,
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:5000/app/scrape',
code: igCode
}
return $http({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: data,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
}
Apparently others have reported problems with posting the data as json, which have then been resolved by using "application/x-www-form-urlencoded" - however this doesn't seem to work either now.
Here is the exact error message returned:
{error_type: "OAuthException", code: 400, error_message: "You must provide a
client_id"}
code:400
error_message:"You must provide a client_id"
error_type:"OAuthException"
grant_type should be 'authorization_code'
convert the data object to json format , try
data: JSON.stringify(data),
your code will look like this
getIgToken: function (igCode) {
let data = {
client_id: config.imported.instagram.client_id,
client_secret: config.imported.instagram.client_secret,
grant_type: 'authorisation_code',
redirect_uri: 'http://localhost:5000/app/scrape',
code: igCode
}
var jsonData= JSON.stringify(data)
return $http({
method: 'POST',
url: 'https://api.instagram.com/oauth/access_token',
data: jsonData,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
}

malformed JSON string Error while passing JSON from AngularJS

I am trying to pass JSON string in ajax request. This is my code.
NewOrder = JSON.stringify (NewOrder);
alert (NewOrder);
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: "mydata="+ NewOrder
};
$http(req)
.success(function (data, status, headers, config) {
alert ('success');
})
.error(function (data, status, headers, config) {
alert (status);
alert (data);
alert ('Error')
});
alert (NewOrder) gives -
{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}
Which seems to be a valid JSON string.
But in script side I am getting following error. in this line
my $decdata = decode_json($cgi->param('mydata'));
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")
Can please someone help me why i am getting this error?
$cgi->param('myData') returns the query param string 'mydata', which in your case is not sent.
You're posting the json data in the request body of your http post payload, and not as a query/form param. In that case, you'd need some other function to read the contents of the request body in your server-side script.
which happens to be:
my $data = $query->param('POSTDATA');
as described in here: http://search.cpan.org/~lds/CGI.pm-3.43/CGI.pm#HANDLING_NON-URLENCODED_ARGUMENTS
Also you should remove the "mydata=" from your json in the body you post, because http request payload bodies do not have parameter names (they're for query/form-params only).
Your end code should be like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: NewOrder
};
and the servers side:
my $decdata = decode_json($query->param('POSTDATA'));
I think it may be related to this issue: AngularJs $http.post() does not send data
Usually I would post data like this:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: {"mydata" : NewOrder}
};
However I am assuming that you are expecting the data as request params from this:
my $decdata = decode_json($cgi->param('mydata'));
If that is the case then the linked SO question is what you are looking for.
Angular $http.post accepts two params as url and payload
var url = '/cgi-bin/PlaceOrder.pl';
var payLoad = {'myData' :JSON.stringify(NewOrder)};
$http.post(url, payLoad)
.success(function(data) {
console.log(success);
})
At the server side, while fetching the required json string from the request param and then desearlize the json as following:
$result = $cgi->param('myData');
my $decdata = decode_json($result);

Categories

Resources