0

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.

lillemap
  • 139
  • 2
  • 12

1 Answers1

1

$(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).

u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Came here to say the same. I set up a fiddle: https://jsfiddle.net/84kfnn1c/. If you check out the network panel in the dev tools you can see what parameters are sent which would help debugging. You can look into serializeArray for the form which would give an array of objects like so: https://api.jquery.com/serializeArray/. I like to add something like this plugin so I can get the object in a format that is easier to work with in PHP: http://stackoverflow.com/questions/8900587/jquery-serializeobject-is-not-a-function-only-in-firefox. In either case, you can add the deck data to what you send. – Pango Mar 14 '17 at 18:34