Ionic 3 php MySQL insert query executing twice

I am working on a mobile app in ionic 3 to scan QR Code for a specific cause and store it into database. The API for storing it into mysql database is written in php. it is working fine on web but when it comes to mobile, insert query is executing twice and giving me the output as duplicate key. Please help me to get through

import { TabsPage } from './../tabs/tabs';
import { AlertController } from 'ionic-angular';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { DataServiceProvider } from '../../providers/data-service/data-service';
import { RequestOptions, Headers, Http } from '@angular/http';

/**
 * Generated class for the ScanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

// @IonicPage()
@Component({
  selector: 'page-scan',
  templateUrl: 'scan.html',
})
export class ScanPage {
  data : any;
  response: Object;
  username: any;

  constructor(public navCtrl: NavController,
    private barcodeScanner: BarcodeScanner,
    private http: Http,
    private alertCtrl: AlertController,
    public navParams: NavParams

 ) {

  }
  ionViewWillEnter()
  {
  }


  scan() {

  const data = JSON.parse(localStorage.getItem('userData'));
  this.username = data.username;
   console.log(data);
      console.log(this.username);
    console.log(this.username);
    alert(this.username);
   var headers = new Headers();
       headers.append("Accept", 'application/json');
       headers.append('Content-Type', 'application/json');

  let options = new RequestOptions({
   headers: headers
 });


   this.barcodeScanner.scan().then((barcodeData) => {
    // alert(barcodeData);
     this.data = barcodeData.text;
     alert(this.data);
     this.http.get("https://192.168.161.31/qrcode/check_data_mobile.php?insecure=cool&username="+this.username+"&data="+this.data, options)
     .map(res => res.json())
     .subscribe(res => {
        alert(res);
        if(res == "New Data") {

          let alert = this.alertCtrl.create({
            title: "CONGRATS",
            subTitle: (res),
            buttons: ['OK']
          });

          alert.present();
         }
         else if(res == "Duplicate Data") {
           let alert = this.alertCtrl.create({
             title: "Duplicate",
             subTitle: (res),
             buttons: ['OK']
           });

           alert.present();
         }
         else if(res == "No data posted") {
           let alert = this.alertCtrl.create({
             title: "data not posted",
             subTitle: (res),
             buttons: ['OK']
           });

           alert.present();
         }


         else {
           let alert = this.alertCtrl.create({
             title: "No DATA",
             subTitle: (res),
             buttons: ['OK']
           });

           alert.present();
         }

       },
       err=>{
         // let alert = this.alertCtrl.create({
         //   title: "ERROR",
         //   subTitle: (err),
         //   buttons: ['OK']
         // });

          alert("error is : "+err);
          //this.navCtrl.push(TabsPage);

       });
     // },
     //  (err)=> {
     //   alert(err);
     // }
 });

  }
}

There are a lot of problems here with code structure and needless junk. I would suggest reading the Tour of Heroes HttpClient chapter carefully and following its idioms instead of whatever old rando tutorial gave you all this res.json() and pre-pipeable operator map and unnecessary headers. It’s really hard to read and follow code that nests futures like this, as well. Break these tasks into discrete functions that do one thing instead of having a big monolith.

Probably the most important problem, however, has nothing to do with Ionic. GET requests in RESTful APIs must not modify any state on the server, and as a result they may be issued multiple times without ill effect. Change this endpoint to POST instead and put all the information in the body of the request, not the URI.

After these refactorings, see if you’re still getting duplicate requests. Look in the server logs to see if two POSTs are hitting the server or not. That will tell you whether your problem is in the client or the server. If the problem persists, post your new code and we’ll keep working on it.

1 Like

Thanks for you suggestion… I will try as you said and inform here again

Good advice on checking the logs.

For me it was the OPTIONS request in that Angular does with HTTP GET requests that was sending it twice.

Handling the preflight to just process the authentication and exiting after prevented double triggering of the PHP service.