PHP Webhost Operation Checking - php

I wanted perform checking if the PHP Webhost is complete whenever perform a update function, if everything doing fine then send an notification and let the Application know the Operation is Doing fine.
Basically I wanted to know if the query in PHP work and use my application to notify the user.
is there any way or method to do so?
I using this method to fetch data from PHP in my React Native App
RecipeUpdation = () =>{
const { ID } = this.state ;
const { Name } = this.state ;
const { Type } = this.state ;
const { Ingredient } = this.state ;
const { Step } = this.state ;
return fetch('https://www.update.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
RecipeID : ID,
RecipeName : Name,
RecipeType : Type,
RecipeIngredient: Ingredient,
RecipeStep: Step
})
}).then((response) => response.json())
.then((responseJson) => {
}).catch((error) => {
console.error(error);
});
}

Basically we can verify if the Operation in PHP is successful or not by Checking the Query Execution Status. A very Basic way to do the checking is using If Else to see if the Query Function return True(Success) or False(Fail). You can also always return some Message through JsonResponds.
Here some example Code for PHP checking and Return Some Message:
// Using If Else to Check if operation Success or Not
if(mysqli_query($connection,$Your_Query)){
$MSG = 'Success' ;
// Convert message into Json format first
$json = json_encode($MSG);
// This is where it return the message to Application.
echo $json ;
}
else{
$MSG = 'Failed' ;
$json = json_encode($MSG);
echo $json ;
}
In your Application Code you already have the implementation to retrieve the JsonResponds(the Message) which have been echo in the PHP Code, I would suggest use a simple method which is Alert to pop out the message in your React Native Application to notify the User the Operation Status.
}).then((response) => response.json())
.then((responseJson) => {
// this responseJson Already have the echo Message from PHP
// just Display the Status with Alert Function
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
Hope this would help.

Related

Angular HTTP POST request doesn't create anything

I'm using Angular with PHP and trying to post an object. Request status is 200, but $_POST array is empty. Data I'm sending is a valid JSON Object.
sendTweet(){
if(!this.username || !this.tweet){
alert("Enter username or tweet");
return;
}
const newTweet:Tweet = {
username: this.username,
tweet: this.tweet
}
//Call Service
this.testService.postTweet(newTweet).subscribe((response)=>{console.log(response)},
(err:any)=>{
console.log(err.message);
});
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
postTweet(tweet:Tweet):Observable<Tweet>{
const url = `${this.apiUrl}/?page=submit&action=add`;
return this.http.post<Tweet>(url,tweet, httpOptions);
}
PHP:
if (isset($_POST['tweet'])&&isset($_POST['username'])) {
//Sending tweet to the db
} else{
print_r($_POST);
}
i dont know if its a backend problem with php but in my project i have it a little bit diferent (i am using .net core for backend)
for example in my project:
//service component WebScrapLinkService
get(): Observable<Any[]> {
return this.http.get<Any[]>(this.url)
.pipe(map(res => res));
}
//main component
getRegisters() {
this.getProductsSub = this.crudService.get()
.subscribe(data => {
this.registers = data;
})
}
//variables
public registers: Array<object> = [];
//the service goes in the constructor
private crudService: WebScrapLinkService
this works fine for me, i hope it is useful for you
It was just me not knowing that in PHP you have to parse HTTP_RAW_POST_DATA in order to get the data.

How to get response from API using Angular 9 http post request

I am using Postman to make POST request to API and save data to DB and I am getting as response {message:"Contact created successfully"}. BUT in Angular I don't get any response. What I am doing wrong?
I have provided a piece of my code below.
Angular Service
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => { console.log(response); }),
catchError(this.handleError)
);
}
Contact.component.ts
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe();
//this.contactLst = this.contactService.get();
}
addContact.php
//more code here
// create the product
if($contact->create()){
// set response code - 201 created
http_response_code(201);
// tell the user
echo json_encode(array("message" => "Contact was created."));
}
// if unable to create the contact, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to create contact."));
}
Any help is welcome.
You're not actually returning the response. You are only logging it:
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => response ), // <- return response
catchError(this.handleError)
);
}
To call it, you need to specify what happens in your subscribe callback:
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe( r => console.log(r) );
//this.contactLst = this.contactService.get();
}

The variables never reach PHP from the FETCH API

