How to send data to server React Native | - javascript

I made a react native project and I got a prolem
I try to send a data to my server but the server didn't get the data.
I already made a code but its not work properly
and here's my code
constructor(props) {
super(props)
this.state = {
e :"",
}
}
componentWillMount(){
this.UserLoginFunction(View);
}
UserLoginFunction = () =>{
fetch('https://sen.000webhostapp.com/Profile.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
em: this.state.e,
})
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(JSON.stringify(responseJson));
}).catch((error) => {
Alert.alert(error);
});
}
render() {
AsyncStorage.multiGet(['email']).then((data) => {
let email = data[0][1];
if (email !== null){
this.setState({
e:email
});
}
});
return()
}
and the .php file is
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$u = $obj['em'];
echo json_encode($u);
but the respond is nothing I got null. can anyone solve this?

Related

React: How to do form submit data successfully and then page refresh/redirect to home page?

I am submitting the data. Api is working fine. It submits the data if I do not use window.location.href = "/".
Please update my code that successfully inserts the data all the time and then page refresh redirects to the home page. Please help.
handleSubmit(event) {
event.preventDefault();
const Category_ID = this.props.key_id;
const CategoryName = this.state.CategoryName;
const data = {
Category_ID,
CategoryName
}
fetch(REQUEST_URL, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.catch(() => console.log("error in posting data"));
window.location.href = "/";
}
}
Thanks
Just add the refresh part inside then()
handleSubmit(event) {
event.preventDefault();
const Category_ID = this.props.key_id;
const CategoryName = this.state.CategoryName;
const data = {
Category_ID,
CategoryName
}
fetch(REQUEST_URL, {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' }
})
.then(response => {window.location.href = "/";})
.catch(() => console.log("error in posting data"));
}
}

AJAX Javscript - PHP

I learn MVC and make some AJAX interaction. So I've routes file with
'cart/addProductAjax' => 'cart/addProductAjax',
CartController with actionAddProductAjax:
<?php
class CartController
{
public function actionIndex() {
}
public function actionAdd($productId) {
Cart::addProduct($productId);
$referer = '/';
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
}
header("Location: $referer");
}
public function actionAddProductAjax() {
$productId = $_POST['productId'];
print_r($_POST);
exit;
Cart::addProduct($productId);
$itemsAmount = Cart::countItems();
exit(json_encode($itemsAmount));
}
}
And JS piece of code that send request and receive response from the server:
document.body.addEventListener('click', event => {
if(event.target.classList.contains('add-to-cart')) {
event.preventDefault();
let productId = event.target.dataset.id;
let response = fetch("/cart/addProductAjax/", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(productId),
})
.then(response => response.json())
.then(response => console.log(response));
}
});
And nothing works. I think there is an error somewhere in PHP method. What shoul I do to make it work?

Post action API with object parameter within the URL

