Ionic 4 POST to PHP backend












0















I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.



This is my function



test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = ;
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}


And this is an example function on the backend



else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}


So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.



Posting using POSTMAN with this



method=getThis&db=myDatabase


works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.










share|improve this question

























  • this.allData = "method=getThis&db=myDatabase" would be a quick but lazy way that would probably work.

    – John V.
    Nov 2 '18 at 6:31











  • @JohnV. hahahaha.. unfortunately it did not work..

    – Shadheeskumar Thinakaran
    Nov 2 '18 at 6:34











  • Oh, I misunderstood. It looks like the result will be an object with a "result" key and that will be an array. You should try this.allData = data.result

    – John V.
    Nov 2 '18 at 6:40
















0















I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.



This is my function



test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = ;
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}


And this is an example function on the backend



else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}


So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.



Posting using POSTMAN with this



method=getThis&db=myDatabase


works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.










share|improve this question

























  • this.allData = "method=getThis&db=myDatabase" would be a quick but lazy way that would probably work.

    – John V.
    Nov 2 '18 at 6:31











  • @JohnV. hahahaha.. unfortunately it did not work..

    – Shadheeskumar Thinakaran
    Nov 2 '18 at 6:34











  • Oh, I misunderstood. It looks like the result will be an object with a "result" key and that will be an array. You should try this.allData = data.result

    – John V.
    Nov 2 '18 at 6:40














0












0








0








I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.



This is my function



test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = ;
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}


And this is an example function on the backend



else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}


So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.



Posting using POSTMAN with this



method=getThis&db=myDatabase


works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.










share|improve this question
















I'm trying to POST data to a PHP backend and receive back the values and push it into an array. Hence, I created a function to do just that. However, I'm not to change the API on the backend (written in PHP). So I cannot change it to suit my normal methods of using POST.



This is my function



test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).subscribe(data => {
this.result = data; // get data in result variable
this.items = JSON.stringify(this.result); // then convert data to json string
// console.log(this.items);
this.allData = JSON.parse(this.items); // parse json data and pass json string
// console.log(this.allData.length); // got result of particular string
this.array = ;
for (var i = 0; i < this.allData.length; i++) {
this.array.push({
data1: this.allData[i].data1,
data2: this.allData[i].data2,
})
}
console.log(this.array[0])
})
}


And this is an example function on the backend



else if($_POST['method']=="getThis"){
global $conn;
mysqli_select_db($conn, $_POST['db']);
$name="";
$result=array();
$r=mysqli_query($conn,"select data1,data2 from table");
while ($rs = mysqli_fetch_array($r,MYSQLI_ASSOC)){
array_push($result,$rs);
}
echo json_encode(array("result"=>$result));
}


So how do I actually get it to post? I'm stuck here. I usually post with JSON and then decode the JSON on the backend. But this time around I'm not developing the backend and not changing it so gotta use the one provided.



Posting using POSTMAN with this



method=getThis&db=myDatabase


works well. Not sending JSON just a text. So how do I actually achieve this in Ionic.







php android angular typescript ionic-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 2 '18 at 6:47









Alex.K.

2,20192835




2,20192835










asked Nov 2 '18 at 5:49









Shadheeskumar ThinakaranShadheeskumar Thinakaran

32




32













  • this.allData = "method=getThis&db=myDatabase" would be a quick but lazy way that would probably work.

    – John V.
    Nov 2 '18 at 6:31











  • @JohnV. hahahaha.. unfortunately it did not work..

    – Shadheeskumar Thinakaran
    Nov 2 '18 at 6:34











  • Oh, I misunderstood. It looks like the result will be an object with a "result" key and that will be an array. You should try this.allData = data.result

    – John V.
    Nov 2 '18 at 6:40



















  • this.allData = "method=getThis&db=myDatabase" would be a quick but lazy way that would probably work.

    – John V.
    Nov 2 '18 at 6:31











  • @JohnV. hahahaha.. unfortunately it did not work..

    – Shadheeskumar Thinakaran
    Nov 2 '18 at 6:34











  • Oh, I misunderstood. It looks like the result will be an object with a "result" key and that will be an array. You should try this.allData = data.result

    – John V.
    Nov 2 '18 at 6:40

