I have 3 files (HTML,JS and PHP) in the HTML save de info in variable called DatosPaciente in JavaScript
function Tomar_DATOS(){
DatosPaciente={
id:document.getElementById("paciente_id").value,
fecha:document.getElementById("fecha").value
};}
Then i use a function called Tiene_Cita_Hoy inside of a JS file
Tiene_Cita_Hoy(DatosPaciente)
in the JS file i try to use the Fetch API to send info to the PHP file
function Tiene_Cita_Hoy(Datos){
console.log(Datos);//"{id: "8", fecha: "2020/09/03"}" here everything is fine
fetch('tiene_cita.php',{
method: 'POST',
body: Datos
})
.then(res => res.json())
.then(data => {
console.log(data); //to see the result
})
}
then in a PHP file, then tried to receive the information via POST
$VALOR_id_paciente=$_POST['id'];
$VALOR_fecha=$_POST['fecha'];
and then I assign those values ​​to a query
$SQL="SELECT * FROM vhsagenda WHERE PACIENTE='".$VALOR_id_paciente."' AND FECHA='".$VALOR_fecha."'";
echo json_encode($SQL);//just to see what information have
but the result is always: SELECT * FROM vhsagenda WHERE PACIENTE='' AND FECHA=''
apparently the information never reaches the PHP file
I have made some proper way for this method to get working.
You need to make an object first, then pass it in 'for loop'. It will generate string like this for example (test=123&test_two=444)
async function catch_something(url, bodyContent = {test: 123, test_two: 444}){
let bodyContent_string = '';
if(bodyContent instanceof Object){
for(const form_key of Object.keys(bodyContent)){
if(form_key != Object.keys(bodyContent)[Object.keys(bodyContent).length - 1]){
bodyContent_string += `${form_key}=${bodyContent[form_key]}&`;
}else{
bodyContent_string += `${form_key}=${bodyContent[form_key]}`;
}
}
}
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: bodyContent_string
}).catch((error) => {
console.error('Error:', error);
});
if(!response.ok){
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
You should send the parameters as a URL-encoded string.
function Tomar_DATOS(){
DatosPaciente = 'id=' + encodeURIComponent(document.getElementById("paciente_id").value) + '&fecha=' + encodeURIComponent(document.getElementById("fecha").value);
}
You've passed a plain object to the body parameter, but fetch doesn't know what to do with that data type (so it converts it to the useless string "[object Object]").
You should pass something that fetch knows how to convert into something supported by PHP instead.
e.g. a FormData object.
DatosPaciente = new FormData(document.getElementById("form_containing_your_inputs"));

TypeError: Network request failed using fetch ReactNative and Laravel response

I am posting data to Laravel and expect a success response, but it catches the exception TypeError: Network request failed. Using get methods and login post methods using Laravel passport works all fine.
Adding 'Content-Type': 'application/json' to headers creates Network request failed for the login methods.
Postman returns valid errors or success, so works totally as expected.
Debugging showed that the request has been sent to Laravel and routing is correct as Visual Studio Code debugger stops at a breakpoint at return response.
public function postMessages()
{
...
return response()->json(['success' => 'success'], 200);
}
Route::middleware('auth:api')->group(function () {
Route::post('messages', 'Api\ChatController#postMessages');
});
export const fetchApi = async (endPoint, method = 'get', body = {}) => {
const accessToken = authSelectors.get().tokens.access.value;
const accessType = authSelectors.get().tokens.access.type;
let headers = {
...(accessToken &&
{
Authorization: `${accessType} ${accessToken}`
}
)
};
let response;
if (method=='get' || Object.keys(body)==0 ) {
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers
});
} else {
var formData = new FormData();
Object.keys(body).forEach(type => {
formData.append(type, body[type]);
});
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers,
body: formData
});
console.log('fetch response: ' + JSON.stringify(response));
}
let responseJsonData = await response.json();
return responseJsonData;
}
export const postMessages = (eidug, type, name, messages) => fetchApi('/message', 'post', {
'eidug': eidug,
'type': type,
'name': name,
'messages': messages
});
I expect a response without any exception like Postman. What can be going wrong?
Have you enabled CORS in the backend? Once open inspect->network and then run fetch. Show if there are any errors.

What value should be passed with AsyncStorage?

I am currently a beginner of react native and I want to know if I wanted to login and store user data using AsyncStorage, what key and value should be passed?
AsyncStorage.setItem('key', 'value');
UserLogin = () =>{
const { username } = this.state ;
fetch('https://www.example.com/React/user-login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('ProfileScreen', { username:username });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
If I were to say if logged in, then AsyncStorage.setItem('key', 'value');, then that could work if I want to store say the user's username so that I can display it on their profile page?
AsyncStorage parameters are both strings, so you can store serialised json data or just a plain string.
// Some code that logs someone in and gets an authentication token which then is stored
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
// then somewhere else in your code
AsyncStorage.getItem('token').then(authenticationToken => {
console.log(‘the token’, authenticationToken)
})

Categories