1

I want to pass an array from JS to PHP and then use it there, I gather the values in JS and send them to a fnother file where I try turn it into a $_SESSION variable but when I do a var_dump on this it gives me a string with comma seperated values. Is there a better way of doing this?

My JS:

var value_1 = document.getElementById("value_1").value;
var value_2 = document.getElementById("value_2").value;
var value_3 = document.getElementById("value_3").value;
var value_4 = document.getElementById("value_4").value;
var value_5 = document.getElementById("value_5").value;

var values = [];
values.push(value_1);
values.push(value_2);
values.push(value_3);
values.push(value_4);
values.push(value_5);

var formData = new FormData();
formData.append("values", values);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
        // success
    }
};
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.send(formData);

PHP:

if(isset($_POST['values'])){
    $_SESSION['values'] = $_POST['values'];
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Paddy Hallihan
  • 1,624
  • 3
  • 27
  • 76
  • Are you sure it gives you a string with comma separated values, or is it more like `["value_1", "value_2", "value_3"]`? – GrumpyCrouton Jan 04 '19 at 14:39
  • yeah I do `var_dump($_SESSION['values']);` and it returns `C:\wamp64\www\\::string 'value1,value2,value3,value4,value5` – Paddy Hallihan Jan 04 '19 at 14:43
  • You could stringify the array to a json string that you post to PHP, which you then decode in PHP. – M. Eriksson Jan 04 '19 at 14:43
  • Can anyone tell me what converts it to a string is it the JS sending it or is it setting it to a session? Like is it converted to a string already when the PHP file picks it up as a post? – Paddy Hallihan Jan 04 '19 at 14:46
  • 1
    Possible duplicate of [Sending Arrays via Ajax/JSON without JQuery](https://stackoverflow.com/questions/30143624/sending-arrays-via-ajax-json-without-jquery) – executable Jan 04 '19 at 14:47
  • 1
    @executable I don't get your flagging as a possible duplicate *and* an answer. I feel the flag should be removed. That isn't fair for others later who might want to post more answers. – Funk Forty Niner Jan 04 '19 at 15:52
  • Sorry, how can I remove it ? – executable Jan 04 '19 at 16:05

3 Answers3

1

You should convert your array into JSON, like :

var value_1 = document.getElementById("value_1").value;
var value_2 = document.getElementById("value_2").value;
var value_3 = document.getElementById("value_3").value;
var value_4 = document.getElementById("value_4").value;
var value_5 = document.getElementById("value_5").value;

var values = [];
values.push(value_1);
values.push(value_2);
values.push(value_3);
values.push(value_4);
values.push(value_5);

var json_upload = "values=" + JSON.stringify({values});
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "myfile.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

PHP

<?php
session_start();
if(isset($_POST['values'])){
    $_SESSION['values'] = $_POST['values'];
}
executable
  • 3,365
  • 6
  • 24
  • 52
0

Your problem with your original code was using an array as the value argument for FormData.append() (should be a string, which the JavaScript engine has type-cast your array to in your case).

If you instead append each value with the same key-name suffixed with an empty pair of square brackets (e.g. values[]), PHP will automatically form these into a numeric array for you.

JavaScript:

var formData = new FormData();
for(var i = 1; i <= 5; i++) {
    formData.append("values[]", document.getElementById("value_" + i).value);
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
        // success
    }
};
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.send(formData);

PHP:

<?php
session_start();
if(isset($_POST['values'])){
    $_SESSION['values'] = $_POST['values'];
}
Headbank
  • 361
  • 2
  • 6
-3

The better way is to use jQuery $.ajax() function:

_this.sendAjaxRequest = function(url, data, callback, errorCallback) {

    var _type = $.inArray($.type(data), ['string', 'object']) > -1 ? 'post' : 'get';

    var request  = $.ajax({
        'url'      : url,
        'type'     : _type,
        'dataType' : 'json',
        'data'     : data,
        'cache'    : false,
        'success'  : function(response) {
            if (typeof callback != 'undefined' && callback) {
                callback.call(_this, response);
                return;
            }
        },
        'error'    : function(response) {
            if (typeof errorCallback != 'undefined' && errorCallback) {
                errorCallback.call(_this, response);
                return;
            }
        }
    });
};

You could use JSON object as data variable.

Ivan Ovcharenko
  • 372
  • 4
  • 14
  • 3
    He doesn't use jQuery – executable Jan 04 '19 at 14:43
  • 1
    _"The better way is to use jQuery $.ajax()"_ - Why would including a 100kb bloated js library be a "better" way? – M. Eriksson Jan 04 '19 at 14:44
  • Why is this "better"? Include an external dependency when it's not in use anywhere else? – GrumpyCrouton Jan 04 '19 at 14:44
  • Hi thanks for your answer, I might come back to use jQuery. – Paddy Hallihan Jan 04 '19 at 14:45
  • 2
    @PaddyHallihan - If you want to learn proper development, I would stick to what you got now and sort the issues out instead. You don't want to be a "library"-developer (a developer that doesn't actually knows the language, but only a few libraries). There's nothing wrong with using tools and libraries, but including a 100kb lib just for this is overkill and bad for the end user (that needs to download all that extra bloat). – M. Eriksson Jan 04 '19 at 14:48
  • Better - because it saves time and makes code simple and you don't have to develop and support your own wrappers over XMLHttpRequest. For educational purposes - it is good to learn deeper, of course. – Ivan Ovcharenko Jan 04 '19 at 15:40