Gilbert Nwaiwu Gilbert Nwaiwu - 1 month ago 29
Ajax Question

PHP session not working in Aurelia

I'm using Aurelia with PHP as backend. Here is my view with its model:

home.html

<template>
<require from="datepicker.js"></require>
<form submit.delegate="submit()">
<input value.bind="name"></input>
<input value.bind="age"></input>
<button type="submit" name="submit">Submit
</button>
</form>
</template>


home.js

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';

@inject(HttpClient)
export class Home {
name;
age;

constructor(http) {
this.http = http;
}

submit() {
this.jsonobj = {
'name': this.name,
'age': this.age
};

if (this.jsonobj.name && this.jsonobj.age) {
this.http.fetch('dist/components/ses.php', {
method: 'post',
body: JSON.stringify(this.jsonobj)
})
.then(response => response.json())
.then(data =>
{
console.log(data);
});
}
}
}


And here is the PHP script:

ses.php

<?php
session_start();

$word = 'lol';
if(!isset($_SESSION['username'])){
$_SESSION['username'] = 'kil';
}

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

echo json_encode(array('item' => $_SESSION['username']));

?>


I expect that after the first call to the script, $_SESSION['username'] will be set to 'kil'. So on next ajax post !isset($_SESSION['username'] wont evaluate to true but it does which means PHP session isn't working.

Answer

By default fetch (the web standard that aurelia-fetch-client is built on) does not send cookies. You'll need to use credentials: 'include' in your request init object.

Two great resources for fetch:

The codez:

this.http.fetch('dist/components/ses.php', {
    credentials: 'include', // <-------------------------------------
    method: 'post',
    body: JSON.stringify(this.jsonobj)
  })