Pass an Array using a POST using JavaScript or jQuery

0

I have a array that I want to pass mediante un POST (using $.post of jQuery ):

var linkNamesList = []; // A este array se le añaden elementos al usar la web

function sendData() {
    $.post('create_paste.php', {
        "linkNames": linkNamesList, //ESTE ES EL ARRAY, PERO PARECE QUE ASÍ DIRECTO NO FUNCIONA
        "name": title
    },function(data) {
        console.log('¡Hecho!', data);
    });
}

When the array is read in PHP, I get an empty variable . I would like to do it without PHP, because with PHP I already know that there is serialize , which will surely work.

    
asked by ByBrayanYT - Tops y más 11.12.2018 в 21:26
source

2 answers

3

When data is sent via a request POST , they have to be string for that you have to use JSON.stringify()

link

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var obj = [{ name: "Euler", age: 25, city: "Lima" },{ name: "Diego", age: 25, city: "Tarapoto" }];
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

what will be sent will be the following:

  

[{"name": "Euler", "age": 25, "city": "Lima"}, {"name": "Diego", "age": 25, "city": "Tarapoto" }]

for your case it would be like that the javascript

var linkNamesList = ["dato1", "dato2", "dato3","dato4"]; 

function sendData() {
    $.post('create_paste.php', {
        "linkNames": JSON.stringify(linkNamesList), 
        "name": title
    },function(data) {
        console.log('¡Hecho!', data);
    });
}

I hope you help, greetings.

    
answered by 12.12.2018 / 00:53
source
1

The problem is that you are not sending an array, in the jquery documentation link have this example:

$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );

and it is correct what you are doing however your array is empty (I do not know if you fill it at some other time), but you could try this:

var linkNamesList = ["nombre 1", "nombre 2", "nombre 3"]; // A este array se le añaden elementos al usar la web

function sendData() {
    $.post('create_paste.php', {
        "linkNames": linkNamesList, //ESTE ES EL ARRAY, PERO PARECE QUE ASÍ DIRECTO NO FUNCIONA
        "name": title
    },function(data) {
        console.log('¡Hecho!', data);
    });
}
    
answered by 11.12.2018 в 22:42