Task: when i choose from select tag customer(i have customer_id), it's must get request into DB and return all customer field. And then it's must automatic fill some input's. I try to make ajax+jQuery. Ajax is good. It's working now!
Here's JS:
I figure this out:
<script>
$(document).ready(function() {
$('#customer_load').change(function() {
$.ajax({
url: '<?= $this->url(array('action' => 'ajax', 'controller' => 'baza')) ?>',
type: 'POST',
dataType: 'json',
data: {
// list of request parameters
'customer_id': $(this).attr('value')
},
success: function(data) {
//alert(data.current_discount);
$('#extra_discount').val(data.extra_discount);
$('#current_discount').val(data.current_discount);
$('#customer_number').val(data.customer_id);
}
});
});
});
PHP init:
$this->_helper->AjaxContext()->addActionContext('add', 'json')->initContext('json');
Ajax action:
$id= $this->_getParam('customer_id');
$result = $this->_customers->fetchSelected($id);
$this->view->customers = $result;
$this->_helper->json($result);
html:
<select name="customer_id" id="customer_load" style="width:300px;">
<option value="0">Выберите заказчика</option>
?php foreach ($this->customers as $cus): ?>
<option value="<?= $cus['customer_id'] ?>"" <?php if ($cus['customer_id'] == $this->form_data['customer_id']) echo "selected"; ?> ><?= $cus['lastname'] . " " . $cus['name'] ?></option>
<?php endforeach; ?>
<option value="new" onclick="NewCustomer()">Новый заказчик</option>
</select>
from your post it's hard to understand if the problem is on client or server side...
In your first example you are not using customer_id
in your ajax request and you do not need to cast the value to Number
in javascript.
Use AJAX Request Below:
$(document).ready(function(){
$.ajax({
url: <?= $this->url(array('action' => 'add', 'controller' => 'baza')) ?>,
type: 'POST',
dataType: 'json',
data: {
// list of request parameters
'customer_id': $('select[name=customer_id] option:selected').val(),
},
success: function(results){
// analyze your response and add custom logic
console.debug(result);
}
});
});
As per your PHP code, you are overcomplicating things.
Add your checks at the top of action and comment them out while you are trying to get it working (this way you can test baza/add
directly in browser), once you get it working uncomment and test. Use JSON view helper to output the json.
public function addAction()
{
// checks/validation/etc
// do some processing...
$result = $this->_customers->fetchSelected($id);
// Send the JSON response:
$this->_helper->json($result);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With