Convert json object to php array?

Asked

Viewed 193 times

-1

I’m trying to convert an object json in array, I have tried several ways using the json_decode()

function Save() {
    let post_id = document.getElementById('post_id');
    let pergunta = document.getElementById('pergunta');
    var dados = {
      post_id: post_id.value,
      pergunta:  pergunta.value

    };

    var data = JSON.stringify(dados);
    console.log(data);

    var ajax = new XMLHttpRequest();
    ajax.open('POST','index.php?class=PostForm&method=addFormPost', true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.onreadystatechange = () => {
      if (ajax.readyState === 4) {
         if (ajax.status === 200) {
             console.log(ajax.responseText);
         }
      }
    };

    ajax.send(data);
}

my function is executed in the action of click and I have the following output on file php

array(1) {
  ["{"post_id":"8","pergunta":"55555"}"]=>
  string(0) ""
}

What other way I could use to convert ?

  • opa beleza ? vc ja olhada na função JSON.parse() ? da uma olhada https://www.w3schools.com/js/js_json_parse.asp

1 answer

0

You are sending wrong information to the backend and so do not have the expected result, the correct is the following:

var dados = `post_id=${post_id}&pergunta=${pergunta}`;

why, you chose to send so with this setting:

ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

the final code:

function Save() {
    let post_id = document.getElementById('post_id');
    let pergunta = document.getElementById('pergunta');
    var dados = `post_id=${post_id}&pergunta=${pergunta}`;
    var data = JSON.stringify(dados);
    var ajax = new XMLHttpRequest();
    ajax.open('POST','source.php?class=PostForm&method=addFormPost', true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.onreadystatechange = () => {
      if (ajax.readyState === 4) {
         if (ajax.status === 200) {
             console.log(ajax.responseText);
         }
      }
    };
    ajax.send(dados);
}

your backend will return something like this in the format if you are basically with this code:

<?php
    
    echo json_encode($_POST);

on the return of Javascript:

{"post_id":"1","pergunta":"8"}

There is the fetch or jQuery.ajax which makes this type of operation much simpler, it is worth taking a look at.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.