Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70432

Ionic HttpClient.post causes two entries into the database: null and correct data

$
0
0

@HippoRoo wrote:

I’m new to Ionic. I have an Ionic form that posts data to PHP.

Here is what my Ionic code looks like:

My event provider / service (event-service-rest.ts):

@Injectable()
export class EventService {

    constructor(public http: HttpClient) {}

    postAnEventRest(headers = null, params = null) {
        return this.http.post(eventApiURL, { headers, params });
    }
}

My event TypeScript class (create-event.ts):

export class CreateEventPage {

    public event = <any>{};

    constructor(public eventService: EventService) {}

    postAnEvent () {

        // temp set headers to null
        const headers = null
        const body = this.event;

        this.eventService.postAnEventRest(headers, body)
        .subscribe((data: any) => {
        this.event = data;
        },
        (error: any) => {
        console.log(error);
        });
    }
}

Here is what my PHP code looks like:

<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");

$jsonData = file_get_contents('php://input');
$data = json_decode($jsonData, true);
$event_title = $data['params']['event_title'];
$event_desc = $data['params']['event_desc'];

// Singleton Database Library - custom code for entering into database
$result = $db->insert('events', $event_title, $event_desc);
?>

The Ionic App either posts two posts into the PHP server or whatever it does, creates two database entries:

  1. Null
  2. $event_title and $event_desc is entered into the database

I tested my database class and it does not create two entries, so the issue is more likely caused by my Ionic code or the way my PHP code handles receiving the http post.

I looked at the Apache log file (pasted below) and there are two entries for each post: one as “OPTIONS” and one as “POST”. But I’m not sure if this Apache log explains the two entries into the database, but I thought I share it anyway.

192.168.1.2 - - [13/Jan/2018:13:21:27 -0800] "OPTIONS /events-json.php HTTP/1.1" 200 ...."
192.168.1.2 - - [13/Jan/2018:13:21:27 -0800] "POST /events-json.php HTTP/1.1" 200 - ..."

I appreciate any help:

  1. What I’m doing wrong that causes two database entries?
  2. Is this the correct way to structure and write Ionic code to post data (To create service / provider page that posts the data and do the subscribe in the TypeScript page)?

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70432

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>