Can't get a json response from Cakephp 3 controller - javascript

I am trying to send an ajax request to a Cakephp 3 controller.
The controller will find the data from the model and return it to the same view to be displayed,
The view and the js function are as follows
<script type = "text/javascript" language = "javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type : "POST",
url : "<?php echo $this->Url->build(['controller' => 'users', 'action' => 'getByCategories', '_ext' => 'json']); ?>",
success: function (data){
console.log(JSON.stringify(data));
}
});
});
});</script>
The above function is in the index view of the controller.
Upon the click of the button a request will be sent to the getByCategories function in the same controller.
The getByCategories function is as follows
public function getByCategories()
{
$id = 33;
$this->request->allowMethod(['ajax']);
$this->autoRender = false;
$cat = $this->Users->Categories->get($id);
if ($this->Users->Categories->childCount($cat) > 0)
{
$result = $this->Users->Categories->find('all', ['conditions' => ['parent_id' => $id]]);
$this->set(compact($result));
$this->set('_serialize', $result);
}
else
{
$result['Machines'] = $this->Users->Machines->find('all', ['conditions' => ['category_id' => $id]]);
$result['Medias'] = $this->Users->Medias->find('all', ['conditions' => ['category_id' => $id]]);
$this->set(compact($result));
$this->set('_serialize', $result);
}
}
The ajax response from this function is alway empty but the debugkit display the _serialize variable correctly.
I have enabled the json extensions in the routes.php file. the variable for the this call in the debugkit is as follows
debugkit varables
I would appreciated if someone can guide to get the variable from the debugkit in the ajax response
Thank you in advance

Looks like you're close, except for a misunderstanding of how _serialize (and maybe either set or compact) works. Check the manual for all the details, but what you should be setting in _serialize is either a list of names of variables, or else true to serialize everything.
Also, if you're using compact with set, you give it names of variables, not the variables themselves.
So, what you should be using there is probably:
$this->set(compact('result'));
$this->set('_serialize', ['result']);

Related

How to get one or two of data value in Controller Codeigniter when using AJAX Post

can someone help me with my code, i have AJAX json type POST and i wanto to get one or two of data send to controller in codeigniter, i wanto to add conditional function where the data from json.
My JSON
$('#add_people').submit(function(e){
e.preventDefault();
var id_people = $('#id_people').val();
var name_people = $('#name_people').val();
var phone_people = $('#phone_people').val();
$.ajax({
type : "POST",
url : "<?php echo base_url('add_people_data')?>",
dataType : "JSON",
data : {id_people:id_people , name_people:name_people, phone_people:phone_people},
success: function(data){
$("#show_people").html('<img src="assets/img/user/spinner.gif"> <h4>Loading data...</h4>');
$('#modal-add_people').modal('hide');
$('.modal-backdrop').remove();
$('[name="id_people"]').val("");
$('[name="name_people"]').val("");
$('[name="phone_people"]').val("");
var loadUrl = "<?php echo base_url('show-people-data')?>";
$("#show_people").load(loadUrl);
}
});
return false;
});
My Controler
public function add_people_data()
{
$id_people = $this->input->post('id_people');
$name_people = $this->input->post('name_people');
$phone_people = $this->input->post('phone_people');
$cekassignreviewer=$this->Model_reviewer->checkassignreviewer('data_people', $id_people, $name_people, $phone_people);
if ($cekassignreviewer > 0) {
$this->session->set_flashdata('failed',
"<script>swal({
title:'Failed!',
text: 'Number of people has been added',
icon: 'error',
confirmButtonText: 'Ok',
confirmButtonClass: 'btn btn-success'
});
</script>");
redirect(base_url('setting-reviewer'));
}else{
$data=$this->Model_reviewer->add_people();
echo json_encode($data);
}
My Model
function add_people()
{
$data = array(
'id_people' => $this->input->post('uniid_reviewer'),
'name_people' => $this->input->post('name_people'),
'phone_people' => $this->input->post('phone_people'),
);
$result=$this->db->insert('data_people',$data);
return $result;
}
Thank you in advance
IncomingRequest Class For CodeIgniter 4
If you are not within a controller, but still need access to the application’s Request object, you can get a copy of it through the Services class:
$request = \Config\Services::request();
With CodeIgniter’s built in methods you can simply do this:
$something = $request->getVar('foo');
The getVar() method will pull from $_REQUEST, so will return any data from $_GET, $_POST, or $_COOKIE. While this is convenient, you will often need to use a more specific method, like:
$request->getGet()
$request->getPost()
$request->getServer()
$request->getCookie()
In addition, there are a few utility methods for retrieving information from either $_GET or $_POST, while maintaining the ability to control the order you look for it:
$request->getPostGet() - checks $_POST first, then $_GET
$request->getGetPost() - checks $_GET first, then $_POST

