Ajax answer goes wrong

Task: when I select the client select tag (I have client_id), it should receive a request in the database and return all the client fields. And then it should automatically fill in some data. I am trying to do ajax + jQuery. Ajax is good. He is working now!

Here's JS:

I understand it:

<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> 
+6
source share
1 answer

from your post it is difficult to understand if the problem is on the client or server side ... In the first example, you do not use customer_id in your ajax request, and you do not need to specify the Number value in javascript.

Use the 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); } }); }); 

According to your PHP code, you are excessive. Add your checks at the top of the action and comment on them while you try to make it work (this way you can test baza/add directly in the browser) as soon as you get work from it without checking and testing. Use the JSON view helper to output json.

  public function addAction() { // checks/validation/etc // do some processing... $result = $this->_customers->fetchSelected($id); // Send the JSON response: $this->_helper->json($result); } 
+1
source

All Articles