Ionic 2 http post request

Hi,

for me as beginner it was hard to figure out how to make a simple http post request with ionic 2. After many hours with Google and stack Overflow i get this “Basic” solution.

Basic, because there is no error handling at the Moment.

But it Shows how to bind a ion-input to a variable, send the http post, and work with the result.

Post Parameter is send as json and the result Comes back as json.
The echo.php file is the Server side. You can use the URL in the Code. The Service is running.

Hope this help to save time.

Hi Jacktoolsnet,
I am beginner in Ionic 2, I referred to your example for sending data using http post, but for my project following are the requirements.

  1. On my server side I am using FormParams i.e for accepting Form Data, so how to send “form data” but not json string using http post request in ionic 2 .

  2. I am sending multiple parameters to the server.

I found this page:


Looks like a good solution for your problem.

By the way, you can post more than one parameter like this:

getCityList(event_category_1, event_city, entry_date): Promise<string> {
return  this.http
.post(this.getCityList_Url, JSON.stringify({event_category_1: event_category_1, event_city: event_city, entry_date:  entry_date}), {headers: this.headers})
.toPromise()
.then(response => response.json() as any)
.catch(this.handleError);

}

I use a “proxy” on the server side to post the json to the api as normal Parameters. I do this because I want to change the path to my API later on the server not in the app.

PHP-Code:

<?php

/*
 * Collect all Details from Angular HTTP Request.
 */

include_once $_SERVER["DOCUMENT_ROOT"] . '/api/global/global.php';

header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

$event_category_1 = urlencode($request->event_category_1);
$event_city = urlencode($request->event_city);
$entry_date = urlencode($request->entry_date);

$url = WEB_SERVICE_URL . 'PROXYAPI/EVENTS/proxyGetCityList.php';
$myvars = "event_category_1=" . $event_category_1 . "&event_city=" . $event_city . "&entry_date=" . $entry_date;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);

if (strcmp($response, "") !== 0) {
	echo $response;
} else {
	echo '[{"event_city":"Serverfehler! Bitte versuchen Sie es später noch ein mal."}]';
}

Thanks for the help.