I want to pass form data from Ionic 3 to php file which is located on localhost. Below is my Ionic button code:
createEntry(name, description)
{
let body : string = "testname=" + name + "&testval=" + description,
type : string = "application/x-www-form-urlencoded; charset=UTF-8",
url : any = this.baseURI + "manage-data.php",
method : 'POST',
headers : any = new Headers({ 'Content-Type': 'application/json' }),
options : any = new RequestOptions({ headers: headers });
alert(url); //Output: http://localhost:1432/ionic-php-sql/manage-data.php
alert(body); //Output: name=Test&description=Test
alert(options); //[object Object]
console.log(options);
this.http
.post(url, body)
.subscribe(
data => {
console.log(data);
alert(data);
alert('success');
if(data.status === 200)
{
this.hideForm = true;
this.sendNotification(`Congratulations the technology: ${name} was successfully added`);
}
},
err => {
console.log("ERROR!: ", err);
alert(err);
}
);
}
This is my php file code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$con = mysqli_connect("localhost","root","","ionic_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "success !";
if($_SERVER['REQUEST_METHOD']=='post')
{
echo "posting";
$postdata = file_put_contents("php://input");
$request = json_decode($postdata);
var_dump($request);
$name = $_POST["testname"];
$desc = $_POST["testval"];
$sql = "INSERT INTO ionictest(testname, testval) VALUES ($name,$desc)";
$stmt = mysqli_query($con, $sql);
}
}
?>
Please check the code, and let me know in case of any mistakes. I want to pass data from Ionic to Php file then mysql database. I have successfully established connection between php and mysql database but I'm not able to pass data from Ionic form to php, though it is not showing any error. Thanks in Advance.