this.allData = "method=getThis&db=myDatabase" would be a quick but lazy way that would probably work.

– John V.
Nov 2 '18 at 6:31





this.allData = "method=getThis&db=myDatabase" would be a quick but lazy way that would probably work.

– John V.
Nov 2 '18 at 6:31













@JohnV. hahahaha.. unfortunately it did not work..

– Shadheeskumar Thinakaran
Nov 2 '18 at 6:34





@JohnV. hahahaha.. unfortunately it did not work..

– Shadheeskumar Thinakaran
Nov 2 '18 at 6:34













Oh, I misunderstood. It looks like the result will be an object with a "result" key and that will be an array. You should try this.allData = data.result

– John V.
Nov 2 '18 at 6:40





Oh, I misunderstood. It looks like the result will be an object with a "result" key and that will be an array. You should try this.allData = data.result

– John V.
Nov 2 '18 at 6:40












3 Answers
3






active

oldest

votes


















0














You could try it that way. It works for me:



First import:



import { map } from "rxjs/operators/map";


Your function:



test() {
let data = "method=getThis" + "&db=myDatabase"
this.http.post("API URL", data).pipe(
map(res => res.json())
).subscribe(response => {
//Here your code
// 'response' is json
});
}





share|improve this answer
























  • res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

    – Shadheeskumar Thinakaran
    Nov 2 '18 at 6:29











  • I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

    – Jonathan
    Nov 2 '18 at 6:35



















0














Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
import { HttpHeaders } from '@angular/common/http';



const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/html'
})
};

this.http.post("API URL", data, httpOptions).subscribe()





