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'];
}
7
  • Are you sure it gives you a string with comma separated values, or is it more like ["value_1", "value_2", "value_3"]? Commented Jan 4, 2019 at 14:39
  • yeah I do var_dump($_SESSION['values']); and it returns C:\wamp64\www\<directory>\<file>:<line>:string 'value1,value2,value3,value4,value5 Commented Jan 4, 2019 at 14:43
  • You could stringify the array to a json string that you post to PHP, which you then decode in PHP. Commented Jan 4, 2019 at 14:43
  • 1
    Possible duplicate of Sending Arrays via Ajax/JSON without JQuery Commented Jan 4, 2019 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. Commented Jan 4, 2019 at 15:52

3 Answers 3

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'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I did this and just changed one line $_SESSION['values'] = json_decode($_POST['values']); and got the desired result
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'];
}

Comments

-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.

6 Comments

He doesn't use jQuery
"The better way is to use jQuery $.ajax()" - Why would including a 100kb bloated js library be a "better" way?
Why is this "better"? Include an external dependency when it's not in use anywhere else?
Hi thanks for your answer, I might come back to use jQuery.
@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).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.