Digipng Digipng - 3 months ago 10
Ajax Question

How to send data using ajax in cakephp3?

I working cakephp3. I have two dropdown select. The first menu list values is displayed with the loading page and then The second menu list values will be filled with the user's choice from the first menu. I do this with ajax but I don't how to send/get data to/from ajax.

In view (addroom.ctp) :

<form method="post" action="#" name="setRoom">
<?php
echo '<select name = "dorm" id="dorm" >';
foreach ($row as $a) {

echo '<option>' . "$a" . '</option>';
}
echo '</select>';

?>

</form>


In ajax.js in webroot:

$(document).ready(function () {
$('#dorm').change(function () {
var dorm = $('#dorm').val();
if (dorm == '') {
$('#roomm').html("choose dormitory!");
}
$.ajax({
url: "addroom.ctp",
type: 'POST',
data: dorm,
success: function (data) {
alert("ok");
}
});
});

}


In Controller:

class UesrmoreinfoesController extends AppController {

public function addroom() {
$gender = $this->request->Session()->read('Auth.User.gender');
$url = $this->params['url'];
$dorm = $url['dorm'];
$this->typeDormitory($gender);
$this->numberRooms($dorm);
}

}


The function
typeDormitory($gender)
returns
$row
in the first menu list and
numberRooms($dorm)
returns
$rooms
in the second menu list.

The first menu data are displayed correctly.
How to get value from the first dropdown and post for ajax?

Answer
  1. Create form with form helper
  2. Change url: "addroom.ctp" to url: $("form").attr("action");
Comments