CakePhp: Got erros in response body when calling an API with the CakePHP HttpClient

I'm having some HTML text in my response from an API.
Response I got
Preview's response
Here is my code (PHP):
public function getBeatmapInformations() {
$this->render(false);
if($this->request->is('get')){
$url = $_GET['beatmapUrl'];
$isOsuUrlBeatmap = "#^(?:https://)?osu\.ppy\.sh/(?:b|beatmapsets)/(\d*)#";
if(preg_match($isOsuUrlBeatmap, $url, $matches)){
$OSU_API_KEY = "MY_API_KEY";
$httpClient = new Client();
$response = $httpClient->get('https://osu.ppy.sh/api/get_beatmaps', [
's' => intval($matches[1]),
'k' => $OSU_API_KEY
]
);
$result = $response->body();
if(!empty($result)){
echo $result;
}
}
}
}
Javascript side (AJAX request):
function launchAjaxRequest(beatMapUrl) {
let url = beatMapUrl.replace(/['"]+/g, '');
$.get({
type : "GET",
url: '/ofv/getBeatmapInformations',
data: {
beatmapUrl : url,
},
success: function(data){
fillModesAvailablesForBeatmap(data);
}
});}
You should not manually echo anything in your controllers actions in CakePHP. The way to achieve json output in CakePHP is to use Data Views with Request Handler:
1.Enable Request Handler in your controller's initialize() method:
public function initialize(){
$this->loadComponent("RequestHandler");
}
2.In your action, set your data to be serialized:
$result = $response->body();
$this->set(compact("result"));
$this->set("_serialize", "result");
More about Request Handler and Data Views can be found in docs: JSON and XML views
As probably someone will point it out, you have also an alternative here: you can simply stop execution of script right after echoing data with die(). But it is not the Cake way of handling this.

Load php function in js file and use function

I have the following php function.
public function dateIndaysoff($mydate=false){
if(!$mydate)return false;
$host = "localhost";
$user = "user";
$pass = "pass";
$databaseName = "database";
$tableName = "table";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// $db=JFactory::getDbo();
$dbs->setQuery("select date from table WHERE `date`='$mydate'")->query();
return (int) $db->loadResult();
}
This function searches an input value inside a database table column and if it finds then we have a TRUE, else FALSE.
So, i have a jquery inside .js file where i execute a specific action and i want to check if i have a TRUE or FALSE result. In jquery i use a variable called val. So inside jquery in some place i want to have something like this:
if (dateIndaysoff(val)) {something}
Any ideas?
Instead of wrapping the php code in a function you can wrap it in a if($_POST['checkDate']){//your code here}, then in javascript make an ajax request (http://www.w3schools.com/ajax/), which sends a parameter named checkDate and in the success block of the ajax call you can have your code you represented as {something}
function checkDate(){
$.post('yourPhpFile.php', {checkDate:$dateToBeChecked}, function(data){
if(data){alert("true")};
});
};
and the php:
if($_POST['checkDate']){
//your current function, $_POST['checkDate'] is the parameter sent from js
}
Just to work with your current code.
In your php file lets say datasource.php
echo dateIndaysoff()
In your requesting file lets say index.php
$.ajax({
url: "index.php",
context: document.body
}).done(function( data ) {
/* do whatever you want here */
});
You can do it with AJaX. Something like this:
A PHP file with all the functions you are using (functions.php):
function test($data) {
// ...
}
A JS to request the data:
function getTest() {
$.ajax('getTestByAJaX.php', {
"data": {"param1": "test"},
"success": function(data, status, xhr) {
}
});
}
getTestByAJaX.php. A PHP that gets the AJaX call and executes the PHP function.
require 'functions.php';
if (isset($_REQUEST["param1"])) {
echo test($_REQUEST["param1"]);
}
Ok if i got this right i have to do this:
1st) Create a .php file where i will insert my php function and above the function i will put this:
$mydate = $_POST['val'];
where $mydate is the result of the function as you can see from my first post and val is the variable i want to put in $mydate from ajax.
2nd) I will go inside .js file. Now here is the problem. Here i have a code like this:
jQuery(".datepicker").change(function() {
var val = jQuery(this).datepicker().val();
console.log(val);
if (dateIndaysoff(val)) {
console.log("hide");
jQuery('.chzn-drop li:nth-child(9)').hide();
jQuery('.chzn-drop li:nth-child(10)').hide();
} else {
console.log("show");
jQuery('.chzn-drop li:nth-child(9)').show();
jQuery('.chzn-drop li:nth-child(10)').show();
}
});
Inside this code, in the first if, i want to see if the variable val is inside my database table. So, how could i write correctly this jQuery with the Ajax you propose in order for this to work? Also please take a look maybe i have a mistake in my php function (in this function i want to connect with a database and take a TRUE if $myvalue is inside a table column)

How to get data from AJAX in PHP without using a function

NOTE: No more down-votes please, just because you cannot answer the question/ or cannot understand the problem doesn't mean you have to down-vote. I clearly said I can provide more information/be more specific if you need me too.
Edited title for clarification
I am using javascript to validate the form client side, then using ajax to pass 3 arrays worth of data to a separate PHP page for processing. Just trying to perform a basic query with one of arrays before i begin.
the ajax request says it's working, and when I go into the network tab, then click response, it shows all the arrays with the correct values/indexes.
But on the PHP side nothing is happening. I have no idea how to debug the PHP because it's on a different page. I'm assuming this has something to do with my syntax, as I have got this too work before, but i used ajax in a function. I am very new to ajax, so I am not too sure if I am doing this correctly. I have tried a valid $wpdb query on the page and nothing is happening. How do i properly structure my PHP page to work with the ajax? Any way I can debug my PHP when ajax fires?
If you need additional information please let me know.
AJAX CALL:
$.ajax({
type: "POST",
url: "?page_id=251",
data: { vData: videoData, tsData: tsValues, dData: tsDescriptions},
success: function(){
$("#errorMessage").text("ajax success.");
}});
?page_id=251 (PHP page)
<?php
$videoData = $_POST['vData']; // i have also tried $_GET['vData'];
$vSRC = $videoData[0];$vTIT = $videoData[1];$vDES = $videoData[2];$vPDF = $videoData[3];$vDAT = $videoData[4];
$uID = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prefix."uservideo", array(
"user_id" => $uID,
"video_src" => $vSRC,
"video_title" => $vTIT,
"video_description" => $vDES,
"pdf_file" => $vPDF,
"video_date" => $vDAT
));
?>
I found the solution to the issue.
I needed to call a function with the ajax, cannot just call a page. I'm sure you can just call the page but no one knows how apparently.
AJAX
<script type="text/javascript">
function insert_data(vidData,timesData,descData){
$.ajax({
url: '?page_id=251',
type: 'POST',
data: {action: 'insert_video', vData: vidData, tsData: timesData, dData: descData },
dataType: 'json',
success: function(response){
alert('dhsdhjsdjhsjhdjhsd');
}
});
}
</script>
PHP
<?php
function insert_video($videoData,$tsValue,$tsDesc){
$videoData = $_POST['vData'];
$vSRC = $videoData[0];$vTIT = $videoData[1];$vDES = $videoData[2];$vPDF = $videoData[3];$vDAT = $videoData[4];
$tsValue = $_POST['tsData'];
$tsDesc = $_POST['dData'];
$uID = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prefix."uservideo", array(
"user_id" => $uID,
"video_src" => $vSRC,
"video_title" => $vTIT,
"video_description" => $vDES,
"pdf_file" => $vPDF,
"video_date" => $vDAT
));
}
echo insert_video($_POST['vData'], $_POST['tsData'], $_POST['dData']);
?>

