Skip to content

Instantly share code, notes, and snippets.

@MahbbRah
Last active January 9, 2020 09:30
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MahbbRah/be41920df6f208681c5951b16d732647 to your computer and use it in GitHub Desktop.
Save MahbbRah/be41920df6f208681c5951b16d732647 to your computer and use it in GitHub Desktop.
Making http POST/GET request from React-Native/React/Javascript side (Using Fetch API) to PHP server
// A function that sends http POST request to PHP server by using Javascript Fetch API with async/await :) 
async function POST(url, payload){

    var body = Object.keys(payload).map((key) => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(payload[key]);
    }).join('&');

    let options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        body
    };
    
    const response = await fetch(url, options);

    return await response.json();
}


// To use the above implementation follow below.
const getResponse = async() {

  // Payload example
  let payload = {
    username: 'username',
    password: 'SecretPasswordShouldUse'
  };
  
  let someUrlForPostRequest = 'http://yourdomainname.com/request_end_point';
  const sendPostRequest =  await POST(someUrlForPostRequest, payload);
  
  // sendPostRequest constant variable contains the response back from server :) Hopefully this helps you.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment