How to call controller from ajax and send $_POST - javascript

I want to call controller from ajax and send POST into database. After POST was sent, i will display database into dropdown list.
but i don't know what to do. here is my code.
ajax script inside view add_produk.php
<script>
function getId(val){
// ajax function
$.ajax({
type: "POST",
url: "<?php base_url();?>index.php/getdata",
data: "id_kategori="+val,
success: function(data){
$("#subcat").html(data);
}
});
}
</script>
i want to load controller getdata.php and send $_POST into this controller, Controller getdata.php :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Getdata extends CI_Controller
{
public function index()
{
if(!empty($_POST["id_kategori"])){
$idcat = $_POST["id_kategori"];
$sql = "SELECT * FROM sub_kategori WHERE id_kategori = $idcat";
$result = $this->db->query($sql);
foreach ($result as $subcat) {
?>
<option value="<?php echo $subcat["id_sub_kategori"];?>"><?php echo $city["nama_sub_kategori"];?></option>
<?php
}
}
}
}
?>
how i can fix my problem?

i think wrong in here data: "id_kategori="+val
i dont know php, but u can try "data:{id_kategori:val}"
good luck

Related

json_encode prints data in html

I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax (json_encode) which I've done successfully. The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it.
Server Side:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
Client side:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
Output (Note that body tags aren't being outputted):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript?
Try to send out the json http header in first place on product.php
header('Content-Type: application/json');

Sending Ajax Request to PHP not working

I am trying to make an ajax request to my PHP file.
The ajax request occurs when my "Country" select option menu changes. The result is suppose to be a new select option menu titled "State Province" and the options would be based off the choice made in the "Country" select option menu.
This is what I want it to look like:
The problem I'm having is when the ajax is making a request to the PHP, the PHP seems to be returning an empty array:
Does anyone know what might be wrong?
Thank you!
HTML for the select option:
<select name="Country" class="form-control input-sm" id="Country">
</select>
Ajax code with the onchange function:
$("#Country").on("change",function(){
var val = $('#Country').val();
performAJAX(val,'Country','StateProvince');
});
function performAJAX(choice,prevSelect,newSelect){
$.ajax({
type: "post",
url: "select-creation.php",
data: {choice: choice, prevSelect: prevSelect,newSelect: newSelect},
dataType: "json",
success: function(data){
var obj = $.parseJSON(data);
console.log("meow meow");
}
});
}
PHP code:
<?php session_start();
try{
$choice = $_POST['choice'];
$prevAttri = $_POST['prevSelect'];
$nxtAttri = $_POST['newSelect'];
$data = array();
$sql = 'SELECT '.$nxtAttri.' FROM agents WHERE '.$prevAttri.' = :userChoice';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/Database.class.php';
$db = new Database();
$conn = $db->getConnection();
$query = $conn->prepare($sql);
$query->bindValue(':userChoice',$choice,PDO::PARAM_STR);
if($query->execute()){
$data = $query->fetchAll(PDO::FETCH_ASSOC);
}//stmt
return json_encode($data);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
Your code return json_encode($data); seems to be nothing or invalid because your code doesn't use a function.
Just use echo json_encode($data);
In the ajax side, you don't need to use $.parseJSON(data); because you already specify the dataType to json it will immediately convert the data response by PHP to an object type.

Codeigniter weird ajax result in controller

I've started a codeigniter project and now a i have to do an ajax call to a special controller.
It goes something like this:
- I have two select fields: 1 for selecting county's and the other one must populate with the city's in the selected county.
The problem is I get a really weird result when I send the selected county id to the ajax controller.
If I put something like this in the controller : echo "a $county_id" in the controller it will give me the response : a [selected county_id], but if I only echo out the county id it shows some json empty response, and I don't know what's wrong, below is the code:
the ajax(jquery) call.
$(document).ready(function(){
$('#judet').change(function(){
var county = $( "select option:selected" ).val();
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/") ?>',
success:function(){
console.log('id_judet:' + county);
},
error:function(mesaj){
console.log("there's an error");
}
});
});
});
The codeigniter ajax_controller Controller:
public function index()
{ header('content-type text/html charset=utf-8');
$cou_county = $this->input->post('cou_county');
$decodedCounty = $cou_county;
echo "$decodedCounty";
}
The county and city selectors are two simple select inputs with id's I'll post some pictures if you think i haven't explained it well eneugh.
EDIT: the ajax call does access the controller, where i actually echo that id, but in the response i get some weird json thingy instead of the number, like in the picture below:
the response
Thanks for taking the time to read this, and thanks in advance to those of you who take the time to help a brother out.
You can't use PHP code in javascript:
<?php echo base_url("ajax_controller/") ?>
Instead, you should create a js variable like this:
base_url = '<?php echo base_url("ajax_controller/") ?>';
Then use this variable with your function.
In order to use base_url() you have to load url helper in controller like this..
$this->load->helper('url');
Or load in application/config/autoload.php.
Then in your ajax edit url to
url:'<?php echo base_url("ajax_controller/index");?>',
In controller:
public function index()
{
$cou_county = $this->input->post('cou_county');
echo $cou_county;
}
In ajax:
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/index");?>',
success:function(data){
console.log(data); //see your console
},
error:function(data){
console.log("there's an error");
}
});