JavaScript in CakePHP's controller

In my CakePHP view, I call method in controller, using jQuery:
function placeSensors(nk) {
$.ajax({
type:'post',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status = 'ok') {
}
}
});
}
JS in controller is defined with ie.:
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
var $components = array('RequestHandler'); // added later, but still the same
function index( $id = null, $value = null ) {
$code = '';
?>
<script type="text/javascript">
alert('Hello!');
</script>
<?php
return $code;
}
So, with simple code, I can not get alert message on my web form. Very simple code I was using in some other project and it works there, and for some reason this does not work on this one...
I'm really stuck with this one, can you please help me.....
UPDATE: this is response i'm getting by Firebug:
<script type="text/javascript">
alert('Hello!');
</script>
You're trying to place code that should be viewed (javascript) by the client, inside a controller. Controller is for business logic, that the client doesn't see.
Place your javascript inside a javascript file in the /webroot/js/ directory.
For interacting with ajax, tell your controllers to use the RequestHandler component to determine that they're being called by ajax. From there you can return simple values, or return a json or xml view.
If that sounds complicated, don't worry about it for now and just start as simple as you need and slowly build up your application.
function placeSensors(nk) {
$.ajax({
type:'post',
dataType:'json',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status) {
alert(r.code);
}
}
});
}
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
function index( $id = null, $value = null ) {
}
// update below code
function placeSensors( ) {
$nk = $_POST['nk'];
echo json_encode(array(
'status' => true,
'code' => "code"
));
exit();
}
Ok, i finally solved this one.
All I needed was to add one form and one text, or even better hidden element on form.
After that everything started to work.
So my mentioned code was ok, all I needed was that one text box......... Hope that somebody can tell me why?
Thank you on all your help and support.

Categories

Resources