Answer the question
In order to leave comments, you need to log in
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>
$post_data = unserialize($_POST['post_data']);
var_dump($post_data);
Answer the question
In order to leave comments, you need to log in
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']);
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>
$('#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'));
});
});
$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 questionAsk a Question
731 491 924 answers to any question