PHP Get the body response - javascript

I'm trying to send API response from my Javascript file like this:
try {
await fetch('https://example.com/api', {
method: 'post',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'john',
})
}).then((response) => response.json())
.then((data) => console.log(data));
} catch (e) {
console.error(e);
}
Now I'm trying to get the body of the request.
My Backend Server built on PHP.
I have already seen this Stackoverflow Question.
As I saw there, I need to do this:
To access the entity body of a POST or PUT request (or any other HTTP method): $entityBody = file_get_contents('php://input');
This is my Index.php file:
<?php
$entityBody = file_get_contents('php://input');
echo json_encode($entityBody);
And it returns nothing.
I'm new to PHP so maybe its a stupid mistake.
My goal is to print john in the console.

Related

Creating tickets using Zendesk api with React

I working on intergrating a react app with the zendesk api for creating support tickets.
Till now i have completed the form flow, but when i making the request to the zendesk api i am getting 401.
I am using the api_key approach for this.
I am fairly new to zendesk, if anyone can help me regarding that.
Here is my code after user clicks submit.
const onSubmit = async () => {
try {
console.log('setInfo', info)
const data = { request: { subject: 'test', comment: { body: 'testdesc' } } }
const user = 'test#test.com'
const api_token = 'some_api_key'
const url = 'https://url.zendesk.com/api/v2/tickets.json'
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
Authorization: api_token,
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
console.log('respone', response)
} catch (error) {
console.log('respone error', error)
}
}
It looks like you're not sending the right authorization header. According to Zendesk API reference you need to use the following format for the credentials:
{email_address}/token:{api_token}
Example:
jdoe#example.com/token:6wiIBWbGkBMo1mRDMuVwkw1EPsNkeUj95PIz2akv
After base64-encoding the resulting string, add it to the Authorization header as follows:
Authorization: Basic amRvZUBleGFtcGxlLmNvbS90b2tlbjo2d2lJQldiR2tCTW8xbVJETXVWd2t3MUVQc05rZVVqOTVQSXoyYWt2

senfing POST in fetch return null

I want to learn how fetch works. Backend is very simple
<?php
print_r(json_encode($_POST['test']));
And I created this fetch
fetch('http://localhost/test.php', {
method: 'POST',
body: JSON.stringify({
test: 'test'
})
})
.then(res => res.json())
.then(data => console.log(data))
All the time this code return null in console.log. Where I make a mistake?
You have two problems.
Strings and Fetch
If you POST a string using fetch it will default to sending it with a Content-Type: text/plain header.
Plain text isn't JSON. Specify the correct Content-Type.
fetch('http://localhost/test.php', {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
test: 'test'
})
})
PHP won't process JSON formatted requests automatically
You need to read the raw body and parse it yourself. This is a FAQ. Here is the solution.

How to get the response object of an ajax request with laravel?

Guys I'm making a fetch request for laravel without using jquery and I would like to get the return of this request, however when I give a console.log() in the response the console informs undefined.
This is my request:
fetch(action, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": token
},
method: "post",
credentials: "same-origin",
body: JSON.stringify({
email: email,
password: password
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
This is my controller that returns the empty field information:
public function login(Request $request)
{
if (in_array('', $request->only('email', 'password'))) {
$json['message'] = "Empty";
return response()->json($json);
}
var_dump($request->all());
}
The request was successful and the browser informs the response message:
Object response message
However console.log(data) returns undefined, how can I return the object that contains the message?
Taking advantage of the question, is this the best way to make this request?
Thank you guys

How to make a HTTP post request like a HTML form using Axios?

I am trying to connect to an API (nova.astrometry.net) that requires an HTTP post request just like a form (x-www-form-encoded). I am using Axios for that, but still, I am getting this error as a response from the API { status: 'error', errormessage: 'no json' }
Here's the code for reference
axios({
method: 'post',
url: 'http://nova.astrometry.net/api/login',
data: {
'request-json': JSON.stringify({ "apikey": process.env.API_KEY })
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
}).then((response) => {
console.log(response.data)
});
I also tried using the request library but got the same response.
The content type required by the api is 'application/x-www-form-urlencoded' but you are sending 'application/json'.
To send that data, do the following:
const body = new URLSearchParams();
body.append('request-json', JSON.stringify({ "apikey": process.env.API_KEY }));
Then use the above body in the body field of axios.
axios.post('http://nova.astrometry.net/api/login', body, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(res => console.log(res.body))
.catch(console.error);

Redirect page only after success in PHP using Fetch

I'm creating a registration system for a university project. This is using fetch to post the data from the form to a PHP file.
I want to transfer over a $message variable that is echoed at the bottom of my PHP page to know if the registration has been successful, or if an error message has occurred. If I can see that the $message equals my success string, I think I can do an if statement using window.location.href like below? Currently it is redirecting the page for any successful fetch, no matter what the response from PHP is.
I've tried using header("Location: /index.html"); in my PHP file on the success line, but this also didn't work for me. I've spent hours looks for a solution but I really can't get my head around how to pass this variable over.
var myJSON = JSON.stringify(userDetails);
fetch("url/register.php", {
method: "POST",
mode: "no-cors",
cache: "no-cache", /
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
redirect: "follow",
referrer: "no-referrer",
body: myJSON
}).then((response) => {
if (response.ok) {
return response.blob();
} else {
throw new Error("Things went poorly.");
}
}).then((response) => {
//Fetch was successful!
window.location.href = "url/index.html";
}).catch((error) => {
console.log(error);
});
You can try this in your php file:
$response = [ message => "the message", success => true ];
echo json_encode($response);
You will receive a JSON response which you will use it to validate if the request was successful.
In your javascript code, you have to parse this JSON response to an literal object like:
fetch(url, {params})
.then(response => response.json())
.then((response) => {
if (response.success) {
// fetch was succesfull!
} else {
// response.message could be used to show what was wrong
throw new Error(response.message);
}
})
One way to accomplish this is to use the URL's query parameters to pass the success message. For example:
window.location.href = "url/index.html?login=success";
Then on the .html page you would have code that looks for the login query parameter and displays something if it's equal to success.

Categories