Joomla 2.5 component get json from external script

I would get a json (make from a db query) from a external script javascript.
my model:
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modelList' );
class MediastoreModelList extends JModelList
{
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, type, designation', 'marque', 'prix');
$query->from('produits');
return $query;
}
}
my controller:
<?PHP
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class MediastoreController extends JController
{
public function getJson() {
$model = getModel();
$data = $model.getListQuery();
$document = JFactory::getDocument();
$document->setMimeEncoding('application/json');
JResponse::setHeader('Content-Disposition','attachment;filename="result.json"');
echo json_encode($data);
}
}
my javascript:
$.getJSON( "http://mediastore.dev/index.php?option=com_mediastore&task=getJson", function(data) {
console.log(data);
});
but the getJSON fails.
What's wrong ?
Thanks
Your controller code will throw PHP errors. It has to look like:
public function getJson() {
$model = $this->getModel();
$data = $model->getItems();
$document = JFactory::getDocument();
$document->setMimeEncoding('application/json');
echo json_encode($data);
JFactory::getApplication()->close();
}
Try to put the controller action to lowercase. I would also replace the $ with jQuery in your ajax call.
To see what is actually in the response of the ajax call I suggest to use firebug or the chrome developer console which will display the whole response and then you will find out very quick where the problem is.

How to pass global variable via ajax

I have three files:
index.php
ajax.php
function.php
I want to pass a global variable from index.php to function.php via ajax.php.
So the alert message in index.php should be "2". But in fact, the result is "1" because function.php does not know the $global_variable.
Here is the code:
index.php
<?php
$global_variable = 1;
?>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
alert(data);
}
});
</script>
ajax.php
<?php
include 'function.php';
$result = process_my_variable(1);
echo $result;
?>
function.php
<?php
function process_my_variable($new_variable) {
global $global_variable;
$result = $global_variable + $new_variable;
return $result;
}
?>
I do not want to pass the global variable to ajax call, because my real project has many variable like this, and they should not to display because of security.
How to do this?
$.ajax({
type: "POST",
url: 'ajax.php',
data:{
global_variable:<?php echo $global_variable?>
},
success: function(data) {
alert(data);
}
});
You can send it with data object to ajax.php page
and at ajax.php page you can fetch it by:
<?php
include 'function.php';
$global_var=$_POST['global_variable'];
$result = process_my_variable($global_var);
echo $result;
?>
index.php and ajax.php (with the included function.php) are different programs. They do not share variables.
You either need to store the data somewhere that both programs can get at it (such as in a SESSION) or pass the data from index.php to the browser, and then send it to ajax.php in the query string or POST body of the Ajax request.

Categories