Search code examples
javascriptphpjsonstringifyvelo

JSON stringify creates underscore when there is a space or non-letter character, why?


Hello I have a function which is sending data using POST method to a server which then I use PHP to decode the JSON string. I am using for headers "Content-Type": "application/x-www-form-urlencoded" and for the body JSON.stringify

What I end up is this string:

[{"registration":true,"name":"dfsdf","last":"fsfs","email":"fdsfsd@gmail_com","phone":"fdsfds","city":"fsfsd","password":"password"}] =>

Then I use this code json_decode(key($_POST)) to decode the string and I end up with this:

stdClass Object
(
    [registration] => 1
    [name] => dfsdf
    [last] => fsfs
    [email] => fdsfsd@gmail_com
    [phone] => fdsfds
    [city] => fsfsd
    [password] => password
)

My problem is when there is a space or any other non-letter character like for example in this email address i got an underscore instead. I have send [email protected], but I end up getting fdsfsd@gmail_com. Do you know how to fix that? I am using Wix backed module to send the data by the way if this information is valuable. This is my full code:

import {fetch} from 'wix-fetch';

export function registration(name, last, email, phone, city, password) {
    return fetch("https://api.demo.com/auth.php", {
        "method": "post",
        "headers": {
            //   "Content-Type": "application/json"
            "Content-Type": "application/x-www-form-urlencoded"
        },
        "body": JSON.stringify({
            registration: true,
            name: name,
            last: last,
            email: email,
            phone: phone,
            city: city,
            password: password,
        }),
    }).then((response) => {
        if (response.ok) {
             return response.text();
            // return response.json();
        } else {
            return Promise.reject("Fetch did not succeed");
        }
    });
}

So far I have tried those things, but I always end up with an empty string:

  • change the Content-Type to application/json
  • remove JSON.stringify from body
  • remove JSON.stringify from body and add application/json

Solution

  • I finally manage to get it done. I had to use this php://input and it finally worked. This is the line of code I used:

    $data = json_decode(file_get_contents('php://input'), true);

    and this is the output

    Array
    (
      [registration] => 1
      [name] => dfsdf
      [last] => fsfs
      [email] => [email protected]
      [phone] => fdsfds
      [city] => fsfsd
      [password] => password
    )