Auto display results using json - json

Currently i'm using json to auto display my reuslt, but i got error say json_encode(): type is unsupported, encoded as null, and i think my problem is view, when i choose in name in dropdown i gives an error json_encode(): type is unsupported, encoded
Model
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
foreach($result->result_array() as $row){
echo $row['address'];
}
}
return $result;
}
Controller
function address() {
$name=$this->input->post('name');
$this->load->model('default/M_profile');
$data['address'] = $this->M_vendor->get_address($name);
$this->output->set_output(json_encode($data));
//echo $data;
return;
}
in view i use dropdown.
$(document).ready(function () {
$('#profile select').change(function () {
var add = $(this).text();
$.ajax({
url: "<?php echo base_url();?>admin/profile/address",
method: "POST",
data: {profile: add},
success: function(add) {
$('#address').val(add);
}
})
});
});
<select name="test">....</select>

You have a lots of errors:
1.In ajax it should be type:'POST'.Not method:'POST'.
2.In controller it should be $this->input->post('profile')
3.In model just return your data using result_array().
MODEL:
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
return $result->result_array();
}
}
}
Controller:
function address() {
$name=$this->input->post('profile');
$this->load->model('default/M_profile');
$data = $this->M_vendor->get_address($name);
echo json_encode($data);
}
View:(Ajax):
<script type="text/javascript">
$(document).ready(function () {
$('#profile select').change(function () {
var add = $(this).text();
$.ajax({
url: "<?php echo base_url('admin/profile/address');?>",
type: "POST",
data: {profile: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
alert(data[0].address);
}
})
});
});
</script>
<select name="test">....</select>
I hope it helps you a lot.

you are echoing the result instead of returning
function get_address($name) {
$vendres = array('name' => $name);
$this->db->select('address');
$this->db->where($vendres);
$this->db->distinct();
$result = $this->db->get('profile');
if($result->num_rows() > 0){
foreach($result->result_array() as $row){
$result[] = $row['address'];
}
}
return $result;
}

Related

Morris.js setData doesn't work, unless I do this

I'm graphing data based on database results and getting the data via ajax. The graph is supposed to redraw based on the query using jquery setData. I've asked other programmers at work and still can't figure it out.
php code
if(isset($_POST['data'])){
$data = $_POST['data'];
$data = json_decode($data);
$query = "SELECT * FROM bad_errors WHERE rel = '$data' LIMIT 20";
$result = $db->query($query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$month = date("M", strtotime($row['date_time']));
$chart_data .= "{ month:'".$month."', website:".$row["rel"].", code:".$row["code"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
$data = json_encode($chart_data);
echo $data;
}
jquery code
let barChart = Morris.Bar({
element : 'chart',
data:[],
xkey:'month',
ykeys:['website', 'code'],
labels:['website', 'code'],
hideHover:'auto',
stacked:true
});
let json = JSON.stringify(rel);
$.ajax({
url: "ajax-php/morris-data.php",
type: "POST",
data: {data: json},
dataType:"json",
success: function (data) {
//data variable only redraws the graph if data looks like this -
data = [
{ month:'Mar', website:38, code:547}, {
month:'Mar', website:38, code:584}, { month:'Mar', website:38,
code:500}, { month:'Mar', website:38, code:564}, { month:'Mar',
website:38, code:500},
]
barChart.setData(data); // but not here via ajax success
},
});
I was processing the data wrong in php
while($row = mysqli_fetch_array($result))
{
$month = date("M", strtotime($row['date_time']));
$data[] = array(
'month' => $month,
'website' => $row['rel'],
'code' => $row['code']
);
}
$data = json_encode($data);
echo $data;

FullCalendar: how to get data from db and show in events (as a json feed)

I am a newbie to fullcalendar and ajax. I have difficulty in fetching data from the database and those data should be shown up in my fullcalendar.
I have tried a code to do the same. but i am not able to get data through ajax as a json feed.
So far i am getting data from the database through codeigniter MVC. but i
coulnt pass data to the fullcalendar event.
The following is my view file: calendar.php
<script>
$(document).ready(function() {
$.ajax({
url: "<?php echo base_url() ?>/common/calendar/show_holidays",
type: 'POST', // Send post data
data: 'type=fetch',
async: true,
success: function(s){
freshevents = s;//alert(s);
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
//events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
events: {
}
});
});
</script>
First you need to parse SQL resultset to JSON, you can do that with the next PHP functions:
Connect to DB function:
function connectDB(){
$con = mysqli_connect("HOST", "USER", "PASS", "DB");
if($con){
echo 'OK';
}else{
echo 'KO';
}
return $con;
}
Function to disconnect from DB:
function disconnectDB($con){
$close = mysqli_close($con);
if($close){
//echo 'OK';
}else{
//echo 'KO';
}
return $close;
}
Function to get JSON parse from one resultset:
function getArraySQL(){
$conexion = connectDB();
//generate SQL query
if(!$result = mysqli_query($conexion, "SELECT title,color,start FROM events")) die();
$rawdata = array();
while($row = mysqli_fetch_array($result))
{
$title=$row['title'];
$color=$row['color'];
$start=$row['start'];
$rawdata[] = array('title'=> $title, 'color'=> $color, 'start'=> $start);
}
disconnectDB($conexion);
//Parse to JSON and return
$rawdata=json_encode($rawdata);
return $rawdata;
}
After this step, you can include JSON returned into your events calendar script:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek'
},
events: <?php
$result = array();
$result=getArraySQL();
if(isset($result)){
echo $result;
}
?>,
eventRender: function (event, element) {
element.attr('href', 'javascript:void(0);');
element.click(function() {
alert(event.title);
});
}
});
});
Hope this can help you.

