Submit Form Without page load using AJAX

I need help to submit form without loading page. and want to retrieve data into same page to replace that form


First you have to send the data to the server via javascript, for example using jQuery:

	url: $('your-form-id').attr('action'),
	type: 'POST',
	dataType: 'json',
	data: $('your-form-id').serialize(),
	beforeSend: function (xhr) {
		// Set the X-CSRF-Token header if the csrf is enabled in your Cake app. 
		// I'm using here the Cookies jquery plugin
		xhr.setRequestHeader('X-CSRF-Token', Cookies.get('csrfToken'));
	success: function (result, status, xhr) {
	    if (result.status == 200) {
	    	console.log('ok, you replace the form');
	    } else {
	        console.log('error, you show an error message');
	complete: function () {
	    // if you need it

Then in Cake you send back a serialized data in the controller:

publuc function yourControllerAction() {

  $this->request->allowMethod(['post', 'ajax']);

  $status = 403;
  $msg = null;
  $errors = false;

   your logic goes here

      'status' => $status,
      'message' => $msg,
      'errors' => $errors,
      '_serialize' => ['status', 'message', 'errors']