Can not send data to PHP from jQuery

advertisements

I'm trying to post some data from a form into a controller with jQuery. But I'm having difficulties here.

I have a form with some inputs and a button calling my script.

The Button

  <button onclick="save('layoutstyle');">save</button>

And the script

function save(action) {

jQuery("#formTest").submit(function(e) {
    e.preventDefault();

    var $form = jQuery(this);

    var $inputs = $form.find("input, select, button, textarea");

    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);

    jQuery.ajax({
        type: 'POST',
        // TO DO
        url:  '/template/templates/nwmadm/controller.php',
        data: 'save='+ action+'&data='+ serializedData,
        dataType: 'html',
        success: function(data) {

            jQuery('#content').html(data);

        }
    });

})

}

And the controller in php looks like this

    if (isset($_POST["save"])) {
    switch ($_POST["save"]) {

        case "layoutstyle":
        $return = $_POST["data"];
        echo $return;
        break;

        case "surveys":
        echo "This is the Surveys site";
        break;

        default:
        echo "Return 404 page not found";

    }
}

But I'm only getting the first input through to the controller. And it is a string not an array.

What do I do? How do I get all the inputs from the form into my controller as an array?


In JQuery.ajax() you are using code:

data: 'save='+ action+'&data='+ serializedData,

serializedData is a string, which looks like this field1=val1&field2=val2. It means, that resulting data string will look such that:

save=layoutstyle&data=field1=val1&field2=val2

And it seems malformed. Instead, try to use this code

data: 'save=' + action + '&' + serializedData

In your PHP controller you must be able to access parameters of a request:

$action = $_POST["save"];
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];