LinCR
LinCR

Reputation: 401

Sending array as one variable from JavaScript to PHP

I have a form, and the URL is like this:

http://hostname/projectname/classname/methodname/variablename

And in my JavaScript, I fill an array like this:

var currentrelations = new Array();
    $(".ioAddRelation").each(function(index) {
        currentrelations[index] = $(this).html();
    });

And this array has two values ['eeeeee','eeeeee']

So the url is:

http://localhost/Mar7ba/InformationObject/addIO/eeeeee,eeeeee

And in my PHP, in the class InformationObject, on the method addIO:

public function addIO($currentRelations =null) {
        $name = $_POST['name'];
        $type = $_POST['type'];
        $concept = $_POST['concept'];
        $contents = $_POST['contents'];
        $this->model->addIO($name, $type, $concept, $contents);
        if (isset($_POST['otherIOs'])) {
            $otherIOs = $_POST['otherIOs'];
            $this->model->addOtherIOs($name, $otherIOs);
        }
        $NumArguments = func_num_args();
        if ($currentRelations!=null) {
            $IOs = $_POST['concetedIOs'];
            $this->model->setIoRelations($name,$IOs, $currentRelations);
        }
        exit;
        include_once 'Successful.php';
        $s = new Successful();
        $s->index("you add the io good");
}

But when I print the array $currentRelations using this statement:

echo count($currentRelations)

The results was 1 not 2, and when I print the first element using thie statement echo $currentRelations[0] I get e not eeeeee

why is that? What is the solution? What am I doing wrong?

Upvotes: 2

Views: 156

Answers (1)

rdleal
rdleal

Reputation: 1032

As I commented, the $currentRalations is a string, so using count on any type which is not an array or an object will return 1.
Also, note that when you do this $currentRelations[0] on a string, you are accessing a character in the zero-based index of the string. As strings are arrays of characters you can use the square array brackets to access specific chars within strings. This is why echo $currentRelations[0]; printed e in your code.

To split a string you should use the explode function like this:

$curRel = explode(',', $currentRelations);

and then see what you get

var_dump($curRel);

Hope it helps.

Upvotes: 2

Related Questions