PDO: How to send an ajax serialized data to a php controller? - php

I make a ajax call that is triggered when a checkbox is checked or unchecked. I am new to PDO mvc design. What I am attempting to do is when the ajax call is made the serialized data is passed to an object which calls a functions that sets this data in the DB.
ajax:
$('#interests').on('change', 'input', function (e){
e.preventDefault();
var str = $('#interests').serialize();
$.ajax({
type: 'POST',
url: 'index.php',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});
});
Interest controller:
class InterestController
{
function __construct(){}
public function set_user_interest()
{
$table='interests';
$_POST['Username']=$_SESSION['logname'];
$interest = new Interests($_POST, $table);
if ($interest->set_interest()) {
echo "interest were set";
}
else {
echo "something went wrong with interest";
}
# code...
}
All controllers are usually created by a routes file, which based on the string passed to the url constructs that object.
routes:
<?php
function call($controller, $action){
require_once('controllers/' . $controller . '_controller.php');
// create a new instance of the needed controller
switch($controller) {
case 'landing':
$controller = new LandingController();
break;
case 'login':
$controller = new LoginController();
break;
case 'signup_form':
$controller = new SignupFormController();
break;
case 'signup':
require_once 'models/users.php';
require_once 'models/interest.php';
$controller = new SignupController();
break;
case 'interest':
require_once 'models/interest.php';
$controller = new InterestController();
}
// call the action
$controller->{ $action }();
}
// just a list of the controllers we have and their actions
// we consider those "allowed" values
$controllers = array('landing'=>['landing_page', 'error'],
'signup_form'=>['set_signup_form', 'error'],
'signup'=>['create_user', 'error'],
'interest'=>['set_user_interest', 'error']
);
// check that the requested controller and action are both allowed
// if someone tries to access something else he will be redirected to the error action of the pages controller
if (array_key_exists($controller, $controllers)) {
if (in_array($action, $controllers[$controller])) {
call($controller, $action);
} else {
call('landing', 'error');
}
} else {
call('landing', 'error');
}
?>
index.php:
<?php
session_start();
require_once('Water.inc');
if (isset($_GET['controller']) && isset($_GET['action'])) {
$controller = $_GET['controller'];
$action = $_GET['action'];
} else {
$controller = 'landing';
$action = 'landing_page';
}
require_once 'views/layout.php';
?>
How would i send a serialized form to a controller that sends it to the database, using ajax?

Select Country
">
Select State
Select City
<script type="text/javascript">
$(document).ready(function(){
$("#COUNTRIES").change(function(){
var CID = $('#COUNTRIES').val();
$.ajax({
method:'post',
url:'<?php echo base_url('index.php/Userc/SERVICE2') ?>',
data: {"CID":CID},
dataType:'json',
success: function(result){
$('#STATES').html(result); },
});
});
//*********************controller******************//
public function SERVICE2(){
if ($this->input->post('CID')) {
$CID = $this->input->post('CID');
$where = array('CID' => $CID);
$query['P'] = $this->Model1->displaywhere('states',$where);
$html = '<option>Select State</option>';
foreach($query['P'] as $row) {
$html .="<option value=".$row['SID'].">".$row['SNAME']."</option>";}
echo json_encode($html); // must..}

Related

How to get the response and return result from controller action to view

i have written this script in View. In onblur event i have check whether the mail id is already exits r not.for that i have to pass mailId id to the controller action and i want to get the return result.
$.ajax({
type: "POST",
url: "<?php Yii::app()->createAbsoluteUrl("Approval/checkMailid"); ?>",
data: mailId,
success: function() {
return data;
},
error: function() {
alert('Error occured');
}
});
public function actionCheckMailid($mailId)
{
$model = YourModel::model()->findAll('id = :mid', array(':mid'=>$mailId));
echo json_encdoe($model);
}
Just need to throw a 404 page and ajax error handle can catch it.
public function actionCheckMailid($mailId){
$exist = Yii::app()->db->createCommand('select count(*) from your_email_table where id_email = :id_email')
->queryScalar(array(
'id_email' => $mailId
));
if($exist > 0){
echo json_encode(array(
'success'=>true
));
}else{
throw new CHttpException('Email can not be found');
}
}

AJAX request and PHP class functions

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 ^^

Posting to controller with jquery ajax in CakePHP

I want to post data to a controller in CakePHP, but posting with JQuery always results in an error and I can't figure out why.
In my view I have the following method, that posts the data to the controller page
function RenameNode(name, id)
{
$.ajax({
type: "POST",
url: '<?php echo Router::url(array('controller' => 'categories', 'action' => 'rename')); ?>',
data: {
id: id,
name: name
},
success: function(){
}
});
}
My controller method looks like this:
public function rename($id = null, $name = null) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if(!$id)
{
$id = #$this->request->query('id');
}
if(!$name)
{
$name = #$this->request->query('name');
}
if (!$id) {
throw new NotFoundException(__('No id'));
}
$category = $this->Category->findById($id);
if (!$category) {
throw new NotFoundException(__('Invalid category'));
}
$this->autoRender = false;
$this->layout = 'ajax';
if ($this->request->is('post') || $this->request->is('put')) {
$this->Category->id = $id;
$this->request->data['Category']['name'] = $name;
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash(__('The category has been updated.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to update the category.'));
}
}
}
When I do a post with the jquery method, I keep getting the following error message in my log:
2013-05-20 11:34:25 Error: [NotFoundException] No id
Request URL: /cakephp/categories/rename
Stack Trace:
#0 [internal function]: CategoriesController->rename()
When I comment the request checks for get and post, the controller itself works perfectly when I call it with /categories/rename?id=1&name=test. For some reason the ajax way doesn't work, but I can't figure out why. Any ideas?
Update
I fixed it by changing the following code, now it works perfectly
if(!$id)
{
$id = #$this->request->query('id');
}
if(!$name)
{
$name = #$this->request->query('name');
}
to
if(!$id)
{
$id = #$this->request->data('id');
}
if(!$name)
{
$name = #$this->request->data('name');
}
You are not including the id and/or name in the URL you're posting to;
echo Router::url(array('controller' => 'categories', 'action' => 'rename'));
Will output;
/categories/rename
But you're expecting
/categories/rename/1/test
Or
/categories/rename?id=1&name=test
Change the URL in your AJAX code to something like;
echo Router::url(array(
'controller' => 'categories',
'action' => 'rename',
0 => $this->request->params['pass'][0],
1 => $this->request->params['pass'][1]
));
Which should output the right url, containing the original id and name of the current request (e.g. /categories/rename/123/oldname)
use somthing like that
data = 'name='+name+'&id='id'';
$.ajax({
type:'post',
url: '/categories/rename',
data: data
});
and in controller function
$name=$_POST[name];
$id=$_POST[id];
$('a.ajax-delete-pdf').on('click', function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax(
{
url: webroot + 'productos/ajax_eliminar_pdf/' + id ,
async : false,
success: function(respuesta)
{
if(respuesta == 'Borrado')
{
$(this).parent().toggle();
}
}
});
});

Calling php class function in javascript (ajax)

I was wondering if is there any good practices to call method from php class with Javascript, by the way of Ajax.
This is my current "style" to execute it.
(The method in the class are only here for example)
PHP side :
<?php
if(isset($_POST['action']) && $_POST['action'] != null)
{
extract($_POST);
if($action)
{
$ajaxCommand = new EleveUpdate();
if(method_exists($ajaxCommand, $action))
{
$reponse = call_user_func(array($ajaxCommand, $action),$_POST);
echo $reponse;
exit(0);
}
else
{
throw new Exception("Cette méthode n'existe pas");
}
}
}
else
{
echo 'Cette action n\'est pas autorisée';
return false;
}
class EleveUpdate
{
public function __construct()
{
}
public function testfunct($data)
{
echo $data['eleve'];
}
}
Javascript side:
$(document).ready(function() {
$.ajax({
url: 'eleveupdate.php',
type: 'POST',
data: {
action: "testfunct",
eleve: 1
},
beforeSend: function()
{
loading(true);
},
error: function()
{
console.log('error');
},
success: function(data)
{
loading(false);
console.log(data);
}
});
});
The problem is that the isset $_POST is always in my class, I'm pretty sure this is not the right way to do it so, I'm here to found help about it.
Thanks you in advance
Simon
The problem is it's not easy to call scope-namings based on a string-request.
You can use something called LAMBDA, or anonymous functions. This way you can store an array of strings with a LAMBDA attached to them. Like this:
<?php
class EleveUpdate {
private $funcs = array();
function __construct($which_function) {
$funcs['testfunct'] = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
$funcs[$which_function];
}
}
?>
See more info here: http://www.php.net/manual/en/function.create-function.php
You probably won't even need the Class anymore with this method, but just showing.

Zend Ajax can't delete

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');
}

Categories