How can I do an AJAX request with Typescript? (using JSON)

28,182

I think I have solved the problem, I'm sending the same data like I did before but now I use contentType: 'json' to tell the server that I'm sending a JSON and in the server side (PHP) I use the following to get the json: json_decode(file_get_contents('php://input'), true);

Main.ts

$(document).ready(function() {

    $( "a#boton_seleccion_dificultad" ).click(function(event) {

        event.preventDefault();

        if (pasapalabra.gameState == GameState.GAME_STARTING) {

            let _dificultad: Dificultad = new Dificultad("Normal");

            sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
                console.log(response);
            });

        }

    });
});

function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {

    var request = $.ajax({
        type: _type,
        url: BASE_URL + _url,
        data: _params,
        contentType: 'json'
    });
    request.done(function(res) {
        _callback(res);
    });
    request.fail(function(jqXHR, textStatus) {
        console.error(jqXHR);
        _callback({ err: true, message: "Request failed: " + textStatus });
    });

}

Welcome.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function __construct() {
    parent::__construct();
        $this->load->database();
        $this->load->library("grocery_CRUD");
        date_default_timezone_set('Europe/Madrid');
        $this->load->library('session');
        $this->load->helper('url');
        $this->load->model("Rol_model");
        $this->load->model("Questions_model");
    }

public function get_dificultad_seleccionada() {

        $data = json_decode(file_get_contents('php://input'), true);
        print_r($data);
        echo $data["_dificultad_seleccionada"];
    }

}

Now the server gets the value properly and I supose that now it's getting it in JSON format.

Share:
28,182
Ise92
Author by

Ise92

Updated on May 07, 2020

Comments

  • Ise92
    Ise92 almost 4 years

    I'm learning AJAX and I'm trying to do an AJAX request with parameters, but I'm having problems to send the JSON data:

    I'm using Typescript and PHP (with Codeigniter), the idea is to create a Typescript object and send it to the PHP in JSON format. So basically I create an object and use the stringify method that I find on Google to convert this object to JSON (or a string in form of JSON I should say?) and send it to the server with AJAX, but the data is not arriving properly.

    I used print_r($_POST); to see what is the server receiving and it shows to me the following:

    Array
    (
        [{"_dificultad_seleccionada":"Normal"}] => 
        [0] => 
    )
    

    The entire string that I get from stringify is shown as the key and the value is empty.

    I don't understand very well what is happening, isn't stringify the way to convert an object to JSON and send it to the server? Why it isn't sending the object properly?

    Client code:

    Dificultad.ts (class that I want to send to the server)

    class Dificultad {
    
        private _dificultad_seleccionada: string;
    
        constructor (dificultad_seleccionada: string) {
            this._dificultad_seleccionada = dificultad_seleccionada;
        }
    
        get dificultad_seleccionada(): string {
            return this._dificultad_seleccionada;
        }
    
        set dificultad_seleccionada(dificultad_seleccionada: string) {
            this._dificultad_seleccionada = dificultad_seleccionada;
        }
    
    }
    

    Lib.ts (where I declare all const, DOM elements, etc.)

    const BASE_URL: string = window.location.origin + "/Project_name/";
    type CallbackFunction = (arg: any, ...args: any[]) => void;
    

    Main.ts (here is where I send the AJAX)

        $(document).ready(function() {
    
            $( "a#boton_seleccion_dificultad" ).click(function(event) {
    
                event.preventDefault();
    
                if (pasapalabra.gameState == GameState.GAME_STARTING) {
    
                    let _dificultad: Dificultad = new Dificultad("Normal");
                    sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
                        console.log(response);
                    });
    
                }
    
            });
    
        });
    
    function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
    
        var request = $.ajax({
            type: _type,
            url: BASE_URL + _url,
            data: _params,
            contentType: 'json'
        });
        request.done(function(res) {
            _callback(res);
        });
        request.fail(function(jqXHR, textStatus) {
            console.error(jqXHR)
            _callback({ err: true, message: "Request failed: " + textStatus });
        });
    
    }
    

    Server code:

    Welcome.php

    class Welcome extends CI_Controller {
    
        public function __construct() {
        parent::__construct();
            $this->load->database();
            $this->load->library("grocery_CRUD");
            date_default_timezone_set('Europe/Madrid');
            $this->load->library('session');
            $this->load->helper('url');
            $this->load->model("Rol_model");
            $this->load->model("Questions_model");
        }
    
    public function get_dificultad_seleccionada() {
    
            print_r($_REQUEST); print_r($_POST);
            //echo json_encode($dificultad);
        }
    
    }
    

    It seems to be a problem with the object conversion that I do with stringify on the client because if I change the ajax call like this, sendind a JSON manually, it works:

    Main.ts

    sendAjaxRequest("POST", "get_dificultad_seleccionada", {"_dificultad_seleccionada":"Normal"}, function(response) {
                    console.log(response);
                });
    

    It seems that I'm doing something wrong but I have no idea of what could be, how can I send this object to the server in JSON format?

    I want to do an universal function for all AJAX request in my program, but I don't know very well if I'm doing it properly, is the type of the callback function ok? or am I wrong with this?

    Thank you very much for your help.

  • Kevin B
    Kevin B about 7 years
    well.. i mean... in this answer you're not sending json at all. just to be clear. you could remove JSON.parse(JSON.stringify and get the same result.
  • Ise92
    Ise92 about 7 years
    True, it still works without that... then why with stringify doesn't works? I'm using POST now and I writed contentType: 'json', but it still isn't working, now neither $_POST or $_REQUEST have anything, they both return: Array ( )