简体   繁体   中英

Unexpected token N in JSON at position 2

hi can you guys spot where the mistake is? as a beginner ionic dev I am always having a hard time with that sensitive JSON in my PHP file hope you guys takes time to answer this. as a beginner ionic dev I am always having a hard time with that sensitive JSON in my PHP file hope you guys takes time to answer this.

register.ts

import { Component, ViewChild } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { HomePage } from '../home/home';
import { Http, Headers, RequestOptions }  from "@angular/http";
import { LoadingController } from 'ionic-angular';
import 'rxjs/add/operator/map';

@Component({
  selector: 'page-register',
  templateUrl: 'register.html'
})
export class RegisterPage {


@ViewChild("email") email;
@ViewChild("username") username;
@ViewChild("mobile") mobile;
@ViewChild("userpass") userpass;


  constructor(public navCtrl: NavController, public alertCtrl: AlertController,  private http: Http,  public loading: LoadingController) {

  }

  Register(){
 //// check to confirm the username, email, telephone and userpass fields are filled

  if(this.username.value=="" ){

 let alert = this.alertCtrl.create({

 title:"ATTENTION",
 subTitle:"Username field is empty",
 buttons: ['OK']
 });

 alert.present();
  } else
 if(this.email.value==""){

 let alert = this.alertCtrl.create({

 title:"ATTENTION",
 subTitle:"Email field is empty",
 buttons: ['OK']
 });

 alert.present();

}
 else 
  if(this.mobile.value=="" ){

 let alert = this.alertCtrl.create({

 title:"ATTENTION",
 subTitle:"Mobile number field is empty",
 buttons: ['OK']
 });

 alert.present();
  } else
 if(this.userpass.value==""){

 let alert = this.alertCtrl.create({

 title:"ATTENTION",
 subTitle:"userpass field is empty",
 buttons: ['OK']
 });

 alert.present();

}
 else 
 {


var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.append('Content-Type', 'application/json' );
    let options = new RequestOptions({ headers: headers });

  let data = {
        username: this.username.value,
        userpass: this.userpass.value,
        mobile: this.mobile.value,
        email: this.email.value      
      };


 let loader = this.loading.create({
    content: 'Processing please wait...',
  });

 loader.present().then(() => {
this.http.post('http://localhost/mobile/register.php',data, options)
.map(res => res.json())
.subscribe(res => {

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

    alert.present();
 this.navCtrl.push(HomePage);

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

 alert.present();
  } 
});
});
 }

}
}

register.php

<?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);
    }

  require "dbconnect.php";

    $data = file_get_contents("php://input");
    if (isset($data)) {
        $request = json_decode($data);
        $username = $request->username;
        $userpass = $request->userpass;
        $mobile = $request->mobile;
        $email = $request->email;
    }

$username = stripslashes($username);
$userpass = stripslashes($userpass);
$userpass = sha1($userpass."@la]#}^(dy*%-Ga=/,Ga!.");

$sql = "INSERT INTO users (username,userpass,mobile,email)
        VALUES ('$username','$userpass','$mobile','$email')";

if ($con->query($sql) === TRUE) {
    echo "New account created successfully";
} 

else {
    echo "Error: " . $sql . "<br>" . $con->error;
}

    echo json_encode($data);

?>

在此处输入图像描述 在此处输入图像描述

Your problem is that everything that is output from your script ends up in your ajax response. Since you are trying to decode that as JSON , you need to ensure that it only contains that. So, rather than echoing a status message, include that in your JSON, with a success status or similar. Something like this:

if ($con->query($sql) === TRUE) {
    $status = "success";
    $message = "New account created successfully";
} 
else {
    $status = "error";
    $message =  "Error: " . $sql . "<br>" . $con->error;
}

echo json_encode(array('status' => $status, 'message' => $message, 'data' => $data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM