Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

php - Fetch returns nothing to <Text> after getting info from page 1 to Query API

This code works for php and returns the json Data, tested on my browser and postman

<?php
$host = 'localhost';
$db_user = 'id15131779_root';
$db_pass = '_8gJ{58#)Jgdh^{';
$db = 'id15131779_announcements';

$con = mysqli_connect($host, $db_user, $db_pass, $db) or die ('cannot connect, Reason : '.mysqli_error());

$AccountNum = mysqli_real_escape_string($con,$_GET['AccountNum']);
$sql = "select * from bankDetails where AccountNum = '$AccountNum'";
$result = mysqli_query($con,$sql);
$check = mysqli_num_rows($result);

if($check > 0)
{
    $row = mysqli_fetch_assoc($result);
    $Fullname = $row['Fullname'];
    $AccountNum = $row['AccountNum'];
    $email = $row['email'];
    $Telephone = $row['Telephone'];
    $balance = $row['balance'];
}
else
{
    $Fullname = "";
    $AccountNum = "";
    $email = "";
    $Telephone = "";
    $balance = "";
}

    $response[] = array("Fullname"=>$Fullname,"AccountNum"=>$AccountNum, "email"=>$email, "Telephone"=>$Telephone, "balance"=>$balance);
    echo json_encode($response);

?>

i get this back as Data when i make a GET Request for instance to the Rest API

https://uncoiled-crust.000webhostapp.com/api/searchData.php?AccountNum=0023736621

[{"Fullname":"Princewill Dickson","AccountNum":"0023736621","email":"[email protected]","Telephone":"08125527192","balance":"700000.00"}]

Dummy data , this data is not real, just fed into the system. Now I have this Code which is supposed to get the username from the Login form (The Login form being the Account number for instance ) and then use the same Data in Page 2 to query the API to return the data to be used.

Now Here is my Login page in React native it is supposed to search from

/* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View , Image, TextInput, TouchableOpacity, Alert, Linking} from 'react-native';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

class Login extends Component {

  constructor(props) {
    super(props);
    this.state = {
        user: '',
        password: ''
    };

    DummyLogin = () =>
    {
        alert('I am a Dummy Login!');
        this.props.navigation.navigate('Home',{user: this.state.user});
    }

    FunctionLogin = () =>
    {
        const {user} = this.state;
        const {password} = this.state;
        fetch('https://uncoiled-crust.000webhostapp.com/rest/login.php',{
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                user: user,
                password: password
              })
        }).then((response) =>response.json())
        .then((responseJson) => {
            if(responseJson === 'OK')
            {
                this.props.navigation.navigate('Announcements');
            }
            else
            {
                Alert.alert(responseJson);
            }
        }).catch((error) =>{
            console.error(error);
        });
    }
  }

  render() 
  {
      return (
      <View style={styles.container}>
        <Image source={{uri:'asset:/logo/436146d3-d290-459b-ae8a-bc5b07eacea1_200x200.png'}}
        style={styles.logo} />

        <Text style={{textAlign:'left',fontSize:40,fontWeight:'bold' ,color: '#030303'}}> Sign In</Text>

        <TextInput
            placeholder = " Account Number"
            onChangeText={user => this.setState({user})}
            style={styles.input}
            keyboardType='numeric'
            value={this.state.myNumber}
            maxLength={15} 
        />

        <TextInput
            placeholder = " Passcode"
            onChangeText={password => this.setState({password})}
            style={styles.input}
            secureTextEntry={true} 
            keyboardType='numeric'
            value={this.state.myNumber}
            maxLength={6} 
        />

        <Text style={{color: '#030303', textAlign: 'center', alignSelf:'stretch'}}
        onPress={() => Linking.openURL('http://google.com')}>
        Forgot Password? Reset
        </Text>

        <View style={styles.space} />
        <TouchableOpacity onPress={() => {DummyLogin();}} style={styles.button}>
        <Text style={styles.loginbtn}> Login </Text>
         </TouchableOpacity>
         <View style={styles.space} />
         <TouchableOpacity onPress={() => {DummyLogin();}} style={styles.Regbutton}>
        <Text style={styles.loginbtn2}> Register </Text>
         </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        justifyContent :"center",
        alignItems:"center"
    },

    input:{
        width:300,
        height:55,
        margin:10,
        fontSize : 15,
        fontWeight : 'bold',
        borderBottomColor:'#030303',
        borderBottomWidth: 1,
        marginBottom: 30,
    },

    button:{
        width:300,
        height: 52,
        padding:10,
        borderRadius:10,
        backgroundColor:'#030303',
        alignItems: 'center'
    },

    Regbutton:{
        width:300,
        height:52,
        padding:10,
        borderRadius:10,
        backgroundColor:'#ffffff',
        alignItems: 'center',
        borderWidth : 2,
        borderColor: '#030303'
    },


    loginbtn:{
        color:'#ffff',
        fontSize : 20,
        fontWeight : 'bold'
    },

    loginbtn2:{
        color:'#030303',
        fontSize : 20,
        fontWeight : 'bold'
    },

    logo:{
    width:150,
    height:150
    },

    space: {
        width: 10, 
        height: 10,
      },

      imageStyle: {
        flexDirection:'row',
        justifyContent:'center',
        padding: 5,
        margin: 2,
        height: 15,
        width: 15,
        resizeMode: 'stretch',
        marginBottom: 8,
        marginTop : 8,
        alignItems: 'center',
      },
});

export default Login;

Now the page its supposed to fetch information from the API and populate has tags on it, it just returns nothing to them. My code Looks something like this :

import React, { Component } from 'react';
import { Platform, StyleSheet,Text, View , Image, TextInput, TouchableOpacity, Alert, Linking, Dimensions, FlatList} from 'react-native';

export default class Home extends Component {
  
    constructor(props) {
    super(props);
    this.state = {
      AccountNum : '',
      Fullname : '',
      email : '',
      Telephone : '',
      balance : ''
    };
  }

  onclick_item(key)
  {
      switch(key)
      {
          case "BVN":
             this.props.navigation.navigate('bvn');
              //  const {navigation} = this.props;
              //  const username = navigation.getParam('user','NO-User');
              //  alert('Hello '+username);
              break;
          case "Transfers":
                this.props.navigation.navigate('Transfers');
                break;
          case "Bill Payments":
            this.props.navigation.navigate('BillPayments');
                break;
          case "Checkbook Requests":
                this.props.navigation.navigate('CheckBookRequest');
                break;
          case "Airtime Purchase":
                this.props.navigation.navigate('AirtimePurchase');
                break;
          case "Contact Us":
                this.props.navigation.navigate('Contact');
                break;
      }
  }


  componentDidMount()
  {
    this.getAccountDetails();
  }

  getAccountDetails = () =>
  {
    const {navigation} = this.props;
    const AccountNum = navigation.getParam('user','NO-User');
   var searchAPIURL = 'https://uncoiled-crust.000webhostapp.com/api/searchData.php?AccountNum='+AccountNum;
     var header = {
         'Accept': 'application/json',
         'Content-Type': 'application/json'
     };

     fetch(
         searchAPIURL,
         {
             method : 'GET',
             headers : header
         }
     ).then((response) => response.json())
      .then((responseJson)=> {
          this.setState({Fullname : responseJson.Fullname});
          this.setState({balance: responseJson.balance});
      })
  }

  render() {
      //const {navigation} = this.props;
      //const username = navigation.getParam('user','NO-User');
    return (
      <View>
        <Text style={styles.welcomeText}> Welcome , {this.state.Fullname}!  - 2080440475  </Text>
        <Text style={styles.balanceText}> ? {this.state.balance} </Text>
        <View
        style={{
            borderBottomColor: '#696b69',
            borderBottomWidth: 1,
         }}
        />
        <View>
        <Text style={styles.MenuText}> Menu </Text>
        <View style={styles.space} />
            <FlatList
            const data  = {[
                {key : 'BVN'},
                {key: 'Transfers'},
                {key: 'Bill Payments'},
                {key: 'Checkbook Requests'},
                {key: 'Airtime Purchase'},
                {key: 'Contact Us'},
            ]}
            renderItem={({ item }) => (
                <TouchableOpacity onPress={() =>this.onclick_item(item.key)} style={styles.button}>
            <View style ={styles.item}>
                <Text style = {styles.itemText} >{item.key}</Text>
            </View>
                </TouchableOpacity>
              )}
              numColumns = '2'
            />
        </View>
        <View style={styles.space} />
      </View>
    );
  }
}

const styles = StyleSheet.create({

    MenuText :{
        margin : 10,
        fontSize : 27,
        fontFamily : 'Verdana',
        fontWeight : 'bold',
        flexDirection : 'row'
    },

    welcomeText :{
        margin : 10,
        fontSize : 15,
        fontFamily : 'Verdana',
        fontWeight : 'bold',
        flexDirection : 'row'
    },

    space: {
        width: 10, 
        height: 10,
      },

    balanceText:{
        margin : 10,
        fontSize : 25,
        fontFamily : 'Verdana',
        fontWeight : 'bold'
    },
    accountNumText :{
        margin : 10,
        fontSize : 13,
        textAlign : 'right',
        fontFamily : 'Verdana',
        fontWeight : 'bold'
    },
    container:{
        flex :1,
        marginVertical :20
    },
    item : {
        backgroundColor : '#030303',
        borderRadius : 10,
        alignItems: 'center',
        justifyContent : 'center',
        flex : 1,
        margin : 1,
        height : Dimensions.get('window').width / 3
      },
      itemText:{
        color: '#fff'
      },
      button:{
        backgroundColor : '#030303',
        borderRadius : 35,
        alignItems: 'center',
        justifyContent : 'center',
        flex : 1,
        margin : 1,
        height : Dimensions.get('window').width / 3
      }

});

I need a guide as to what i am doing wrong


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i managed to fix the issue in the Long run, works perfectly. I had to remove the body and let it use a full GET request once and for all. And all works good now.

Code looks like this, Hopefully would help someone some day.

import React, { Component } from 'react';
import { Platform, StyleSheet,Text, View , Image, TextInput, TouchableOpacity, Alert, Linking, Dimensions, FlatList} from 'react-native';

export default class Home extends Component {
  
    constructor(props) {
    super(props);
    this.state = {
      AccountNum : '',
      Fullname : '',
      email : '',
      Telephone : '',
      balance : ''
    };
  }

  onclick_item(key)
  {
      switch(key)
      {
          case "BVN":
             this.props.navigation.navigate('bvn');
              //const {navigation} = this.props;
             //const username = navigation.getParam('user','NO-User');
              //alert('Hello '+username);
              break;
          case "Transfers":
                this.props.navigation.navigate('Transfers');
                break;
          case "Bill Payments":
            this.props.navigation.navigate('BillPayments');
                break;
          case "Checkbook Requests":
                this.props.navigation.navigate('CheckBookRequest');
                break;
          case "Airtime Purchase":
                this.props.navigation.navigate('AirtimePurchase');
                break;
          case "Contact Us":
                this.props.navigation.navigate('Contact');
                break;
      }
  }


  componentDidMount()
  {
    this.getAccountDetails();
  }

  getAccountDetails = () =>
  {
    const {navigation} = this.props;
    const AccountNum = navigation.getParam('user','NO-User');
   var searchAPIURL = 'https://uncoiled-crust.000webhostapp.com/api/searchData.php?AccountNum='+AccountNum;
     var header = {
         'Accept': 'application/json',
         'Content-Type': 'application/json'
     };

     fetch(
         searchAPIURL,
         {
             method : 'GET',
             headers : header
         }
     ).then((response) => response.json())
      .then((responseJson)=> {
          this.setState({Fullname:responseJson[0].Fullname});
          this.setState({balance:responseJson[0].balance});
          this.setState({AccountNum:responseJson[0].AccountNum});
      })
  }

  render() {
      //const {navigation} = this.props;
      //const username = navigation.getParam('user','NO-User');
    return (
      <View>
        <Text style={styles.welcomeText}> Welcome , {this.state.Fullname}!  - {this.state.AccountNum}  </Text>
        <Text style={styles.balanceText}> ? {this.state.balance} </Text>
        <View
        style={{
            borderBottomColor: '#696b69',
            borderBottomWidth: 1,
         }}
        />
        <View>
        <Text style={styles.MenuText}> Menu </Text>
        <View style={styles.space} />
            <FlatList
            const data  = {[
                {key : 'BVN'},
                {key: 'Transfers'},
                {key: 'Bill Payments'},
                {key: 'Checkbook Requests'},
                {key: 'Airtime Purchase'},
                {key: 'Contact Us'},
            ]}
            renderItem={({ item }) => (
                <TouchableOpacity onPress={() =>this.onclick_item(item.key)} style={styles.button}>
            <View style ={styles.item}>
                <Text style = {styles.itemText} >{item.key}</Text>
            </View>
                </TouchableOpacity>
              )}
              numColumns = '2'
            />
        </View>
        <View style={styles.space} />
      </View>
    );
  }
}

const styles = StyleSheet.create({

    MenuText :{
        margin : 10,
        fontSize : 27,
        fontFamily : 'Verdana',
        fontWeight : 'bold',
        flexDirection : 'row'
    },

    welcomeText :{
        margin : 10,
        fontSize : 15,
        fontFamily : 'Verdana',
        fontWeight : 'bold',
        flexDirection : 'row'
    },

    space: {
        width: 10, 
        height: 10,
      },

    balanceText:{
        margin : 10,
        fontSize : 25,
        fontFamily : 'Verdana',
        fontWeight : 'bold'
    },
    accountNumText :{
        margin : 10,
        fontSize : 13,
        textAlign : 'right',
        fontFamily : 'Verdana',
        fontWeight : 'bold'
    },
    container:{
        flex :1,
        marginVertical :20
    },
    item : {
        backgroundColor : '#030303',
        borderRadius : 10,
        alignItems: 'center',
        justifyContent : 'center',
        flex : 1,
        margin : 1,
        height : Dimensions.get('window').width / 3
      },
      itemText:{
        color: '#fff'
      },
      button:{
        backgroundColor : '#030303',
        borderRadius : 35,
        alignItems: 'center',
        justifyContent : 'center',
        flex : 1,
        margin : 1,
        height : Dimensions.get('window').width / 3
      }

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...