SpartanA239
SpartanA239

Reputation: 1

How to properly use AJAX/JQuery/JSON with CakePHP 4?

I am beginning in AJAX and CakePHP 4, so any help would be grateful. For a project, I need to make a search system for my data (ingredients and recipes) and a hierarchy system. I must admit I am quite lost in all this, and don't really know how to do it and where to start.

Thanks !

Upvotes: 0

Views: 2068

Answers (1)

sanjay verma
sanjay verma

Reputation: 257

You can write your ajax code at bottom in view eg: templates/Folder-Name/YOUR-FILE.php Or you can include a js file and write code there (In this case you should create js file in webroot folder)

In templates folder: ajax code will be look like :

var path="<?php echo $this->Url->webroot ?>/Controller-Name/Method-Name";
$.ajax({
    type:"POST",
    url:path,
    data:{fname:'John',lname:'mac'},
    success:function(result){
       // on sucess whatever you want to do.
 
    }
 });

In controller you will have to define your method eg:

function MethodName(){
    $fname= $this->request->getData('fname');
    $lname= $this->request->getData('lname');
    .....
}

I hope this will work for you.

Upvotes: 1

Related Questions