Send Array in an input as string for javascript php

Asked

Viewed 137 times

0

Hello!

I would like to place an array of objects inside an input and send to php using the Jquery mounted form

At the moment I’m testing like this:

My object

const myObject = [
   { id: 1, nome: 'Stackoverflow' },
   { id: 2, nome: 'Linux' },
   { id: 3, nome: 'Broffice' },
   { id: 4, nome: 'MS Office' },
  ]

What I’d like to put this myObject in an input:

I tried so:

  let myStrObj = JSON.stringify( myObject )
  let form =  $('<form action="backend.php" method="post">'+
                 '<input type="hidden" name="objecto" value="'+myStrObj+'">'+
                '</form>'
               )
  $('body').append( form )
  form.submit()

Only this way, in php arrives this way with the json_decode( $_POST['objecto'] ):

[{

That’s all

'Cause I want it that way?

Because it’s a processing I want what backend does and doesn’t need to return me, otherwise I would use it like this:

$.ajax({
   url: 'backend.php',
   type: 'post',
   ...
}) 

As I couldn’t do it the way above, I tried to do it the following way:

   let inputDados = ''
    $.each( myObject , ( i, j )=> {
        inputDados += `<input type="hidden" name="dados[${i}][id]" value="${j.id}">
        <input type="hidden" name="dados[${i}][nome]" value="${j.nome}">`
    })

And I put my form together like this:

      var form =  $('<form action="backend.php" method="post">'+
                       inputDados +
                    '</form>'
                   )
      $('body').append( form )
      form.submit()

And in php it comes like this:

array(
  0 => array(
       id => 1,
       nome => stackverflow
   ),
  1 => array(
       id => 2,
       nome => Linux
   ),
   2 => array(
       id => 3,
       nome => Broffice
   ),
   3 => array(
       id => 4,
       nome => MS Office
   )
)

There’s another better way?

1 answer

1


You can use the method JSON.stringify to serialize the JSON:

function generateInputHTMLWithJSON(inputName, data) {
  const input = document.createElement('input');
  input.type = 'hidden';
  input.name = inputName;

  // Serializa o JSON e o coloca na propriedade `value` do input:
  input.value = JSON.stringify(data);
  
  // Evita erros na serialização:
  return input.outerHTML;
}

console.log(
  generateInputHTMLWithJSON('data', [
    { username: 'Foo', age: 10 },
    { username: 'Bar', age: 20 },
    { username: 'Baz', age: 30 }
  ])
);

In the above example, the property Element.outerHTML was used to generate an HTML valid without risk of conflicts with JSON quotes, which will be properly escaped to &quot;.

And in PHP:

json_decode($_POST['data']);
  • So you practically have to have an input element created on the page itself and not in javascript?

  • In this case the input was created via Javascript.

  • Because you command him document.createElement which creates the element on the page, correct?

  • The document.createElement does not insert the element into the DOM unless you use something like the appendChild. In this case, it is as if the "input" is in memory. I only used the createElement to access the property outerHTML. :)

  • Very good! Thank you very much!

Browser other questions tagged

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