share|improve this answer































    0














    PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.



    //demo.php
    <?php
    $data = ['message' => 'Hello world.'];
    header("Content-Type: application/json; charset=UTF-8");

    //If allow cross domain and not configration in Ngix/Apache
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");

    echo json_encode($data);


    And please try http access demo.php again.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53113272%2fionic-4-post-to-php-backend%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      You could try it that way. It works for me:



      First import:



      import { map } from "rxjs/operators/map";


      Your function:



      test() {
      let data = "method=getThis" + "&db=myDatabase"
      this.http.post("API URL", data).pipe(
      map(res => res.json())
      ).subscribe(response => {
      //Here your code
      // 'response' is json
      });
      }





      share|improve this answer
























      • res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

        – Shadheeskumar Thinakaran
        Nov 2 '18 at 6:29











      • I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

        – Jonathan
        Nov 2 '18 at 6:35
















      0














      You could try it that way. It works for me:



      First import:



      import { map } from "rxjs/operators/map";


      Your function:



      test() {
      let data = "method=getThis" + "&db=myDatabase"
      this.http.post("API URL", data).pipe(
      map(res => res.json())
      ).subscribe(response => {
      //Here your code
      // 'response' is json
      });
      }





      share|improve this answer
























      • res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

        – Shadheeskumar Thinakaran
        Nov 2 '18 at 6:29











      • I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

        – Jonathan
        Nov 2 '18 at 6:35














      0












      0








      0







      You could try it that way. It works for me:



      First import:



      import { map } from "rxjs/operators/map";


      Your function:



      test() {
      let data = "method=getThis" + "&db=myDatabase"
      this.http.post("API URL", data).pipe(
      map(res => res.json())
      ).subscribe(response => {
      //Here your code
      // 'response' is json
      });
      }





      share|improve this answer













      You could try it that way. It works for me:



      First import:



      import { map } from "rxjs/operators/map";


      Your function:



      test() {
      let data = "method=getThis" + "&db=myDatabase"
      this.http.post("API URL", data).pipe(
      map(res => res.json())
      ).subscribe(response => {
      //Here your code
      // 'response' is json
      });
      }






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 2 '18 at 6:25









      JonathanJonathan

      262




      262













      • res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

        – Shadheeskumar Thinakaran
        Nov 2 '18 at 6:29











      • I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

        – Jonathan
        Nov 2 '18 at 6:35



















      • res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

        – Shadheeskumar Thinakaran
        Nov 2 '18 at 6:29











      • I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

        – Jonathan
        Nov 2 '18 at 6:35

















      res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

      – Shadheeskumar Thinakaran
      Nov 2 '18 at 6:29





      res.json() will not work in ionic 3 and 4.. (as far i tried).. if im not mistaken its because it returns a json by default so no need to use res.json again.. anyways, what version of ionic are you running on??

      – Shadheeskumar Thinakaran
      Nov 2 '18 at 6:29













      I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

      – Jonathan
      Nov 2 '18 at 6:35





      I am using 4.1.1 and it works for me. Here a pice of code what is perfectly working in 4.1.1: ``` this.http.post("localhost:8080/sql/get", data).pipe( map(res => res.json()) ).subscribe(response => { console.log("GET DATA FROM SQL:"); console.log(response); console.log(response[4].Name); //this.loginField = response[4].Name; //this.passwordField = response[4].Password; }); ```

      – Jonathan
      Nov 2 '18 at 6:35













      0














      Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
      import { HttpHeaders } from '@angular/common/http';



      const httpOptions = {
      headers: new HttpHeaders({
      'Content-Type': 'text/html'
      })
      };

      this.http.post("API URL", data, httpOptions).subscribe()





      share|improve this answer




























        0














        Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
        import { HttpHeaders } from '@angular/common/http';



        const httpOptions = {
        headers: new HttpHeaders({
        'Content-Type': 'text/html'
        })
        };

        this.http.post("API URL", data, httpOptions).subscribe()





        share|improve this answer


























          0












          0








          0







          Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
          import { HttpHeaders } from '@angular/common/http';



          const httpOptions = {
          headers: new HttpHeaders({
          'Content-Type': 'text/html'
          })
          };

          this.http.post("API URL", data, httpOptions).subscribe()





          share|improve this answer













          Since the data you are sending is in plain text, you will need to add a header mentioning the content type.
          import { HttpHeaders } from '@angular/common/http';



          const httpOptions = {
          headers: new HttpHeaders({
          'Content-Type': 'text/html'
          })
          };

          this.http.post("API URL", data, httpOptions).subscribe()






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 2 '18 at 10:20









          Delwyn PintoDelwyn Pinto

          16219




          16219























              0














              PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.



              //demo.php
              <?php
              $data = ['message' => 'Hello world.'];
              header("Content-Type: application/json; charset=UTF-8");

              //If allow cross domain and not configration in Ngix/Apache
              header("Access-Control-Allow-Origin: *");
              header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
              header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");

              echo json_encode($data);


              And please try http access demo.php again.






              share|improve this answer




























                0














                PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.



                //demo.php
                <?php
                $data = ['message' => 'Hello world.'];
                header("Content-Type: application/json; charset=UTF-8");

                //If allow cross domain and not configration in Ngix/Apache
                header("Access-Control-Allow-Origin: *");
                header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
                header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");

                echo json_encode($data);


                And please try http access demo.php again.






                share|improve this answer


























                  0












                  0








                  0







                  PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.



                  //demo.php
                  <?php
                  $data = ['message' => 'Hello world.'];
                  header("Content-Type: application/json; charset=UTF-8");

                  //If allow cross domain and not configration in Ngix/Apache
                  header("Access-Control-Allow-Origin: *");
                  header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
                  header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");

                  echo json_encode($data);


                  And please try http access demo.php again.






                  share|improve this answer













                  PHP side should be return JSON and told browser content type is application/json, please test your code base on one simple page.



                  //demo.php
                  <?php
                  $data = ['message' => 'Hello world.'];
                  header("Content-Type: application/json; charset=UTF-8");

                  //If allow cross domain and not configration in Ngix/Apache
                  header("Access-Control-Allow-Origin: *");
                  header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");
                  header("Access-Control-Allow-Headers: Accept-Encoding, X-Requested-With, Content-Type, Origin, Accept, Authenticationtoken");

                  echo json_encode($data);


                  And please try http access demo.php again.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 14 '18 at 3:52









                  Nick WangNick Wang

                  49925




                  49925






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53113272%2fionic-4-post-to-php-backend%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Florida Star v. B. J. F.

                      Error while running script in elastic search , gateway timeout

                      Adding quotations to stringified JSON object values