I'm trying to send a ajax requistion to a controller, that it should returns something, but isn't.
My element (View/Elements/list.ctp):
<script type="text/javascript">
$(document).ready(function(){
$('#click').click(function(){
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>',
success: function(data){
alert(data);
}
});
});
});
</script>
<p id="click">Click me!</p>
Controller products:
<?php
class ProductsController extends AppController {
public $helpers = array('Js' => array('Jquery'));
public $components = array('RequestHandler');
var $name = 'Products';
function showProducts(){
return 'This should to return in jQuery data';
}
}
?>
In cakePHP 2.x your controller needs to be in this way to return json data to the $.ajax request :
<?php
App::uses('AppController', 'Controller');
App::uses('JsBaseEngineHelper', 'View/Helper');
class AjaxtestsController extends AppController {
function beforeFilter() {
parent::beforeFilter();
}
public function returnsSomthing()
{
$layout = 'ajax'; // you need to have a no html page, only the data.
$this->autoRender = false; // no need to render the page, just plain data.
$data = array();
$jquerycallback = $_POST["callback"];
//do something and then put in $data those things you want to return.
//$data will be transformed to JSON or what you configure on the dataType.
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($data).',"ajt":','postfix' => '});'));
}
}
Improved Answer
You can use your controller's methods to search data on the db: find(), but I move the search queries to the Model:
First: Add the marked lines at the model code
App::uses('AppModel', 'Model');
App::uses('Sanitize', 'Utility'); // <---
App::uses('JsBaseEngineHelper', 'View/Helper'); // <---
Second: Create a Model method that executes the search:
public function getdata(){
$input = NULL;
$query = array();
$sql = NULL;
$data = array();
$i = 0;
$input = $_GET["name_startsWith"]; // <-- obtains the search parameter
$input = Sanitize::clean($input); // <-- prepares the search parameter
$sql = "select * from atable where condition like '".$input."%';";
$query = $this->query($sql); // <-- the model execute the search
if ($query){
$c = count($query);
for($i=0;$i<$c;$i++){ // <-- iterate over the returned data
$json['id'] = $query[$i][0]['id'];
$json['column1'] = $query[$i][0]['column1'];
$json['column2'] = $query[$i][0]['column2'];
$data[] = $json; // <-- the data it's stored on an multiarray, to be converted to JSON
}
}
$jquerycallback = $_GET["callback"];
echo JsBaseEngineHelper::object($data,array('prefix' => $jquerycallback.'({"totalResultsCount":'.count($query).',"search":','postfix' => '});')); //<-- the data it´s returned as JSON
}
Then: On the controller create a method to call the search
public function getdata()
{
$layout = 'ajax'; //<-- No LAYOUT VERY IMPORTANT!!!!!
$this->autoRender = false; // <-- NO RENDER THIS METHOD HAS NO VIEW VERY IMPORTANT!!!!!
$this->Cliente->getclient(); // <-- Get the data
}
You can call this method via ajax like this:
$.ajax({
url: "/application/controller/getdata",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 10,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.search, function( item ) {
return {
value: item.id,
label: item.column1+" "+item.column2
}
}));
}
});
Check this for more info:
CakePHP Controller:autorender
CakePHP JsonView
Typo Quotes mismatch
Use double quotes to wrap
url: "<?php echo Router::url(array('controller' => 'products', 'action' => 'showProducts')); ?>",
^ ^
Problem
url: '<?php echo Router::url(array('controller' => 'products',
var ^ str^ var
controller and products are treated as variables not strings
Related
To put in simple words I want status1 to go to ajaxleadsreport controller
A bit more complex explanation:
I have 2 view classes called indexreport and ajaxleadsreport. ajaxleadsreport fetches all the data and displays it. Now I have a GET variable that is being passed to indexreport which I want to be able to pass it to ajaxleadsreport to filter the current data according to the GET variable that has been passed.
Controller Class:
public function listsreport($slug='')
{
$status1 = $this->input->get('status');
print_r($status1);
$main['content']=$this->load->view('crm/leads/indexreport',$content,true);
}
public function ajaxleadsreport($p='')
{
$output = array( 'html'=>$this->load->view('crm/leads/ajaxleadsreport',$content, true));
echo json_encode($output);
}
indexreport View Class:
<?php
$i=$return=$uriseg;
$post=$this->input->post(); $sess=$this->session->userdata();
$post = $post?$post:$sess;
?>
<div>
...
</div>
$(document).ready(function (){
getleads();
});
function getleads(p){
$.ajax({
type: "post",dataType:"json",async:false,cache:true,
url: "<?php echo site_url('leads/ajaxleadsreport'); ?>"+( parseInt(p)>0?'/'+p:''),
data: $('#objlistform').serialize(),
success: function(e){$('#leadswrap').hide().html(e.html).fadeIn('slow');}
}); return false;
}
ajaxleadsreport View class:
<?php
$sess=$this->session->userdata();
$status1 = $this->input->get('status');
// This is where I'm trying to put my GET value of status for filtering but it gives NULL.
$post = array('fstatus'=> $status,'fpriority'=> $sessn['fpriority']);
$postd = json_encode(array_filter($post));
?>
...
<script>
$(document).ready(function() {
function sendreq(){
setpostdatas();cleartable();getleads();
}
var slug = '<?php echo $slug?>';
var postd = '<?php echo $postd; ?>';
$('#item-list').DataTable({
"processing": true,
"stateSave": true,
"serverSide": true,
"ordering": false,
"ajax": {
url: "<?php echo site_url(); ?>leads/loadLeads",
data: {slug: slug, postdata: postd},
type : 'POST',
"dataSrc": function ( d ) {
d.myKey = "myValue";
if(d.recordsTotal == 0 || d.data == null){
$("#item-list_info").text("No records found");
}
return d.data;
}
},
'columns': [
{"data": "id", "id": "id"},
{"data": "lead_status", "lead_status": "lead_status"},
{"data": "priority", "priority": "priority"},
]
});
As you can see in the code above, I've tried $status1 = $this->input->get('status'); in ajaxleadsreport View class but the output for that is NULL, since the GET value is passed in my indexreport view class. When I do a print_r($status1) in indexreport controller it gives the right output, but NULL in ajaxleadsreport controller.
So basically now I need a way to pass this GET value to ajaxleadsreport controller.
You can use flashdata here:
Set your status to flashdata then get it out in ajaxleadsreport like this: (flashdata only exist once on next request)
$this->session->set_flashdata('status', $status1);
In ajaxleadsreport:
$this->session->flashdata('status');
In the controller class declare the variable:
protected $status1;
public function listsReport() {
$this->status1 = $this->input->get('status');
// [...]
}
Then you can access $this->status1 from any function that is invoked after.
So when i try to return an array of database object to my AJAX and parse it, it becomes in an array of chars. I mean my json_encode result is [{'id':38, 'first_name':jana}] and when try to parse it to array in the ajax what is happen is and array of chars - ['[', '{', '''] etc. This is my ajax:
function searchInput() {
var $content = $('.jobboard-quick-search-form').serialize();
$.ajax({
url : '/admin/site/search',
method : "GET",
data : $content,
success : function ( data ) {
var arr = JSON.parse(data);
console.log(arr);
}
});
}
and my action:
public function actionSearch()
{
$lang = \frontend\models\Lang::getCurrent();
$pageSize = 100;
if(\Yii::$app->request->isAjax)
{
$search = \Yii::$app->request->get('search-label');
$town = \Yii::$app->request->get('towns-list');
$startsWith = '%'.$search;
$between = '%'.$search.'%';
$endsWith = $search.'%';
$joinDoctors = "SELECT `doctor`.`id`, `doctorLang`.`first_name`, `doctorLang`.`second_name`, `doctorLang`.`city`, `doctorLang`.`hospital_name`
FROM `doctor` LEFT JOIN `doctorLang` ON `doctor`.`id`=`doctorLang`.`doc_id`
WHERE `doctorLang`.`city`='$town'
AND `doctorLang`.`language`='$lang->url'
AND `doctor`.`active`=1
AND (`doctorLang`.`first_name` LIKE '$startsWith'
OR `doctorLang`.`first_name` LIKE '$between'
OR `doctorLang`.`first_name` LIKE '$endsWith'
OR `doctorLang`.`second_name` LIKE '$startsWith'
OR `doctorLang`.`second_name` LIKE '$between'
OR `doctorLang`.`second_name` LIKE '$endsWith'
OR `doctorLang`.`third_name` LIKE '$startsWith'
OR `doctorLang`.`third_name` LIKE '$between'
OR `doctorLang`.`third_name` LIKE '$endsWith')";
$doctor = \Yii::$app->db->createCommand($joinDoctors)->queryAll();
$joinHospitals = "SELECT `hospital`.`id`, `hospitalLang`.`title`, `hospitalLang`.`address`, `hospitalLang`.`description`
FROM `hospital` LEFT JOIN `hospitalLang` ON `hospital`.`id`=`hospitalLang`.`hospital_id`
WHERE `hospitalLang`.`city`='$town'
AND `hospitalLang`.`language`='$lang->url'
AND `hospital`.`active`=1
AND (`hospitalLang`.`title` LIKE '$startsWith'
OR `hospitalLang`.`title` LIKE '$between'
OR `hospitalLang`.`title` LIKE '$endsWith')";
return json_encode($doctor);
}
}
Thank you in advance!
First of all add in ajax:
dataType: 'json'
$.ajax({
url:<code>,
type: <code>,
dataType: 'json',
data:<code>
})
Next try use restController
class DataController extends yii\rest\Controller
{
public function actionSearch()
{
[.....]
return \Yii::$app->db->createCommand($joinDoctors)->queryAll();
}
}
Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.
Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
How to call a PHP class function from an ajax call
animal.php file
class animal
{
function getName()
{
return "lion";
}
}
Then in my ajax.php file I have an ajax request, need to get values from getName function
How to do that getName() function can I do like this?
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animal/getName",
beforeSend: function() {
},
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
animal.php
<?php
class animal
{
function getName()
{
return "lion";
}
}
Next. Create a new animalHandler.php file.
<?php
require_once 'animal.php';
if(isset( $_POST['invoiceno'] )) {
$myAnimal = new animal();
$result = $myAnimal->getName();
echo $result;
}
Finally. Change your Javascript.
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animalHandler.php",
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
That's is.
You need one additional script, because your animal class can't do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
OOP Currently with php:
ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)
OOP Currently with DotNet:
ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)
My real-life solution:
Do OOA, do not OOP.
So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).
/* mytable.php */
<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);
mysql_set_charset('utf8');
//add
if($_POST["mode"]=="add") {
$cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//modify
if($_POST["mode"]=="modify") {
$cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//erase
if($_POST["mode"]=="erase") {
$cadena="delete from mytable where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
// comma delimited file
if($_POST["mode"]=="get") {
$rpta="";
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while($row = mysql_fetch_array($rs)) {
$rowCount = mysql_num_fields($rs);
for ($columna = 0; $columna < $rowCount; $columna++) {
$rpta.=str_replace($row[$columna],",","").",";
}
$rpta.=$row[$columna]."\r\n";
}
echo $rpta;
};
//report
if($_POST["mode"]=="report_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while ($row=mysql_fetch_array($rs)) {
echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
};
};
//json
if($_POST["mode"]=="json_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
$result = array();
while ($row=mysql_fetch_array($rs)) {
array_push($result, array("id"=>$row['code'],"value" => $row['name']));
};
echo json_encode($result);
};
?>
Can you please mention which are you using any Framework?
You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echo rather then return
For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.
<?php
// =======================================================================
$allowedClasses = array("lnk","objects"); // allowed classes here
// =======================================================================
$raw = file_get_contents("php://input"); // get the complete POST
if($raw) {
$data = json_decode($raw);
if(is_object($data)) {
$class = $data->class; // class: String - the name of the class (filename must = classname) and file must be in the include path
$method = $data->method; // method: String - the name of the function within the class (method)
#$params = $data->params; // params: Array - optional - an array of parameter values in the order the function expects them
#$type = $data->returntype; // returntype: String - optional - return data type, default: json || values can be: json, text, html
// set type to json if not specified
if(!$type) {
$type = "json";
}
// set params to empty array if not specified
if(!$params) {
$params = array();
}
// check that the specified class is in the allowed classes array
if(!in_array($class,$allowedClasses)) {
die("Class " . $class . " is unavailable.");
}
$classFile = $class . ".php";
// check that the classfile exists
if(stream_resolve_include_path($classFile)) {
include $class . ".php";
} else {
die("Class file " . $classFile . " not found.");
}
$v = new $class;
// check that the function exists within the class
if(!method_exists($v, $method)) {
die("Method " . $method . " not found on class " . $class . ".");
}
// execute the function with the provided parameters
$cl = call_user_func_array(array($v,$method), $params );
// return the results with the content type based on the $type parameter
if($type == "json") {
header("Content-Type:application/json");
echo json_encode($cl);
exit();
}
if($type == "html") {
header("Content-Type:text/html");
echo $cl;
exit();
}
if($type == "text") {
header("Content-Type:text/plain");
echo $cl;
exit();
}
}
else {
die("Invalid request.");
exit();
}
} else {
die("Nothing posted");
exit();
}
?>
To call this from jQuery you would then do:
var req = {};
var params = [];
params.push("param1");
params.push("param2");
req.class="MyClassName";
req.method = "MyMethodName";
req.params = params;
var request = $.ajax({
url: "proxy.php",
type: "POST",
data: JSON.stringify(req),
processData: false,
dataType: "json"
});
Try this:
Updated Ajax:
$("#submit").on('click', (function(e){
var postURL = "../Controller/Controller.php?action=create";
$.ajax({
type: "POST",
url: postURL,
data: $('form#data-form').serialize(),
success: function(data){
//
}
});
e.preventDefault();
});
Update Contoller:
<?php
require_once "../Model/Model.php";
require_once "../View/CRUD.php";
class Controller
{
function create(){
$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
insertData($nama, $msisdn, $sms);
}
}
if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
$object = new Controller();
$object->create();
}
?>
For every ajax request add two data, one is class name and other is function name
create php page as follows
<?php
require_once 'siteController.php';
if(isset($_POST['class']))
{
$function = $_POST['function'];
$className = $_POST['class'];
// echo $function;
$class = new $className();
$result = $class->$function();
if(is_array($result))
{
print_r($result);
}
elseif(is_string($result ) && is_array(json_decode($result , true)))
{
print_r(json_decode($string, true));
}
else
{
echo $result;
}
}
?>
Ajax request is follows
$.ajax({
url: './controller/phpProcess.php',
type: 'POST',
data: {class: 'siteController',function:'clientLogin'},
success:function(data){
alert(data);
}
});
Class is follows
class siteController
{
function clientLogin()
{
return "lion";
}
}
I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:
ajax_handler.php
<?php
// Include the class you want to call a method from
echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
some.js
function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
$.ajax({
type: 'POST',
url: 'ajax_handler.php',
data: {
className: className,
methodName: methodName,
parameters: parameters
},
success: successCallback,
error: xhr => console.error(xhr.responseText)
});
}
Greetings ^^
I have a table named state with columns state_id, state_name. Currently I can add new states and edit them, but I can't delete states. What might be wrong with my code?
{title:"Actions",template:'<a class="left" onclick="javascript:openEditStatePopup(this);">Edit</a>' +
'<a class="right" onclick="javascript:deleteState(this);">Delete</a>'
,width:120,sortable:false}
This snippet is the view code, and when I click the link, it executes the following JavaScript:
function deleteState(element)
{
var countryDetail = {};
var GriddataItem = $("#state_grid").data("kendoGrid").dataItem($(element).closest("tr"));
countryDetail.state_id =GriddataItem.state_id;
countryDetail.state_name = GriddataItem.state_name;
// alert(countryDetail.state_id);
$.ajax({
url:"<?= $this->baseUrl('admin/state/delete')?>",
data: {state_id : countryDetail.state_id},
dataType: "json",
type: "POST",
success: function(){
alert('success');
},
failure:function(){
alert('not working');
}
});
}
When I echo alert(countryDetail.state_id) before the $.ajax call, I can get the correct state id.
My delete controller is:
public function deleteAction()
{
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
}
and the model mapper for deleting is:
public function delete(Application_Model_State $state)
{
$data = $state->toArray();
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$data['state_id']));
}
Hi you need to write deleteAction as following
public function deleteAction()
{
$state = $this->_getParam('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateId = $stateMapper->delete($state);
$this->_helper->json(array('success'=>1));
}
in your controller action deleteAction() you are getting POST param 'state_id'
$state = $this->_request->_getPost('state_id');
$stateMapper = new Application_Model_Mapper_StateMapper();
$stateMapper->delete($state);
and you are passing that $state in the $stateMapper->delete($state); function
in your model class function public function delete(Application_Model_State $state) definition you are passing State model object not and state id, so you should change this to
public function delete($state_id)
{
$adapter = $this->getDbTable()->getAdapter()->delete(array('state_id=?'=>$state_id));
}
Then it should work...
Another thing I have not seen
failure:function(){
alert('not working');
}
Rather it is
error:function(){
alert('not working');
}