How to get, by reference, string values using PHP

0

The way it is:

var dados = $('#form').serialize(); // title=titulo&body=corpo
$.post("autosave.php", dados);

In PHP I get the values by reference as follows:

$title = &$_POST['title']; and $body= &$_POST['body'];

Now when I try to do the same for:

$.post("autosave.php", {'meus_dados': dados});

and in PHP:

$title = &$_POST['meus_dados']['title'];
$body  = &$_POST['meus_dados']['body'];

I get the following errors:

First error:

  

Warning: Illegal string offset 'title' in

Second error:

  

Fatal error: Can not create references to / from string offsets nor   overloaded objects in ...

    
asked by anonymous 31.01.2017 / 11:39

1 answer

2

Analyzing the following line:

$.post("autosave.php", {'meus_dados': dados});

The Form Data of the HTTP request will be sent like this:

  

my_dados: title = sr & body = test

In other words, in PHP only $_POST['meus_dados'] will be available which will be a string with title=sr&body=teste value and not an array as expected. Test in PHP print_r($_POST) and see the structure of the $_POST array.

One solution is to use the return of the serializeArray function to create a new object:

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Applying the solution:

var dados = $('#form').serializeObject();
$.post("autosave.php", {'meus_dados': dados});

So the Form Data of the HTTP request will have the following format:

  

my_dados [title]: sr
  my_dates [body]: test

In PHP the $_POST array will have the necessary indexes for your script to work:

$title = &$_POST['meus_dados']['title'];
$body  = &$_POST['meus_dados']['body'];

Source (important to read also the comments): link

    
31.01.2017 / 12:24