0

I am trying to auto fill defaults on my invoices form with customer data based off the customer selected in the drop down. Once the customer is selected in this drop down in the photo below I want it to auto fill the addresses from the data found in the customer table in the next photo below also. enter image description here enter image description here

So far this is my invoices add.ctp script to try fetch the data. Currently with this script I can fetch the customer id that was selected to use in a sql query and also set data in the forms inputs

<script>

            document.getElementById('customers').addEventListener('change',function(){
               alert(this.value);
            $('#customers').click(function(){
                $.ajax({
                    type: "POST",
                    url: '<?php echo Router::url(array('controller' => 'Customers', 'action' => 'fill')); ?>',
                    success: function(data){
                        alert(data);
                    }
                });
            });

            document.getElementById('name').value = "test"
            document.getElementById('invoice_to_address').value = "test"

            });

        </script>

This is my fill function in my CustomersController. This is where I am going wrong I think my query is probably completely wrong and it's not searching for the right thing and returning it incorrectly and probably not even using the customer ID from the form. Currently it just returns no data but also has no errors and an empty alert box comes up due to the script in the view.

 public function fill()
{
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    $data = array();

    $id = $this->request->data();
    $query = $this->Customers->find()
    ->where([
    'id' => $id]);

$this->set(array(
    'id' => $query,
    '_serialize' => 'id'
    ));    


}

UPDATE

My full Invoices add.ctp

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<?php echo $this->Html->script('jquery.chained'); ?>
<script type="text/javascript">
    $(document).ready(function () {
        $("#contacts").chained("#customers");
    });
</script>
<?php use Cake\Routing\Router; ?>
<?php
/**
  * @var \App\View\AppView $this
  */
?>
<nav class="large-3 medium-4 columns" id="actions-sidebar">
    <ul class="side-nav">
        <li class="heading"><?= __('Actions') ?></li>
        <li><?= $this->Html->link(__('List Invoices'), ['action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('List Customers'), ['controller' => 'Customers', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Customer'), ['controller' => 'Customers', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Customer Contacts'), ['controller' => 'CustomerContacts', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Customer Contact'), ['controller' => 'CustomerContacts', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Aircraft Registrations'), ['controller' => 'AircraftRegistrations', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Aircraft Registration'), ['controller' => 'AircraftRegistrations', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Shipping Companies'), ['controller' => 'ShippingCompanies', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Shipping Company'), ['controller' => 'ShippingCompanies', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Job Types'), ['controller' => 'JobTypes', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Job Type'), ['controller' => 'JobTypes', 'action' => 'add']) ?></li>
        <li><?= $this->Html->link(__('List Currencies'), ['controller' => 'Currencies', 'action' => 'index']) ?></li>
        <li><?= $this->Html->link(__('New Currency'), ['controller' => 'Currencies', 'action' => 'add']) ?></li>
    </ul>
</nav>
<div class="invoices form large-9 medium-8 columns content">
    <?= $this->Form->create($invoice) ?>
    <fieldset>
        <legend><?= __('Add Invoice') ?></legend>
        <?php
            echo $this->Form->input('start_date', ['empty' => false]);
            echo $this->Form->input('close_date', ['empty' => true]);
            echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);
            echo $this->Form->input('name', ['type' => 'text', 'id'=>'name']);
            echo $this->Form->input('invoice_to_address', ['type' => 'text', 'id'=>'invoice_to_address']);
            echo $this->Form->input('ship_to_address');
            echo $this->Form->input('customer_contact_id', ['options' => $customerContacts, 'empty' => true,'id'=>'contacts']);
            echo $this->Form->input('currency_id', ['options' => $currencies, 'default'=> 1, 'id'=>'currencies']);
        ?>

    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
    <?= $this->Form->create(Null, ['type' => 'POST']) ?>
    <?= $this->Form->end() ?>
</div>

<script>
        jQuery('#name').autocomplete({source:'<?php echo Router::url(array('controller' => 'Customers', 'action' => 'search')); ?>'
        });
</script>

