Shreyas Pednekar
Shreyas Pednekar

Reputation: 1305

How to pass form data from Ionic 3 to PHP file?

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.

Upvotes: 3

Views: 3039

Answers (2)

user8453321
user8453321

Reputation: 344

well for me the easiest way of which i tested on localhost and it works just fine is.... in php file:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
require_once "../vendor/autoload.php";
require_once "../config/config.php";
use \Firebase\JWT\JWT;

$content = array("name"=>"messi", "age"=>"32");
print json_encode($content);

and in ionic its best to create a serviceprovider to handle http requests here is the http request from ionic 3:

FunctionToHandleRequest(){

  let data=JSON.stringify(
    {
    email:this.email,
    password:this.password,
   }
  );
  console.log(data);
  this.http.post("http://localhost/RestLoginWithJwt/server/LoginAuthentication.php",
  data).map(res => res.json())
  .subscribe(data => {
   console.log(data.name);
});
  }

and like i said this was tested on localhost as you can see and it works just fine.

Upvotes: 1

Shreyas Pednekar
Shreyas Pednekar

Reputation: 1305

I resolved my query! Ionic button click code:

submitEntry(name, description)
{
    var link = this.baseURI + "manage-data.php";
    var body = JSON.stringify({testname: name, testval: description});

    alert("DATA: "+body);

    this.http.post(link, body)
    .subscribe(data => {
         console.log("DATA:", data);
         this.hideForm   = true;
         this.sendNotification(`Congratulations the technology: ${name} was successfully added`);
    },
         err => {
         console.log("ERROR!: ", err);
         alert(err);
    });
}

Php file code:

<?php
    if(isset($_SERVER['HTTP_ORIGIN']))
    {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    //Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 
    {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        exit(0);
    }

    $postdata = file_get_contents("php://input");
    if(isset($postdata))
    {
        $request = json_decode($postdata);
        $name = $request->testname;
        $desc = $request->testval;

        if($name != "" && $desc != "")
        {
            $con = mysqli_connect("localhost","root","","ionic_test");

            // Check connection
            if (mysqli_connect_errno())
            {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }
            else
            {
                echo "Name: " .$name;
                echo "Desc: " .$desc;

                $sql  = "INSERT INTO ionictest(testname, testval) VALUES ('$name', '$desc')";
                $stmt = mysqli_query($con, $sql) or die ("MySQL Error:".mysqli_error($con));

                echo "successfully inserted !";
            }
        }
        else 
        {
            echo "Empty name and description parameter!";
        }
    }
    else 
    {
        echo "Not called properly with name and description parameter!";
    }
 ?>   

You can refer the code if anyone wants... :)

Upvotes: 2

Related Questions