I've got an API where some of the parameters need to be given within the URL.
Example of how my api url looks like: https://www.server.com/api/actions/execute?auth_type=apikey&data={"Name": "name","Email" : "email"}
What my code looks like right now
register = async () => {
let data = {"Name":this.state.name, "Email":this.state.email}
data = JSON.stringify(data)
let URL = 'https://www.server.com/api/actions/execute?auth_type=apikey&data=';
fetch(URL, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: data
})
.then((response) => response.text())
.then((responseText) => {
alert(responseText);
})
.catch((error) => {
console.error(error);
});
}
The response I get on my device:
{"code":"succes","details":{"userMessage":["java.lang.Object#2e56000c"],"output_type":void","id:"20620000000018001"},"message":"function executed succesfully"}
This is alle working fine when I test it in postman but I can't get it to work within React-Native. I've tried stuff like 'Content-Type':'application/x-www-form-urlencoded' already.
First install the package axios from the url https://www.npmjs.com/package/react-native-axios
Then create two service for handling get and post request so that you can reuse them
GetService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const GetService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.get(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
PostService.js
import axios from 'axios';
let constant = {
baseurl:'https://www.sampleurl.com/'
};
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
}
};
export const PostService = (data,Path,jwtKey) => {
if(jwtKey != ''){
axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
}
try{
return axios.post(
constant.baseUrl+'api/'+Path,
data,
config
);
}catch(error){
console.warn(error);
}
}
Sample code for using get and post services is given below
import { PostService } from './PostService';
import { GetService } from './GetService';
let uploadData = new FormData();
uploadData.append('key1', this.state.value1);
uploadData.append('key2', this.state.value2);
//uploadData.append('uploads', { type: data.mime, uri: data.path, name: "samples" });
let jwtKey = ''; // Authentication key can be added here
PostService(uploadData, 'postUser.php', jwtKey).then((resp) => {
this.setState({ uploading: false });
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
GetService({}, 'getUser.php?uid='+uid, jwtKey).then((resp) => {
// resp.data will contain json data from server
}).catch(err => {
// handle error here
});
If you need to pass parameters via URL you should use GET, if you use POST then the parameters should be passed in the body

How can I run a code after another has already ended running?

In less than 1 second, I have to post something into a JSON file and then get that exact data updated. When running the code, it seems that I post the data in the JSON file but when I try to get it, it gets the old data, not the updated one.
How can i run get method after post method has ended running?
I ran this post method
import Game from "./components/Game/Game";
class App extends React.Component {
postUserInfo(){
fetch("http://localhost:8080/api/users" , {
method: "post" ,
mode: "cors",
headers: {
"Content-type": "application/json",
},
body:JSON.stringify({username:this.state.userInput, bestscore:0})
})
.then((res) => res.json())
.then((data => {console.log(data)}))
.catch((error) => {
console.log(error);
});
}
}
and then in the other class I run this get method right after the post method
class Game extends React.Component {
getUserInfo() {
fetch("http://localhost:8080/api/users" , {mode: "cors"})
.then((res) => res.json())
.then((data => {
this.setState({ usersInfoArray: data})
var _userid = data[data.length-1].id;
var _username = data[data.length-1].username;
var _bestscore = data[data.length-1].bestscore;
this.setState({ userid: _userid, username: _username, bestscore: _bestscore});
}))
}
}
componentDidMount(){
this.getUserInfo();
this.render();
}
I guess you may call postUserInfo() in another component then move to new Component
then after component mount, call getUserInfo()
Am i right?
If so
your navigate to(or create) other component logic must in postUserInfo()
near
.then((data => {console.log(data)}))
Probably the easiest way to do this is to maintain a dataPosted flag in App's state and pass that flag to the Game component. If the dataPosted flag is true, then load the data.
App.jsx
import Game from "./components/Game/Game";
class App extends React.Component {
constructor() {
super();
this.state = { dataPosted: false }
}
postUserInfo(){
fetch("http://localhost:8080/api/users" , {
method: "post" ,
mode: "cors",
headers: {
"Content-type": "application/json",
},
body:JSON.stringify({username:this.state.userInput, bestscore:0})
})
.then((res) => res.json())
.then(data => {
this.setState({ dataPosted: true })
})
.catch((error) => {
console.log(error);
});
}
}
render() {
<Game dataPosted={this.state.dataPosted} />
}
}
Game.jsx
class Game extends React.Component {
componentDidUpdate() {
if (this.props.dataPosted) {
this.getUserInfo();
}
}
getUserInfo() {
fetch("http://localhost:8080/api/users" , {mode: "cors"})
.then((res) => res.json())
.then((data => {
this.setState({ usersInfoArray: data})
var _userid = data[data.length-1].id;
var _username = data[data.length-1].username;
var _bestscore = data[data.length-1].bestscore;
this.setState({ userid: _userid, username: _username, bestscore: _bestscore});
}))
}
}

Getting Json fetched data on second attempt

I am getting my fetched Json data on second attempt. I have to refresh my screen two times to get the data. Thoughts?
var data = [];
class Profiel extends Component {
constructor(props) {
}
componentDidMount() {
this.setState({fetching:true},()=>{
this.getData().then(JsonData => data=JsonData).then(console.log(data));
});
}
getData(){
return fetch('https://Domain.eu.auth0.com/userinfo', {
method: 'GET',
headers: {
Authorization: 'Bearer ' + token,
},
}).then((response) => {return response.json()})
};

Categories

Resources