I'm trying to add data to database with ajax, but this is my first try of ajax, that's why I can't solve this problem.
I have add() action which checks if form is sent. If it is, it adds a record to database.
public function add()
{
if ($this->request->is('ajax')) {
Configure::write('debug', 0);
}
$this->loadComponent('RequestHandler');
$this->loadModel('Galleries');
$entity = $this->Galleries->newEntity();
if ($this->request->is('post'))
{
/*$photos = $this->request->data['multiple_photos'];
for ($i = 0; $i < count($photos); $i++) {
$photo = [
'name' => $this->request->data['multiple_photos'][$i]['name'],
'type' => $this->request->data['multiple_photos'][$i]['type'],
'tmp_name' => $this->request->data['multiple_photos'][$i]['tmp_name'],
'error' => $this->request->data['multiple_photos'][$i]['error'],
'size' => $this->request->data['multiple_photos'][$i]['size']
];
echo "<pre>"; print_r($photo); echo "</pre>";
}*/
$data = [
'id' => '',
'thumb' => 'thuburl',
'highres' => 'highresurl',
'gal_id' => 1
];
$entity = $this->Galleries->patchEntity($entity, $data);
$this->Galleries->save($entity);
}
$this->set(compact('entity'));
$this->viewBuilder()->layout(false);
$this->render();
}
In my view:
<body>
<?php
echo $this->Form->create($entity, ['type' => 'file', 'id' => 'formUpload', 'action' => 'add']);
echo $this->Form->hidden('id', ['value' => '']);
echo $this->Form->input('multiple_photos[]', ['type' => 'file', 'multiple' => 'true', 'label' => false]);
echo $this->Form->hidden('thumb', ['value' => 'thumburl']);
echo $this->Form->hidden('highres', ['value' => 'highresurl']);
echo $this->Form->hidden('gal_id', ['value' => '1']);
echo $this->Form->button('Wyslij', ['type' => 'submit']);
echo $this->Form->end();
?>
<script>
$('#formUpload').submit(function() {
var formData = $(this).serialize();
var formUrl = $(this).attr('action');
$.ajax({
type: "POST",
url: formUrl,
data: formData,
success: function(data,textStatus,xhr) {
alert(data);
},
error: function(xhr,textStatus,error) {
alert(textStatus);
}
});
return false;
});
</script>
</body>
What's the result? It adds a record, so Ajax script works but I get "error" alert.
How to modify action or ajax script to get it working?
Thanks in advance :)