Send Ajax post value inside PHP Class - php

I'm trying to send a POST value inside a PHP class by Ajax, to change my SQL query.
PHP Page
//Link page with Classes
require_once('mPortfolio.php');
$mPortfolio = new Portfolio();
$all = $mPortfolio->getAll();
//Echo sql results here
//AJAX to send filter value to PHP with Classes
$('#filters a').on('click', function(e){
var filter = $(this).data('filter');
$.ajax({
type: 'POST',
url: 'models/mPortfolio.php',
data: {filter: filter},
success: function(data){
alert(data);
}
});
PHP Classes mPortfolio.php
echo $_POST['filter']; //This works !
require_once $_SERVER["DOCUMENT_ROOT"].'/models/db/db.php';
class Portfolio{
private $_db;
public function Portfolio()
{
$this->_db = new db();
$this->_db->SQLRequest("SET NAMES utf8");
}
public function getAll()
{
if(isset($_POST['filter'])) :
$query = "SELECT * FROM portfolio WHERE category='".$_POST['filter']."' AND online = 1 ORDER BY category,pos ASC";
else :
$query = "SELECT * FROM portfolio WHERE online = 1 ORDER BY category,pos ASC";
endif;
return $this->_db->SQLRequest($query);
}
}
The mPortfolio.php page can actually read the $_POST['filter'] outside the Class, but the public function getAll() cannot.
Can you help me please make it work.
Thanks

Somewhere, you must be creating an object of Portfolio class, and calling getAll(). From there, pass the $_POST['filter'] to getAll like
$portfolioObj = new Portfolio();
$portfolioObj->getAll($_POST['filter']);
The below 2 lines must be inside another PHP, which will include the mPortfolio.php

Add following code:
$portfolio = new Portfolio();
$returnData = $portfolio->getAll();
echo $returnData;
below the class declaration.
This is because of class and functions cann't call directly. You need to call them for class you need to create the instance and then call the function inside the class. Without calling the class or function you cann't execute them.

use
$('#filters a').on('click', function(e){
var filter = $(this).data('filter');
$.ajax({
type: 'POST',
url: 'models/mPortfolio.php/getAll/filter/$_POST['filter']',
data: {filter: filter},
success: function(data){
alert(data);
}
});
and get value in getAll function
OR
$filter = $_POST['filter'];
$portfolio = new Portfolio();
$return = $portfolio->getAll($filter);
echo $return;

Related

Why am I getting undefined index when calling a php method with AJAX?

I'm trying to get some information from my albums class. I think my issue is in the syntax of my AJAX call. Let me break this down for you step by step. Here's the method:
Album.php
...
public function getTracks ($title) {
$db = Dbclass::getDB();
$query = "SELECT *
FROM upcoming_albums_tracks
WHERE albums_title = :title";
$statement = $db->prepare($query);
$statement->bindParam(':title', $title, PDO::PARAM_STR, 50);
$statement->execute();
$tracks = $statement->fetchAll();
return $tracks;
}
This method is working fine, by the way. Now here's my php file that calls this method:
GetTracks.php
<?php
require_once '../../models/database.php';
require_once 'Album.php';
$tracks = new Album;
$tracks->getTracks($_POST['albumTitle']);
return $tracks;
And finally, the AJAX call
upcoming_albums_ajax.js
...
$(document).ready(function() {
//Get track info with Ajax
$(".btn-tracks").click(function (e) {
// stop form submission first
e.preventDefault();
// get album title
var albumTitle = $(this).val();
console.log(albumTitle) //This gives me the value I'm looking for.
// get tracks from php
$.ajax({
url : '../../controllers/admin/GetTracks.php',
//I think the issue is in how I'm formatting the data.
data: {title: albumTitle},
type : 'POST',
success : function (d) {
alert(d);
},
error : errorHandler
});
});
});
My alert just pops up telling me that I have an undefined index: albumTitle.
By the way, this is my button:
<button type='submit' class='btn-tracks' value='" . $album['albums_title'] . "'>Show Tracks</button>
In GetTracks.php you expect to receive $_POST['albumTitle']
$tracks->getTracks($_POST['albumTitle']);
But you pass in $_POST['title'] from javascript
data: {title: albumTitle},
Change either (so they're equal) and you should be fine

jquery Ajax url point to php functions

hi is it possible to retrieve data from a PHP function using Ajax?.
i want my url in ajax to point in one of my functions. please see my code below.
like this:
<?php
class employee{
public function __construct(){
}
public function fName($fName){
echo $fName;
}
public function lName($lName){
echo $lName;
}
}
?>
<div id="fName"></div>
<script type="text/javascript">
$.ajax({
type: 'POST',
url: "classes.php", <!-- HERE I want to target the fname function-->
success: function(result){
fname.html(result);}
});
</script>
what im doing so far is create a new php page which contain code like this.
<?php
$employee = new employee();
$employee->fName();
then ill point the ajax url to that new php page.
Assuming this code works as written in your question
<?php
$employee = new employee();
$employee->fName();
you can pass a parameter to your PHP script then decided which function is to be called like so:
jQuery:
$.ajax({
type: 'GET',
url: "classes.php?func=fname",
success: function(result) {
$("fname").html(result);
}
});
PHP - classes.php:
<?php
$employee = new employee();
$func = #$_GET["func"];
switch($func) {
case "fname":
echo $employee->fName();
break;
case "lname":
echo $employee->lName();
break;
default:
break;
}
The url property has to be a url .. in your case it perhaps will point to "/classes.php" , assuming the file is on document root of the webserver
The function fName needs to be called by the code present in that url.
so your file "/classes.php" should look like this
<?php
class Employee {
protected fName;
protected lName;
function __construct($f, $l) {
$this->fName = $f;
$this->lName = $l;
}
public function getFName(){
return $this->fName ;
}
public function getLName(){
return $this->lName ;
}
}
$employee = new Employee("John" , "Doe");
echo $employee ->fName();

return response correctly for jquery autocomplete in Codeigniter

I am new to jquery and am having trouble with the autocomplete function. edit:I should mention I am using MVC with Codeigniter. My AJAX response is returning like this [{"customer_name":"Adecco Management & Consulting S.A."}]. It is also not all in a row it is each character in the dropdown like this
[
{
"
c
u
s
t
and so on. Here is my autocomplete script.
$('#cust_name').autocomplete({
source: function(request,response){
var request = {
toSearch: $('#cust_name').val()
};
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
response(data);
}
});
}
});
and my controller:
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
echo json_encode($data['id']);
}
model:
public function autoComplete(){
$toSearch = $_POST['toSearch'];
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
input in view:
<input data-input-type="cust_name" id="cust_name" class="ids form-control search-query " type="text" name="customer_name">
I am not sure I set up the jquery function correctly but the response includes the desired results, in the wrong format, when I type in the input. Thanks for any help you can give!
I received the answer outside of SO and want to post the solution here for others.
controller: I needed to put the results into an array and pass that to the ajax response as one object.
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
$results = array();
foreach($data['id'] as $row){
$results[]=$row->customer_name;
}
echo json_encode($results);
}
jquery: As far as I understand this section, I wasn't making use of the built in functions and therefore overwriting the request variable that autocomplete sets up.
$('#cust_name').autocomplete({
source: function(request,response){
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
var items = JSON.parse(data);
response(items);
}
});
}
});
model: didn't change much. I added distinct to limit dup values.
public function autoComplete(){
$toSearch = $_POST['term'];
$this->db->distinct();
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
Thanks to all those who helped me with this!

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

code igniter php and jquery - how to get data from multiple tables and return it via ajax

I am currently using jquery to get JSON data via ajax from a codeigniter backend / mySQL database, which works fine. The problem I'm having is that, along with the data that gets returned to the jquery function, I also need to run a PHP loop for some data in another table. Currently what I'm doing is waiting for an ajax success from the first function, then making another ajax call to the second function - but I know there is a way to do it with just one function, I'm just not sure how. Here are the two database queries:
function get_selected_member($member = null){
if($member != NULL){
$this->db->where('id', $member); //conditions
}
$query = $this->db->get('members'); //db name
if($query->result()){
$member_result = $query->row();
return $member_result;
}
}
AND
function get_all_groups(){
$query = $this->db->get('groups');
$result = $query->result();
return $result;
}
and then in the javascript function, what I'm doing is saying:
var post_url = "/index.php/control_form/get_selected_member/" + selected_member_id;
$('#chosen_member').empty();
$.ajax({
type: "POST",
url: post_url,
success: function(member)
{
//Add all the member data and...
var post_url2 = "/index.php/control_form/get_all_groups/";
$.ajax({
type: "POST",
url: post_url2,
success: function(group)
{
//Create a dropdown of all the groups
}
});
}
});
In PHP you can combine both in one then echo it to ajax as json variable. So in php you will need a change like following
function get_member_with_group($member = null){
$data['member'] = $this->get_selected_member($member);
$data['group'] = $this->get_all_groups();
echo json_encode($data);
}
Then in javascript something like below..
var post_url = "/index.php/control_form/get_member_with_group/" + selected_member_id;
$('#chosen_member').empty();
$.getJSON(post_url, function(response){
var member = response.member;
//do with member
var group = response.group;
// do with group
});
Hope this will help you :)

Categories