2

I have a project on Ionic 2 where I'm trying to send a value from my component file into my php, so I can use it for my sql query. I have my value as navParams, but I don't know how to send it to the php, neither how to receive it.

I have tried many ways, but so far I get Unexpected token in JSON position 0

component file :

import { Infoproducto } from './../infoproducto/infoproducto';
    import { ServiceProvider } from './../../providers/service/service';
    import {BarcodeScanner , BarcodeScannerOptions} from '@ionic-native/barcode-scanner';
    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';

    /**
     * Generated class for the Home2Page page.
     *
     * See http://ionicframework.com/docs/components/#navigation for more info
     * on Ionic pages and navigation.
     */
    @IonicPage()
    @Component({
      selector: 'page-home2',
      templateUrl: 'home2.html',
    })
    export class Home2Page {

    options: BarcodeScannerOptions;
        results:{};
        products2 : any[];
        cate : any[];
        id : any;



    constructor(private barcode : BarcodeScanner , public navParams: NavParams,public navCtrl: NavController, public service : ServiceProvider, public alertCtrl: AlertController) {
              this.id = navParams.get('gaming');
      }

      ionViewWillEnter(){
        this.getListarHome2();
        this.getListarCate();
      }

      getListarHome2(){
            this.service.ListarProdCate().subscribe(
              data => this.products2 = data,
              err => console.log(err)
            );      
          }

      getListarCate(){
            this.service.ListarCate().subscribe(
              data2 => this.cate = data2,
              err => console.log(err)
            );      
          }

      moverCategoria(gaming)
      {
        //this.id = { id : gaming.text};
        console.log(gaming);
        this.navCtrl.push(Home2Page,{"gaming": gaming});
      }
      async scanBarcode(){

        this.options = {
          prompt : 'Scanner barcode to see the result!.'
        }
         this.results = await this.barcode.scan(this.options);
        console.log(this.results);
      }

       loadinfoprod(){

           this.navCtrl.push(Infoproducto);

       }
    }

PHP file :

<?php

    header("Access-Control-Allow-Origin:http://localhost:8100");
    header("Content-Type: application/x-www-form-urlencoded");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

        $data = file_get_contents('php://input');
        $objData = json_decode($data);

        //$objData->gaming;


        $gaming = $objData->gaming;

     $datos;
     $resultados_finalees;

     @$db = mysqli_connect("localhost","root","","speedomart");

    if($db)
    {
            $query = "SELECT producto.codigo_barra, producto.nombre, producto.imagen, producto.precio FROM producto WHERE producto.idCategoria = 13"; 
            //$query = "SELECT producto.codigo_barra, producto.nombre, producto.imagen, producto.precio, stock_prod.ubicacion from producto JOIN stock_prod ON stock_prod.idSup = 1 ORDER BY RAND() LIMIT 0,2";
            $data=mysqli_query($db,$query);

            while($fila=mysqli_fetch_array($data))
            {
                $codigo = $fila[0];
                $nombre = $fila[1];
                $imagen = $fila[2];
                $precio = $fila[3];            


                $resultados_finalees[] = array("mensage"=>"algcorrecto","codigo"=>$codigo,"nombre"=>$nombre,"imagen"=>$imagen,"precio"=>$precio);

            }

              echo json_encode($resultados_finalees);


    }else
    {
        $resultados_finalees = array("mensage"=>"credenciales incorrectas");
        echo json_encode($resultados_finalees);
    };

    ?>

1 Answer 1

1

Use Angular's HTTP service to send Ajax request to the backend (eg. PHP, python, node.js...). And then you can obtain the request data from http GET params or http POST body.

It would be something like this:

import 'rxjs/add/operator/toPromise';
import { Http } from '@angular/http';

...

getHero(id: number): Promise<Hero> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.get(url)
    .toPromise()
    .then(response => response.json().data as Hero)
}

Maybe this tutorial can help you: doc.

Sign up to request clarification or add additional context in comments.

4 Comments

Where does that code go and how do I adapt it to mine?
You can just add inject Http service into your component, but a more elegant way is to handle http requests in your own services.
You'd better take a look at the tutorial... angular.io/tutorial
I'm having the same problem and your tutorial didn't help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.