Wednesday, January 17, 2018

React Native post request like a form submit

Leave a Comment

I am trying to achieve a similar thing in React Native any idea how can i do this

<form action="http://example.com/some-url-end-point" method="POST">   <input type="hidden" name="q" value="a"> </form> 

Is there a possibility to do something similar in React Native. I can do this in a web application. But in react native window.document doesn't exist. So I can't submit a form dynamically or in any way.

Basically what happens is I send some data to a 3rd party payment gateway with POST method data. Any idea how I can achieve this in React Native?

Edit: I need a solution that changes when submitted a web view opens up which changes the location of the browser, and sends data to that location in post method format

A similar question I found regarding this for Javascript implementation was this JavaScript post request like a form submit I need to achieve something similar in react native.

3 Answers

Answers 1

There is no equivalent in React Native to the html form.

All network requests are done with some networking library. React Native comes with fetch built in, but you can also use something like Axios, or even the XMLHttpRequest object itself.

See the Networking section in the React Native docs.

There are some libraries for the form UI, but they usually just provide you with the values in the form elements, which you then have to send on your own.

Answers 2

Since what you are trying to do is actually create a web form and redirect after that, why not create your form using HTML? You can do it using WebView. It's source prop accepts HTML directly or a remote source, and by doing so you can get the result you wish.

Answers 3

this is my solution for doing a 'POST'. I am new to react-native as well so feel free to give me some constructive criticism.

    var params   = {                         userName: 'BILLY BOB',         password: 'password',     };                  for (var k in params) {         var encodedKey = encodeURIComponent(k);         var encodedValue = encodeURIComponent(params[k]);         formBody.push(encodedKey + "=" + encodedValue);     }      formBody = formBody.join("&");       var request = {         method: 'POST',         'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',         'Another-Header' : 'any info i want to pass',         body: formBody     };   var URL_Register = 'http://myURL';        fetch(URL_Register, request)     .then(         function(response){             if(response.status != 200)             {                 return;             }             response.json()             .then(function(data) {                    //can access JSON data returned if any             }.bind(this));         }.bind(this)                 )     .catch(function(err){         console.log('Fetch Error', err);     })     }; 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment