# How To make simple jQuery Ajax in cakephp 3.7

**URL:** <https://discourse.cakephp.org/t/how-to-make-simple-jquery-ajax-in-cakephp-3-7/5834>\
**Category:** Need Help\
**Created:** [March 22, 2019, 10:58am UTC](https://discourse.cakephp.org/t/how-to-make-simple-jquery-ajax-in-cakephp-3-7/5834 "2019-03-22T10:58:13Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 22, 2019, 4:32pm UTC](https://discourse.cakephp.org/t/how-to-make-simple-jquery-ajax-in-cakephp-3-7/5834/2 "2019-03-22T16:32:03Z")

</div>

well, you are trying to send a json string followed by another json string…

I’ve taken the liberty to clean up your code a bit so others can read it more easily 🙂

Your controller:

```php
public function index(){
  $country = $this->Countries->find('all')->extract('name');
  $this->set(compact('country'));
}

public function getStates(){
  $state = $this->States->find("all");//->extract('name');
    
  return $this->response
    ->withType('application/json')
    ->withStringBody(json_encode([
      'state' => $state,
      'result' => $result
    ]));
}

public function getCities(){
  $city = $this->Cities->find()->extract('name');
  return $this->response
    ->withType('application/json')
    ->withStringBody(json_encode([
      'state' => $state,
      'result' => $result
    ]));
}

```

The form:

```php
<?= $this->Form->control('country_name', [
  'options' => $country,	
  'empty' => 'Select Country',
  'id' => 'country'
]); ?>

```

Your JS code:

```auto
$(function(){
  $('#country').on('change', function() {
    var id = $(this).val();
    var targeturl = '<?= Router::url(["controller"=>"homes","action"=>"getStates"]); ?>';
    if(id == '-1'){
      $('#state').html(`<option value="-1">Select State</option>`);
    }else{
      $("#divLoading").addClass('show');
	    $('#state').html(`<option value="-1">Select State</option>`); 	
		  $.ajax({
              type:'post',
              url: targeturl,                  
			  data:'id='+id+'&type=state',
			  dataType: 'json',
			  success:function(result){
				  // $("#divLoading").removeClass('show');
				  // $('#state').append(result);
			  }
		  });	
	  }
	});
});

```

I don’t know whether using the `return $this->response` is the “proper” way to do it but it works for me (feel free to correct any mistakes I may have made)

---

_[View the full topic](https://discourse.cakephp.org/t/how-to-make-simple-jquery-ajax-in-cakephp-3-7/5834)._
