Serialized form data via ajax only returns one letter ("r")

I have a form that I am submitting via ajax to a php function like so:

var formData = $(form).serialize();
    $.ajax({
        type : 'post',
        dataType : 'json',
        url : myAjax.ajaxurl, //we can use this value because in our php file we used wp_localize_script
        context:this,
        data : {action: 'tps_save_rental_details', formData:formData },
        success: function(response) {
            alert (response.testing);
        }
    });

I thought that by using .serialize() it would pass the form data in json form and then I could use it in my php function like so:

$formData = $_REQUEST['formData'];

$rentalType = $formData['rentalType'];

$result['testing'] = $rentalType;

(rental type is the name/id of the first text input field)

But when I alert the returned value of $results['testing'] in my ajax success function I just get one character, the letter "r" which doesn't even appear in the value of that field (which is "class-education").

Is this the best way to pass form input values via ajax? If so, what might I be doing wrong here.

Answers 1

  • The serialize method just takes the form elements and puts them in string form. "varname=val&var2=val2"

    You can get these values in php like:

    $params = array();
    parse_str($_GET, $params);
    

    Specific to the OP's case:

    $formData = array();
    parse_str($_REQUEST['formData'], $formData);
    $result['testing'] = $formData['rentalType'];
    

Related Articles