send a JSON data object to the server using Javascript XMLHttpRequest?

56 Views Asked by At

Im conding in php and would like to send the information on the calender to the controller. I think my MVC is set up correctly and i get a status 200 that the data is sent as an object (see photo) but when i want to receive it in the controller i keep getting NULL. My project does not have a .htacess and uses a basic router. I run everthing form my docker container. The idea is click a tile and sent the object information to the controller so i can add it to a shoppingcart. Any help is appreciated

this is the code that i was trying in my javascript

document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.event').forEach(function(eventElement) {
    eventElement.addEventListener('click', function() {
        var eventDetails = {
            name: this.getAttribute('data-name'),
            startTime: this.getAttribute('data-start-time'),
            endTime: this.getAttribute('data-end-time')
        };
        // Send AJAX request to the server
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost/jazz');
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    console.log(eventDetails);
                    console.log('Request successful');
                } else {
                    console.error('Request failed');
                }
            }
        };
        xhr.send(JSON.stringify(eventDetails));
    });
  });
});

This is my controller where i want to receive the information but the vardump is empty and it does not go in the if-statement

OUTPUT - var_dump($requestData) = string(0) ""
OUTPUT - var_dump($_SERVER['REQUEST_METHOD']) = string(3) "GET"
OUTPUT - var_dump($selectedEventData) = NULL
OUTPUT - var_dump($_REQUEST) = array(4) { ["PHPSESSID"]=> string(32) 
"5c37a82703acc9f86f54c3817f08c4e9" ["pma_lang"]=> string(2) "nl" 
["phpMyAdmin"]=> string(32) "18b3f28efd9ffb94e2c3a28ae292819f" 
["pmaUser-1"]=> string(60)  
"JNBvWJn0SxdqeVHqQN1vIu7Hx4P9BdLusicXILkrWFCTKGhrT1VLLIUcFxw=" }

jazzcontroller.php:

    $requestData =  file_get_contents("php://input");
    var_dump($requestData);
 
    var_dump($_REQUEST);
    $selectedEventData = json_decode($requestData, true);
    var_dump($selectedEventData);
    if ($selectedEventData) {
        var_dump($selectedEventData);
        $selectedEventDetails = new EventMusic();
        $selectedEventDetails->getArtist()->setName($selectedEventData['name']);
        $selectedEventDetails->setStartTime($selectedEventData['startTime']);
        $selectedEventDetails->setEndTime($selectedEventData['endTime']);

this is my router <?php

namespace Routers;
use Exception;

class PatternRouter {

private function stripParameters($uri)
{
    if (str_contains($uri, '?')) {

        $uri = substr($uri, 0, strpos($uri, '?'));
    }
    return $uri;
}

public function route($uri)
{
    // Check if there's an api request
    $api = false;
    if (str_starts_with($uri, "api/")) {
        $uri = substr($uri, 4);
        $api = true;
    }

    //Check if there's an request to the CMS
    $cms = false;
    if (str_starts_with($uri, "cms/")) {
        $uri = substr($uri, 4);
        $cms = true;
    }

    // Set default controller & method
    $defaultcontroller = 'home';
    $defaultmethod = 'index';

    // Ignore query parameters
    $uri = $this->stripParameters($uri);

    // Read controller & method names from URI
    $explodedUri = explode('/', $uri);

    if (!isset($explodedUri[0]) || empty($explodedUri[0])) {
        $explodedUri[0] = $defaultcontroller;
    }
    $controllerName = $explodedUri[0] . "controller";

    if (!isset($explodedUri[1]) || empty($explodedUri[1])) {
        $explodedUri[1] = $defaultmethod;
    }
    $methodName = $explodedUri[1];

    // Require the file with the controller class
    $className = "Controllers\\" . $controllerName;

    if ($api) {
        $className = "ApiControllers\\" . $controllerName;
    }

    // Dynamically call controller & method
    try {
        $controllerObj = new $className;
        $controllerObj->{$methodName}();
    } catch (Exception $e) {
        http_response_code(404);
        // die();
    }
  }
}

Thanks again for all the feedback, I kept trying with no result e.g. changing the javascript code to send the data differently (without sending object) but no luck yet. I will keep trying

0

There are 0 best solutions below