1

I'm new to cakephp. I'm trying to make a simple ajax request that would modify a part of the screen. I've found several examples on the web, but I can't mix them together! When I click the button btnNewPhon, I want to send the content of the input txtPhon to be sent to the controller adminController. Then in the view, the div dataToShow would be updated to show the data sent by the controller.

I'm almost there, but I don't know how to send the content of the inputs phonID and phonTxt to the controller and I don't know how to get the data in the controller. Here's my code.

View index.ctp:

<div id="dataToshow"></div>
<input id="phonID" type="text">
<input id="phonTxt" type="text">
<button id="btnNewPhon">New</button>

Ajax view ajax_response.ctp:

<?php echo $content; ?>

Javascript admin.js (included in the view):

$(function() {
  $('#btnNewPhon').click(function() {
    a = $("#txtPhon").val ;
    $.ajax({
      type:"POST",
      datatype:'json',
      cache: false,
      data: <<< I don't know what to put here >>>,
      url:"admin/addPhon",
      update:"#dataToshow"
    });
  });
});

Controller adminController.php:

public function addPhon() {

     if ($this->request->is('ajax')) {
        // Treatment of the new data here

        //create current date in chosen format
        $new_data = '##'.$this->request->param('phonID').'-'.$this->request->param('phonTxt').'##';

        //set current date as content to show in view
        $this->set('content', $new_data); 

        //render spacial view for ajax
        $this->render('ajax_response', 'ajax');

     }
}

Thanks!!!

1
  • You should also consider using the proper extension: `url:"admin/addPhon.json" Commented Mar 29, 2015 at 18:26

1 Answer 1

1

I got it.

1) In the view, I need to add a form around the fields and to set a name attribute to them, like:

<form id="goNewPhon">              
    <input id="phonID" name="phonID" type="text">
    <input id="phonTxt" name="phonTxt" type="text">
</form>

2) In the js, I serialize the form:

data: $("#goNewPhon").serialize(),

3) In the controller, I use data to get the passed parameters:

$this->request->data['phonTxt']

Now I works.

Sign up to request clarification or add additional context in comments.

1 Comment

It would be better to use the CakePHP internal FormHelper to generate forms. Then you wouldn't have run into this problem in the first place :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.