lillemap
lillemap

Reputation: 139

How to access array in PHP from Ajax call param?

I am making an Ajax call:

    $.ajax({
        url: "create_card.php",
        type: "GET",
        data: {deck: selection, data: $(input_form).serialize()}
    });

Initially, I was just using the array in the call, so I had data: $(input_form).serialize(), and I was using this code to get the data from the input form (card_info is an array of the named data in the input form):

    for($x = 0; $x < $array_length; $x++) {
        if(isset($_GET[$card_info[$x]])){
            $arg = $_GET[$card_info[$x]];
            $sql_query .= "\"" . $arg . "\"";
            if($x != $array_length - 1) {
                $sql_query .= ", ";
            } else {
                $sql_query .= ")";
            }
        }
    }

But now that I added the extra parameter to the Ajax call, I can't seem to access the data in the same way anymore. I've tried $_GET[data[$card_info[$x]]] but this did not work.

Upvotes: 0

Views: 35

Answers (1)

u_mulder
u_mulder

Reputation: 54831

$(input_form).serialize() serializes data from your form to a string, kinda inputName1=inputValue1&inputName2=inputValue2&inputName3=inputValue3 and etc.

Using

data: {deck: selection, data: $(input_form).serialize()}

means that you send to your server an object with two properties deck and data. On server this object will be converted to $_GET array with two keys: deck and data. And $_GET['data'] will hold a string with your previously serialized values.

If you use print_r($_GET) you will see, what I'm talking about.

So the solution is not to mix ways of sending data. Either you send a string, as @splash58 proposed:

// here you have a string
data: $(input_form).serialize() + '&deck=' + selection

Or an object:

// here you have an object
data: {deck: selection, field1: $("#someId").val(), field2: $("#yaId").val(), /* etc */ }

Where field1, field2 are keys and $("#someId").val(), $("#yaId").val() are methods which are used to get some values (in this case using ids).

Upvotes: 1

Related Questions