<script>
    document.getElementById('customers').addEventListener('change',function(){
       var id = this.value;
       alert(id);
        var csrfToken = $('[name=_csrfToken]').val();
        $.ajax({
            type: "POST",
            url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
            data: {'id' : id},
            beforeSend: function(xhr){
               xhr.setRequestHeader('X-CSRF-Token', csrfToken);
            },
            success: function(data){
                alert(data);
                data = JSON.parse(data);
                alert("id: " + data.id);
            }
        });
    document.getElementById('name').value = "test"
    document.getElementById('invoice_to_address').value = "test"
    document.getElementById('currencies').value = 3;
    });

</script>

and the controller fill function

public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);  
    }  
}

What happens when ($this->request->is('ajax')) is there. There's no response or preview. enter image description here

When if ($this->request->is('ajax')) is removed. enter image description here

Here is the full error message

{"id":0,"name":"Sky Works","country_id":1,"city_id":6,"address":"Sky works address in the customers table","postal_address":"Sky works shippng address in the customers table","phone":"","email":"","payment_terms_id":1,"stop_credit":false,"gst_percentage":null,"currency_id":"2","account_closed":false,"invoice_email":"","customer_notes":""}<pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-trace').style.display = (document.getElementById('cakeErr5a1140bb8332d-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (512)</a>: Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179 [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>48</b>]<div id="cakeErr5a1140bb8332d-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-code').style.display = (document.getElementById('cakeErr5a1140bb8332d-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8332d-context').style.display = (document.getElementById('cakeErr5a1140bb8332d-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb8332d-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$message&nbsp;</span><span style="color: #007700">=&nbsp;</span><span style="color: #DD0000">"Unable&nbsp;to&nbsp;emit&nbsp;headers.&nbsp;Headers&nbsp;sent&nbsp;in&nbsp;file=</span><span style="color: #0000BB">$file</span><span style="color: #DD0000">&nbsp;line=</span><span style="color: #0000BB">$line</span><span style="color: #DD0000">"</span><span style="color: #007700">;</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">if&nbsp;(</span><span style="color: #0000BB">Configure</span><span style="color: #007700">::</span><span style="color: #0000BB">read</span><span style="color: #007700">(</span><span style="color: #DD0000">'debug'</span><span style="color: #007700">))&nbsp;{</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;trigger_error</span><span style="color: #007700">(</span><span style="color: #0000BB">$message</span><span style="color: #007700">,&nbsp;</span><span style="color: #0000BB">E_USER_WARNING</span><span style="color: #007700">);</span></span></code></pre><pre id="cakeErr5a1140bb8332d-context" class="cake-context" style="display: none;">$response = object(Zend\Diactoros\Response) {
    [protected] headers =&gt; [
        &#039;Content-Type&#039; =&gt; [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames =&gt; [
        &#039;content-type&#039; =&gt; &#039;Content-Type&#039;
    ]
    [private] phrases =&gt; [
        (int) 100 =&gt; &#039;Continue&#039;,
        (int) 101 =&gt; &#039;Switching Protocols&#039;,
        (int) 102 =&gt; &#039;Processing&#039;,
        (int) 200 =&gt; &#039;OK&#039;,
        (int) 201 =&gt; &#039;Created&#039;,
        (int) 202 =&gt; &#039;Accepted&#039;,
        (int) 203 =&gt; &#039;Non-Authoritative Information&#039;,
        (int) 204 =&gt; &#039;No Content&#039;,
        (int) 205 =&gt; &#039;Reset Content&#039;,
        (int) 206 =&gt; &#039;Partial Content&#039;,
        (int) 207 =&gt; &#039;Multi-status&#039;,
        (int) 208 =&gt; &#039;Already Reported&#039;,
        (int) 226 =&gt; &#039;IM used&#039;,
        (int) 300 =&gt; &#039;Multiple Choices&#039;,
        (int) 301 =&gt; &#039;Moved Permanently&#039;,
        (int) 302 =&gt; &#039;Found&#039;,
        (int) 303 =&gt; &#039;See Other&#039;,
        (int) 304 =&gt; &#039;Not Modified&#039;,
        (int) 305 =&gt; &#039;Use Proxy&#039;,
        (int) 306 =&gt; &#039;Switch Proxy&#039;,
        (int) 307 =&gt; &#039;Temporary Redirect&#039;,
        (int) 308 =&gt; &#039;Permanent Redirect&#039;,
        (int) 400 =&gt; &#039;Bad Request&#039;,
        (int) 401 =&gt; &#039;Unauthorized&#039;,
        (int) 402 =&gt; &#039;Payment Required&#039;,
        (int) 403 =&gt; &#039;Forbidden&#039;,
        (int) 404 =&gt; &#039;Not Found&#039;,
        (int) 405 =&gt; &#039;Method Not Allowed&#039;,
        (int) 406 =&gt; &#039;Not Acceptable&#039;,
        (int) 407 =&gt; &#039;Proxy Authentication Required&#039;,
        (int) 408 =&gt; &#039;Request Time-out&#039;,
        (int) 409 =&gt; &#039;Conflict&#039;,
        (int) 410 =&gt; &#039;Gone&#039;,
        (int) 411 =&gt; &#039;Length Required&#039;,
        (int) 412 =&gt; &#039;Precondition Failed&#039;,
        (int) 413 =&gt; &#039;Request Entity Too Large&#039;,
        (int) 414 =&gt; &#039;Request-URI Too Large&#039;,
        (int) 415 =&gt; &#039;Unsupported Media Type&#039;,
        (int) 416 =&gt; &#039;Requested range not satisfiable&#039;,
        (int) 417 =&gt; &#039;Expectation Failed&#039;,
        (int) 418 =&gt; &#039;I&#039;m a teapot&#039;,
        (int) 421 =&gt; &#039;Misdirected Request&#039;,
        (int) 422 =&gt; &#039;Unprocessable Entity&#039;,
        (int) 423 =&gt; &#039;Locked&#039;,
        (int) 424 =&gt; &#039;Failed Dependency&#039;,
        (int) 425 =&gt; &#039;Unordered Collection&#039;,
        (int) 426 =&gt; &#039;Upgrade Required&#039;,
        (int) 428 =&gt; &#039;Precondition Required&#039;,
        (int) 429 =&gt; &#039;Too Many Requests&#039;,
        (int) 431 =&gt; &#039;Request Header Fields Too Large&#039;,
        (int) 444 =&gt; &#039;Connection Closed Without Response&#039;,
        (int) 451 =&gt; &#039;Unavailable For Legal Reasons&#039;,
        (int) 499 =&gt; &#039;Client Closed Request&#039;,
        (int) 500 =&gt; &#039;Internal Server Error&#039;,
        (int) 501 =&gt; &#039;Not Implemented&#039;,
        (int) 502 =&gt; &#039;Bad Gateway&#039;,
        (int) 503 =&gt; &#039;Service Unavailable&#039;,
        (int) 504 =&gt; &#039;Gateway Time-out&#039;,
        (int) 505 =&gt; &#039;HTTP Version not supported&#039;,
        (int) 506 =&gt; &#039;Variant Also Negotiates&#039;,
        (int) 507 =&gt; &#039;Insufficient Storage&#039;,
        (int) 508 =&gt; &#039;Loop Detected&#039;,
        (int) 510 =&gt; &#039;Not Extended&#039;,
        (int) 511 =&gt; &#039;Network Authentication Required&#039;,
        (int) 599 =&gt; &#039;Network Connect Timeout Error&#039;
    ]
    [private] reasonPhrase =&gt; &#039;&#039;
    [private] statusCode =&gt; (int) 200
    [private] protocol =&gt; &#039;1.1&#039;
    [private] stream =&gt; object(Zend\Diactoros\Stream) {}
}
$maxBufferLength = (int) 8192
$file = &#039;/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php&#039;
$line = (int) 179
$message = &#039;Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line=179&#039;</pre><pre class="stack-trace">Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 48
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37</pre></div></pre><pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8392c-trace').style.display = (document.getElementById('cakeErr5a1140bb8392c-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (2)</a>: Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>146</b>]<div id="cakeErr5a1140bb8392c-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8392c-code').style.display = (document.getElementById('cakeErr5a1140bb8392c-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb8392c-context').style.display = (document.getElementById('cakeErr5a1140bb8392c-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb8392c-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$response</span><span style="color: #007700">-&gt;</span><span style="color: #0000BB">getStatusCode</span><span style="color: #007700">(),</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">(</span><span style="color: #0000BB">$reasonPhrase&nbsp;</span><span style="color: #007700">?&nbsp;</span><span style="color: #DD0000">'&nbsp;'&nbsp;</span><span style="color: #007700">.&nbsp;</span><span style="color: #0000BB">$reasonPhrase&nbsp;</span><span style="color: #007700">:&nbsp;</span><span style="color: #DD0000">''</span><span style="color: #007700">)</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">));</span></span></code></pre><pre id="cakeErr5a1140bb8392c-context" class="cake-context" style="display: none;">$response = object(Zend\Diactoros\Response) {
    [protected] headers =&gt; [
        &#039;Content-Type&#039; =&gt; [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames =&gt; [
        &#039;content-type&#039; =&gt; &#039;Content-Type&#039;
    ]
    [private] phrases =&gt; [
        (int) 100 =&gt; &#039;Continue&#039;,
        (int) 101 =&gt; &#039;Switching Protocols&#039;,
        (int) 102 =&gt; &#039;Processing&#039;,
        (int) 200 =&gt; &#039;OK&#039;,
        (int) 201 =&gt; &#039;Created&#039;,
        (int) 202 =&gt; &#039;Accepted&#039;,
        (int) 203 =&gt; &#039;Non-Authoritative Information&#039;,
        (int) 204 =&gt; &#039;No Content&#039;,
        (int) 205 =&gt; &#039;Reset Content&#039;,
        (int) 206 =&gt; &#039;Partial Content&#039;,
        (int) 207 =&gt; &#039;Multi-status&#039;,
        (int) 208 =&gt; &#039;Already Reported&#039;,
        (int) 226 =&gt; &#039;IM used&#039;,
        (int) 300 =&gt; &#039;Multiple Choices&#039;,
        (int) 301 =&gt; &#039;Moved Permanently&#039;,
        (int) 302 =&gt; &#039;Found&#039;,
        (int) 303 =&gt; &#039;See Other&#039;,
        (int) 304 =&gt; &#039;Not Modified&#039;,
        (int) 305 =&gt; &#039;Use Proxy&#039;,
        (int) 306 =&gt; &#039;Switch Proxy&#039;,
        (int) 307 =&gt; &#039;Temporary Redirect&#039;,
        (int) 308 =&gt; &#039;Permanent Redirect&#039;,
        (int) 400 =&gt; &#039;Bad Request&#039;,
        (int) 401 =&gt; &#039;Unauthorized&#039;,
        (int) 402 =&gt; &#039;Payment Required&#039;,
        (int) 403 =&gt; &#039;Forbidden&#039;,
        (int) 404 =&gt; &#039;Not Found&#039;,
        (int) 405 =&gt; &#039;Method Not Allowed&#039;,
        (int) 406 =&gt; &#039;Not Acceptable&#039;,
        (int) 407 =&gt; &#039;Proxy Authentication Required&#039;,
        (int) 408 =&gt; &#039;Request Time-out&#039;,
        (int) 409 =&gt; &#039;Conflict&#039;,
        (int) 410 =&gt; &#039;Gone&#039;,
        (int) 411 =&gt; &#039;Length Required&#039;,
        (int) 412 =&gt; &#039;Precondition Failed&#039;,
        (int) 413 =&gt; &#039;Request Entity Too Large&#039;,
        (int) 414 =&gt; &#039;Request-URI Too Large&#039;,
        (int) 415 =&gt; &#039;Unsupported Media Type&#039;,
        (int) 416 =&gt; &#039;Requested range not satisfiable&#039;,
        (int) 417 =&gt; &#039;Expectation Failed&#039;,
        (int) 418 =&gt; &#039;I&#039;m a teapot&#039;,
        (int) 421 =&gt; &#039;Misdirected Request&#039;,
        (int) 422 =&gt; &#039;Unprocessable Entity&#039;,
        (int) 423 =&gt; &#039;Locked&#039;,
        (int) 424 =&gt; &#039;Failed Dependency&#039;,
        (int) 425 =&gt; &#039;Unordered Collection&#039;,
        (int) 426 =&gt; &#039;Upgrade Required&#039;,
        (int) 428 =&gt; &#039;Precondition Required&#039;,
        (int) 429 =&gt; &#039;Too Many Requests&#039;,
        (int) 431 =&gt; &#039;Request Header Fields Too Large&#039;,
        (int) 444 =&gt; &#039;Connection Closed Without Response&#039;,
        (int) 451 =&gt; &#039;Unavailable For Legal Reasons&#039;,
        (int) 499 =&gt; &#039;Client Closed Request&#039;,
        (int) 500 =&gt; &#039;Internal Server Error&#039;,
        (int) 501 =&gt; &#039;Not Implemented&#039;,
        (int) 502 =&gt; &#039;Bad Gateway&#039;,
        (int) 503 =&gt; &#039;Service Unavailable&#039;,
        (int) 504 =&gt; &#039;Gateway Time-out&#039;,
        (int) 505 =&gt; &#039;HTTP Version not supported&#039;,
        (int) 506 =&gt; &#039;Variant Also Negotiates&#039;,
        (int) 507 =&gt; &#039;Insufficient Storage&#039;,
        (int) 508 =&gt; &#039;Loop Detected&#039;,
        (int) 510 =&gt; &#039;Not Extended&#039;,
        (int) 511 =&gt; &#039;Network Authentication Required&#039;,
        (int) 599 =&gt; &#039;Network Connect Timeout Error&#039;
    ]
    [private] reasonPhrase =&gt; &#039;OK&#039;
    [private] statusCode =&gt; (int) 200
    [private] protocol =&gt; &#039;1.1&#039;
    [private] stream =&gt; object(Zend\Diactoros\Stream) {}
}
$reasonPhrase = &#039;OK&#039;</pre><pre class="stack-trace">header - [internal], line ??
Cake\Http\ResponseEmitter::emitStatusLine() - CORE/src/Http/ResponseEmitter.php, line 146
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 54
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37</pre></div></pre><pre class="cake-error"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb83ee9-trace').style.display = (document.getElementById('cakeErr5a1140bb83ee9-trace').style.display == 'none' ? '' : 'none');"><b>Warning</b> (2)</a>: Cannot modify header information - headers already sent by (output started at /home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php:179) [<b>CORE/src/Http/ResponseEmitter.php</b>, line <b>173</b>]<div id="cakeErr5a1140bb83ee9-trace" class="cake-stack-trace" style="display: none;"><a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb83ee9-code').style.display = (document.getElementById('cakeErr5a1140bb83ee9-code').style.display == 'none' ? '' : 'none')">Code</a> <a href="javascript:void(0);" onclick="document.getElementById('cakeErr5a1140bb83ee9-context').style.display = (document.getElementById('cakeErr5a1140bb83ee9-context').style.display == 'none' ? '' : 'none')">Context</a><pre id="cakeErr5a1140bb83ee9-code" class="cake-code-dump" style="display: none;"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$name</span><span style="color: #007700">,</span></span></code>
<span class="code-highlight"><code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$value</span></span></code></span>
<code><span style="color: #000000"><span style="color: #0000BB">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #007700">),&nbsp;</span><span style="color: #0000BB">$first</span><span style="color: #007700">);</span></span></code></pre><pre id="cakeErr5a1140bb83ee9-context" class="cake-context" style="display: none;">$response = object(Zend\Diactoros\Response) {
    [protected] headers =&gt; [
        &#039;Content-Type&#039; =&gt; [
            [maximum depth reached]
        ]
    ]
    [protected] headerNames =&gt; [
        &#039;content-type&#039; =&gt; &#039;Content-Type&#039;
    ]
    [private] phrases =&gt; [
        (int) 100 =&gt; &#039;Continue&#039;,
        (int) 101 =&gt; &#039;Switching Protocols&#039;,
        (int) 102 =&gt; &#039;Processing&#039;,
        (int) 200 =&gt; &#039;OK&#039;,
        (int) 201 =&gt; &#039;Created&#039;,
        (int) 202 =&gt; &#039;Accepted&#039;,
        (int) 203 =&gt; &#039;Non-Authoritative Information&#039;,
        (int) 204 =&gt; &#039;No Content&#039;,
        (int) 205 =&gt; &#039;Reset Content&#039;,
        (int) 206 =&gt; &#039;Partial Content&#039;,
        (int) 207 =&gt; &#039;Multi-status&#039;,
        (int) 208 =&gt; &#039;Already Reported&#039;,
        (int) 226 =&gt; &#039;IM used&#039;,
        (int) 300 =&gt; &#039;Multiple Choices&#039;,
        (int) 301 =&gt; &#039;Moved Permanently&#039;,
        (int) 302 =&gt; &#039;Found&#039;,
        (int) 303 =&gt; &#039;See Other&#039;,
        (int) 304 =&gt; &#039;Not Modified&#039;,
        (int) 305 =&gt; &#039;Use Proxy&#039;,
        (int) 306 =&gt; &#039;Switch Proxy&#039;,
        (int) 307 =&gt; &#039;Temporary Redirect&#039;,
        (int) 308 =&gt; &#039;Permanent Redirect&#039;,
        (int) 400 =&gt; &#039;Bad Request&#039;,
        (int) 401 =&gt; &#039;Unauthorized&#039;,
        (int) 402 =&gt; &#039;Payment Required&#039;,
        (int) 403 =&gt; &#039;Forbidden&#039;,
        (int) 404 =&gt; &#039;Not Found&#039;,
        (int) 405 =&gt; &#039;Method Not Allowed&#039;,
        (int) 406 =&gt; &#039;Not Acceptable&#039;,
        (int) 407 =&gt; &#039;Proxy Authentication Required&#039;,
        (int) 408 =&gt; &#039;Request Time-out&#039;,
        (int) 409 =&gt; &#039;Conflict&#039;,
        (int) 410 =&gt; &#039;Gone&#039;,
        (int) 411 =&gt; &#039;Length Required&#039;,
        (int) 412 =&gt; &#039;Precondition Failed&#039;,
        (int) 413 =&gt; &#039;Request Entity Too Large&#039;,
        (int) 414 =&gt; &#039;Request-URI Too Large&#039;,
        (int) 415 =&gt; &#039;Unsupported Media Type&#039;,
        (int) 416 =&gt; &#039;Requested range not satisfiable&#039;,
        (int) 417 =&gt; &#039;Expectation Failed&#039;,
        (int) 418 =&gt; &#039;I&#039;m a teapot&#039;,
        (int) 421 =&gt; &#039;Misdirected Request&#039;,
        (int) 422 =&gt; &#039;Unprocessable Entity&#039;,
        (int) 423 =&gt; &#039;Locked&#039;,
        (int) 424 =&gt; &#039;Failed Dependency&#039;,
        (int) 425 =&gt; &#039;Unordered Collection&#039;,
        (int) 426 =&gt; &#039;Upgrade Required&#039;,
        (int) 428 =&gt; &#039;Precondition Required&#039;,
        (int) 429 =&gt; &#039;Too Many Requests&#039;,
        (int) 431 =&gt; &#039;Request Header Fields Too Large&#039;,
        (int) 444 =&gt; &#039;Connection Closed Without Response&#039;,
        (int) 451 =&gt; &#039;Unavailable For Legal Reasons&#039;,
        (int) 499 =&gt; &#039;Client Closed Request&#039;,
        (int) 500 =&gt; &#039;Internal Server Error&#039;,
        (int) 501 =&gt; &#039;Not Implemented&#039;,
        (int) 502 =&gt; &#039;Bad Gateway&#039;,
        (int) 503 =&gt; &#039;Service Unavailable&#039;,
        (int) 504 =&gt; &#039;Gateway Time-out&#039;,
        (int) 505 =&gt; &#039;HTTP Version not supported&#039;,
        (int) 506 =&gt; &#039;Variant Also Negotiates&#039;,
        (int) 507 =&gt; &#039;Insufficient Storage&#039;,
        (int) 508 =&gt; &#039;Loop Detected&#039;,
        (int) 510 =&gt; &#039;Not Extended&#039;,
        (int) 511 =&gt; &#039;Network Authentication Required&#039;,
        (int) 599 =&gt; &#039;Network Connect Timeout Error&#039;
    ]
    [private] reasonPhrase =&gt; &#039;OK&#039;
    [private] statusCode =&gt; (int) 200
    [private] protocol =&gt; &#039;1.1&#039;
    [private] stream =&gt; object(Zend\Diactoros\Stream) {}
}
$name = &#039;Content-Type&#039;
$values = [
    (int) 0 =&gt; &#039;text/html; charset=UTF-8&#039;
]
$first = true
$value = &#039;text/html; charset=UTF-8&#039;</pre><pre class="stack-trace">header - [internal], line ??
Cake\Http\ResponseEmitter::emitHeaders() - CORE/src/Http/ResponseEmitter.php, line 173
Cake\Http\ResponseEmitter::emit() - CORE/src/Http/ResponseEmitter.php, line 55
Cake\Http\Server::emit() - CORE/src/Http/Server.php, line 116
[main] - ROOT/webroot/index.php, line 37</pre></div></pre>
mark.nz
  • 127
  • 1
  • 14

2 Answers2

0

Change:

$query = $this->Customers->find()->where(['id' => $id]); 

To:

$query = $this->Customers->find()->where(['id' => $id])->first();

Also use "echo" in the controller to return the data to ajax.

echo json_encode($query);

Then json encoded data should be returned.

Edit:
Make sure you have created a form (to get csrf token) like this in the ctp file:

<?= $this->Form->create(Null, ['type' => 'POST']) ?>
<?= $this->Form->end() ?>

And add these lines to the javascript code:

beforeSend: function(xhr){
    xhr.setRequestHeader('X-CSRF-Token', csrfToken);
},

And add "data" to javascript, like:

var id = 1; //Your ID. I don't know what ID it is, so I just use 1. 
var csrfToken = $('[name=_csrfToken]').val(); //Sorry, I forgot this.
$.ajax({
    type: "POST",
    url: '<?php echo Router::url(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    beforeSend: function(xhr){
       xhr.setRequestHeader('X-CSRF-Token', csrfToken);
    },
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});

And change the controller:

public function fill(){
    $layout = 'ajax'; // you need to have a no html page, only the data.
    $this->autoRender = false; // no need to render the page, just plain data.
    if ($this->request->is('ajax')) {
        $id = $this->request->data['id'];
        $query = $this->Customers->find()
        ->where([
           'id' => $id
        ])->first();
        echo json_encode($query);  
    }  
}