How to display form errors after ajax query and JsonResponse

I have a form to add product using jquery and ajax. Adding proucts work fine but I'd like to know how to display form errors with JsonRespone
This is the jquery code
$(document).on('submit', "#form-add", function (e) {
e.preventDefault();
$.ajax({
type: 'post',
dataType: 'json',
data: $(this).serialize(),
url: Routing.generate('admin_add_product'),
success: function (msg) {
},
error: function(msg){
// do something to display errors
}
});
return false;
});
and this is the action
public function addAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$product = new Product();
$form = $this->createForm(new ProductType(), $product);
if ($request->isXmlHttpRequest()) {
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($product);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Your product has been added to your cart.');
$response = new JsonResponse();
return $response;
} else {
// return errors
}
}
}
}

How to push json object array from mysql into empty array in angularjs

I have been trying to retrieve data from mysql. So, I have written in php:
$result = mysqli_query($con,"SELECT * FROM customers");
$return_arr = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rowArr = array(
'id' => $row['id'],
'firstName' => $row['firstname'],
'lastName' => $row['lastname'],
'address' => $row['address'],
'city' => $row['city']
);
$return_arr[] = $rowArr;
}
echo json_encode($return_arr);
I want to push this data into an array of angularjs success:
var customers = [];
$http.get("app/server/read.php")
.success(function(data){
customers.push(data);
//console.log(data);
});
If I send single row from mysql, it receives i.e. when I write in php echo json_encode($rowArr);, then var customers able to receives otherwise can't for multiple rows. In the console I get:
[Object { id="36", firstName="asdasd", lastName="asdasd", more...}, Object { id="37", firstName="asdasd", lastName="asdasd", more...}, Object { id="38", firstName="asdasd", lastName="asdasd", more...}, Object { id="40", firstName="asd", lastName="asd", more...}, Object { id="41", firstName="asdasd", lastName="asdasd", more...}, Object { id="42", firstName="asdasd", lastName="asdas", more...}, Object { id="43", firstName="asdasd", lastName="asdasd", more...}]
Please could you help me anyone that where I am doing wrong?
UPDATE:
html:
<div class="col-lg-3 card" data-ng-repeat="customer in customers | orderBy:'lastName'">
<button class="btn close cardClose" data-ng-click="deleteCustomer(customer.id)">×</button>
<div class="cardHeader">{{customer.firstName + ' ' + customer.lastName}}</div>
<div class="cardBody">{{customer.city}}</div>
</div>
Controller:
app.controller('CustomersController', function ($scope, customersService, $http) {
init();
function init() {
$scope.customers = customersService.getCustomers();
}
});
Service:
app.service('customersService', function ($http) {
this.getCustomers = function () {
return customers;
};
var customers = [];
$http.get("app/server/read.php")
.success(function(data){
//customers.push(data);
customers = data;
});
});
Try this:
app.service('customersService', function ($http, $q) {
var deferred = $q.defer();
$http.get('app/server/read.php').then(function(res) {
deferred.resolve(res);
});
var getCustomers = function() {
return deferred.promise;
};
return {
getCustomers: getCustomers
};
});
And in your controller:
customersService.getCustomers().then(function(customers) {
$scope.customers = customers;
});

JSON to HTML (Codeigniter)

public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
foreach($result as $r){
echo json_encode($r);
}
}
}
$(document).ready(function(){
$('#getMem').keyup(function(e){
var name = {
ajax: 1,
name: $('#getMem').val()
}
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data){
$('#freshMem').html(data.first_name);
},
error: function(){
alert('Error.');
}
});
});
});
This works fine if the result from database returns only one row, if more than one generates error, can anyone please tell me how to solve this
Use the Output class to tell the browser that JSON is being returned. The problem is that you are json_encodeing multiple objects in your foreach loop. Just json_encode the array returned from your model
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
$this->output
->set_content_type('application/json')
->set_output(json_encode(array("response" => $result)));
}
}
$(document).ready(function(){
$('#getMem').keyup(function(e){
var name = {
ajax: 1,
name: $('#getMem').val()
}
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data)
{
var __html = '';
$.each(data.response, function (a, b)
{
__html += '<p>'+b.first_name+'</p>';
});
$('#freshMem').html(__html);
},
error: function()
{
alert('Error.');
}
});
});
});
Try this:
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data){
json_data = $.parseJSON(data);
$.each(json_data, function(i,item){
$('#freshMem').append(item.first_name);
});
},
error: function(){
alert('Error.');
}
});
You have to iterate over returned array.
Also you need to change your controller code:
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
// assuming that $result is array...
$json = json_encode($result);
echo $json;
/*foreach($result as $r){
echo json_encode($r);
}*/
}
}