How to take string values by reference using PHP

Asked

Viewed 62 times

0

The way it is:

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

In PHP I can take the values by reference as follows:

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

When I try to do the same:

$.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 mistake:

Warning: Illegal string offset 'title' in

Second mistake:

Fatal error: Cannot create References to/from string offsets nor overloaded Objects in...

  • Is there a title key? Gave a print_r to be sure?

  • Yeah, sure. title=titulo&body=corpo @rray

  • The Form Data in the latter case it will be sent as: meus_dados:title=sr&body=teste, that is, in PHP will only be available $_POST['meus_dados'] which will be a string with the value title=sr&body=teste not an array as expected. Test in PHP print_r($_POST['meus_dados']).

  • Yes @Filipemoraes, but I need to take these values individually by reference.

  • pq needs to be by reference?

  • rray, because theoretically, only so that I am able to obtain the expected result.

Show 1 more comment

1 answer

2


Analyzing the following line:

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

The Form Data HTTP request will be sent as:

meus_data:title=sr&body=test

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

A solution will be to use the function return serializeArray 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 HTTP request will have the following format:

meus_data[title]:sr
meus_data[body]:test

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

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

Source (important also read comments): https://stackoverflow.com/a/1186309/3636960

Browser other questions tagged

You are not signed in. Login or sign up in order to post.