Edit:
Maybe you are not using CsrfToken. In that case, you don't need to load CsrfToken. Change the javascript code like this:

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous">
  //jQuery CDN. If you have loaded jQuery somewhere else, you don't need this.  
</script> 
<script>
var id = 1; //Your ID. I don't know what ID it is, so I just use 1. 
$.ajax({
    type: "POST",
    url: '<?= $this->Url->build(array("controller" => "Customers", "action" => "fill")); ?>',
    data: {'id' : id},
    success: function(data){
        alert(data);
        data = JSON.parse(data);
        alert("id: " + data.id);
    }
});
</script>

With this javascript, I think you don't have to change the controller (you don't need to remove is('ajax').)

Edit
Maybe as you say, null is returned from the controller. But I want to check what the error message is. Please check it by the following way.

If succeeded, you get json string. You can change it to javascript's object after receiving it. enter image description here

If failed, you can check it from the google chrome browser. It should show what error you get: enter image description here

Or, maybe cakephp might return error message in html. In that case, you would receive this: enter image description here

This is raw html code, so it might be hard to read.

Please let me know what error message you get..

lechat
  • 390
  • 2
  • 15
  • That seems like it did something but now I get the error Cannot convert value to integer. I don't think I'm getting the data correctly in the controller I tried to do echo $id; and along with some error messages it has $id = []. – mark.nz Nov 18 '17 at 05:46
  • In the fill() function, you are sure $id = $this->request->data(); has any value? – lechat Nov 18 '17 at 05:54
  • I'm not sure from my test it looked like it didn't but I'm not sure how to get the id I get in the view into the controller to use in the sql query. – mark.nz Nov 18 '17 at 07:44
  • I updated the code. I don't have cakephp3's environment right now, so I didn't test the code if it works, but it should work theoretically. Can you check if it works? – lechat Nov 18 '17 at 11:43
  • I made some changes I changed xhr.setRequestHeader('X-CSRF-Token', csrfToken); to xhr.setRequestHeader('X-CSRF-Token', = json_encode($this->request->param('_csrfToken')); ?>); because it said csrfToken undefined also for some reason the if ($this->request->is('ajax')) in the controller is stopping the request completely so I removed it and it seems to get the correct data but also the error Unable to emit headers when I comment out echo json_encode($query); in the controller it got rid of the error but also returned no data. – mark.nz Nov 18 '17 at 20:27
  • Hi Mark. I updated the code and I tested it with the latest cakephp3. It should work now. Maybe you are not using CsrfToken (This is used for secirity reasons, to prevent cross site request forgery). If you are not using CsrfToken, you don't need to load CsrfToken. If you want to use CsrfToken, please refer to the other one. – lechat Nov 19 '17 at 03:41
  • I don't think i'm using Csrftoken because I tried to implement that version and it broke the date inputs on my form. I tried to impletement the other version but it seems the JSON.parse(data) throws the error uncaught SyntaxError: Unexpected end of JSON input. I think this is because the if ($this->request->is('ajax')) is still always false so it's still returning nothing or null. Also yes I have already loaded jquery because jquery autocomplete is working on another input field. I will edit my question to show what my code is like now. – mark.nz Nov 19 '17 at 05:51
  • Without if ($this->request->is('ajax')), is it working? You can check if error message is returned from the server by: (Use google chrome >) open the input page > press F12 on keyboard > Click "Network" from the upper menu > Update the page > You find a red section if there is error. Click the red section. > You can see error message. – lechat Nov 19 '17 at 07:26
  • The first alert returns the array with the unable to emit headers error but the JSON.parse(data); still creates the same error message. Maybe because the previous error i'll post a screenshot of the first error. By the way just want to say thanks for all the time you've spent helping so far! – mark.nz Nov 19 '17 at 07:45
  • Oh you are always welcome. :) And my guess is you are actually using csrftoken. Can you try the csrf one to see if it works? – lechat Nov 19 '17 at 08:10
  • Alright just updated the code to use the csrf token and edited my question to show the code from the error messages. – mark.nz Nov 19 '17 at 08:36
