A
A
Alexey2015-11-17 18:25:55
PHP
Alexey, 2015-11-17 18:25:55

Is it possible to send an array via serialize()?

I'm trying to send data from this form, but $post_data is always empty. Am I doing something wrong or is this not possible? And is it possible to send arrays (in this case step[]) in this way?

<form name="form_add">
<input type="text" name="step[]">
<input type="text" name="step[]">
<input type="text" name="step[]">
<button type="submit">Отправить</button>
</form>
<script>
  $('form').on('submit', function(event){
    event.preventDefault();
    var inputs = $(this).serialize();
    $.post('/upload.php',
    {post_data: inputs},
    function(d){
      console.log(d);
    })
  });
</script>


on the server I do this:
$post_data = unserialize($_POST['post_data']);
var_dump($post_data);

I get bool(false)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wol_fi, 2015-11-17
@dzheka3d

serlialize in jQuery returns the {input_name:input_value} object from the form passed to it. You don't need to do unserialize in php. Do a var_dump($_POST['post_data']);

N
newpy, 2015-11-18
@newpy

I will give an example, the form is submitted by clicking on the button Submit
Form:

<form id="form">
        <label>Name</label>
        <input type="text" name="name"/>
        <label>Age</label>
        <input type="text" name="age"/>
        <label>City</label>
        <input type="text" name="city"/>
        <button id="submit">Submit</button>
</form>
<pre id="debug">
      "This is test content. Learning AJAX."
</pre>

JavaScript
$('#submit').on('click', function(e) {
                e.preventDefault();
                $.ajax({
                    url: 'search.php',
                    type: 'POST',
                    dataType: 'json',
                    data: $('#form').serialize(),
                }).done(function (data) {
                    $('<h1>Ajax loaded</h1><div>' + data + '</div>').appendTo($('#debug'));
                });
            });

PHP:
$name = $_POST['name'];
$age = $_POST['age'];
$city = $_POST['city'];

$data = array('name' => $name, 'age' => $age, 'city' => $city);
echo json_encode($data);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question