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?
So you practically have to have an input element created on the page itself and not in javascript?
– adventistaam
In this case the input was created via Javascript.
– Luiz Felipe
Because you command him
document.createElement
which creates the element on the page, correct?– adventistaam
The
document.createElement
does not insert the element into the DOM unless you use something like theappendChild
. In this case, it is as if the "input" is in memory. I only used thecreateElement
to access the propertyouterHTML
. :)– Luiz Felipe
Very good! Thank you very much!
– adventistaam