0

This is Lechien.

It seems like the error message is: Unable to emit headers. Headers sent in file=/home/southpac/southpacificavionics.com/team/src/Controller/CustomersController.php line 179.

From the error message, I doubt BOM is added to any of your PHP files. Please see here about the problem: How to fix "Headers already sent" error in PHP
Sometimes Windows default text editor add BOM automatically to the file.

Can you check if there is BOM in controller file and templates (ctp files) of Customers? If you find BOM is added, remove the BOM. Then the code that I provided should work.

lechat
  • 390
  • 2
  • 15
  • Hi Lechien, it doesn't seem BOM is added I checked with notepad++ and made sure they were converted to UTF-8 (no BOM) and reuploaded them to the server. I added my full invoices add.ctp file to the question if that helps. – mark.nz Nov 19 '17 at 20:53
  • Oh ok. Is it possible to send ajax from other ctp files to other controller? You can copy and paste the method to other ctp file & controller and see if it works. If it works, it's a problem of file itself. Also, see here too: https://stackoverflow.com/questions/6756621/cakephp-cannot-modify-header-information-headers-already-sent-by – lechat Nov 19 '17 at 23:38
  • Tried it in a new ctp with just the one dropbox and new controller but still get unable to emit headers. Also it's strange because I have jquery autocomplete working. – mark.nz Nov 20 '17 at 00:40
  • Can you try without-csrf token one? – lechat Nov 20 '17 at 00:49
  • Yeah I just did but the same result sadly. – mark.nz Nov 20 '17 at 00:55
  • "echo" to return the json string can be the problem. Can you try if $this->set works? If this doesn't work, I have no idea.. Sorry :( – lechat Nov 20 '17 at 01:05
  • That's okay thanks so much for the help it helped make some progress. When I use Set it just has no response. I'll keep trying and searching and get back to you if I solve it. Thanks! – mark.nz Nov 20 '17 at 01:33
  • Are you using IDE like Netbeans or Visual Studio Code? With IDE, it is easier to hunt down a bug because you can use breakpoints to stop the execution. – lechat Nov 20 '17 at 02:21
  • No i've just been editing through the text editor on the live server I'll have a look at netbeans – mark.nz Nov 20 '17 at 02:30
  • Hi @lechien I asked around and managed to find an answer your solution was very close it just needed headers: { Accept: "application/json" }, added to the scrip in the view and also exit(); added after echo json_encode() in the controller. Thanks again for all your help! – mark.nz Nov 20 '17 at 21:09