Unknown/Unhandled Data Type(s) - php

Please help.
I am using codeigniter/php for my website. It is working well in my localhost but when I tried to transfer it to live, it's getting an error. The error part is detected in my script where I am trying to parse a json generated in php. this is where the json is encoded :
function get_product_offered_json(){
$data = [];
$query = $this->db->get("product_smb");
if ($query->num_rows() > 0){
foreach ($query->result() as $row) {
$data[] = $row;
}
return json_encode($data);
}else{
return "empty";
}
}
and this is where i parse it:
jQuery.post(base_url + "/product/smb/get_product_offered_json/", function(data, status){
if (data != "empty"){
//productOffered.prop( "disabled", false );
var $data = jQuery.parseJSON(data);
productOffered.empty();
productOffered.append("<option value='0'>Please choose here...</option>");
Hope this is enough to explain my issue. thanks

Use echo instead of return ,in ajax we get the output
if ($query->num_rows() > 0){
foreach ($query->result() as $row) {
$data[] = $row;
}
echo json_encode($data);
}else{
echo "empty";
}

Related

php script error: no search results or error displayed on the search query

I'm working on a php project and the search function from the database is not returning any results or any error. Below is the code for the search function:
function searchweb() {
console.log("click");
//e.preventDefault();
searchWebsite = $("#searchWebsite").val();
if (searchWebsite == "")
$("#searchWebsite").focus();
else {
console.log("else");
$("#search").html("Searching..");
$("#search").attr("disabled", true);
var excat = "like";
if ($('input[type=checkbox]').prop('checked'))
excat = "match";
$.post("userinput.php", {
searchWebsite: $("#searchWebsite").val(),
excat: excat
}, function (data) {
console.log("hey"+data);
populateSearch(data);
});
function populateSearch(data){
data = JSON.parse(data);
$('#result').empty();
$.each(data, function (key, value) {
//console.log(data);
$('#result').append("<tr>\
<td><a href='"+value.website_name+"' target='_blank'><i class='glyphicon glyphicon-search'></i></a></td>\
<td>"+value.website_name+"</td>\
<td>"+value.avg_score+"</td>\
<td><img class = 'imgs img-responsive center' src='../img/"+value.remark+".png' alt ='"+value.remark+"' />\
</td></tr>");
});
}
// console.log(searchWebsite);
$("#search").html("Search Website");
$("#search").attr("disabled", false);
}
}
The 'searchweb' function calls the post method to search in the mysql database. I'm using phpmyadmin for this project. The code for post function in userinput file:
if(isset($_POST['searchWebsite'])){
$searchWebsite = $_POST['searchWebsite'];
$type = $_POST['excat'];
$sql = "SELECT * from websites WHERE ";
//for excact match
if($type=="match")
$sql.= "MATCH(tags) Against('$searchWebsite') ORDER BY avg_score DESC";
//for tags contaionun gthose words
else
$sql.= "tags LIKE '%$searchWebsite%' ORDER BY avg_score DESC";
$result = mysqli_query($db, $sql);
if($result){
$rr = array();
$i=1;
while($row = mysqli_fetch_assoc($result))
{ $rr[] = $row;
$i=$i+1;}
echo json_encode($rr);
}
else
{
echo "<script type='text/javascript'>alert('Error: '".mysqli_error($db).");</script>";
}
}
No error will be spit back as this is a .post in javascript call / AJAX request. AJAX will not dynamically parse the javascript error code you're trying to trap within the AJAX request.
It's better to do something like this:
PHP side:
Replace:
echo "alert('Error: '".mysqli_error($db).");";
With:
echo json_encode( [ 'error' => mysqli_error($db) ] );
Javascript Side:
// Note you shouldn't have to parse JSON since on the PHP side the error array has been encoded as json
if( ! $.isEmptyObject(data.error) ) {
alert( data.error );
}

AngularJS ng-repeat not showing data in table

I have a problem with output from MySQL
getCustomers.php is
$query="select distinct c.ancestry, c.trusted from members c order by c.id";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = json_encode($row);
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
and controler code:
app.controller('customersCrtl', function ($scope, $http, $timeout) {
$http.get('ajax/getCustomers.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 100; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
Problem is that i get from MySQL this format (e.g.):
["{\"ancestry\":\"12865794218\",\"trusted\":\"128\"}"]
but expectable is:
[{"ancestry":"1286794218","trusted":"126"}]
so, if I write constants in data it works perfectly fine
$scope.list = [{"ancestry":"1286794218","trusted":"126"}];
Thanks for any help.
You're double-encoding your response. The backslashes are there because the second application of json_encode escapes the double quotes in the output of the first one. Remove the json_encode from inside your while loop.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row; // don't encode here
}
}
Then just encode it once afterward (as you already are.)
$json_response = json_encode($arr);
I think you need to use header('Content-Type: application/json'); in your php code, so that the server responds with a JSON content type.
There is also a duplicate json_encode in your code, inside your while loop so you're doing duplicate json encoding, hence the unexpected output
use JSON.parse() on your response. JSON.parse docs

Post JSON object to php using Ajax

I am dynamically adding table rows by selecting options from dropdown and then I am trying to send html table rows to php function using ajax as array in json format. However php function does not print all rows in the console log, when I am submitting more than one row. I got the desired output like once or twice. I think I am missing something in the php function. Please check once. If anymore information about the code is required, let me know, I will update.
Javascript:
function storeClgValues() {
var CollegeData= new Array();
$('#collegetable tr').each(function(row, tr){
CollegeData[row]={
"college" : $(tr).find('td:eq(0)').text()
}
});
CollegeData.shift();
return CollegeData;
}
$('#submit').click(function() {
CollegeData=storeClgValues();
CollegeData=$.toJSON(CollegeData);
$.ajax({
type:"POST",
url: '<?php echo base_url();?>ajaxController/insertcollege',
data: "CollegeData=" + CollegeData,
success: function(msg) {
console.log(CollegeData);
console.log(msg);
}
});
});
PHP function in AjaxController class:
public function insertcollege()
{
$data=array();
$data=stripcslashes($_POST['CollegeData']);
$data=json_decode($data, TRUE);
//echo $data[0]['college'].'<br>';
//echo $data[1]['college'].'<br>';
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
echo $item['college'].'<br>';
}
}
}
Output in console in three tries:
[{"college":"College of Agriculture"}]
College of Agriculture
[{"college":"College of Agriculture"},{"college":"College of Business"}]
College of Agriculture
College of Business
[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]
<!--nothing gets printed-->
Try like this...
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
$output[]=$item['college'].'<br>';
}
}
echo json_encode($output);
?>
OR
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
foreach($item as $value){
$output[] = $value."</br>";
}
}
}
echo json_encode($output);
?>

how to fetch the array data from database query in a php file to ajax sucess data

i am trying to get the data which is in array, from an SQL query to the ajax success data. Here is the code i tried,
function adminchecksub(value1){
//alert('hi');
var value1=$('#adminsid').val();
//alert(value1);
if(value1==''){
alert('Please enter a Sub id');
}
else{
//alert(value1);
$.ajax({
type: 'POST',
url: root_url + '/services/services.php?method=adminsubcheck',
data: {value1:value1},
async: true,
success: function (data) {
alert(data);
if (data == 1) {
alert('inside');
//window.location.assign(rdurl+"?sid="+sid);
return true;
} else {
//alert('does not exist!');
//alert('outside');
return false;
}
}
});
}
now in the php method which is requested from the above ajax call, i have to get the data return by this function which is returning an array
function adminsubcheck($sid){
$subid=$sid['value1'];
$row = array();
//echo $subid;
$query = "SELECT Sub_id,Status,Sub_type FROM Sub WHERE Sub_id=$subid";
//echo $query;
//echo $subid;
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
//echo $count;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
return $row;
}
here $row is returning an array as data to the ajax function, where i need to get all the items seperately. Some one help me out to get the values into the ajax call. Thanks in advance..
In your PHP file, you can return your array as a json object in the following way (notice how the PHP file echos the result to pass it back to javascript)
...
$json = json_encode($row);
echo $json
Now add the following to your javascrip ajax
$.ajax({
...
// Whatever code you currently have
...
}).done(function ( json ) {
var data = JSON.parse(json);
//Continue with javascript
});
You can handle the java script variable 'data' as an associative array like it was in PHP
also, look how you populate the php variable $row and adjust the following way:
$cnt = 0;
while ($r = mysql_fetch_assoc($queryresult)) {
$row[$cnt] = $r;
$cnt++;
}
$json = json_encode($row);
echo $json;
in javascript you can access your rows the following way in teh data variable:
var value = data[0]['field_name'];
in the above statement, 0 will correspond to the value of $cnt (i.e. mysql returned row number)
return $row;
replace like this
echo json_encode($row);
and add dataType='json' in ajax like this
dataType: 'json',
If you want get the value in ajax call i think it shoul be :
while ($r = mysql_fetch_assoc($queryresult)) {
$row[] = $r;
}
echo json_encode(array('data'=>$row));
exit;

Modify Array to Output in JSON using PHP and jQuery

I'm currently working with the jQuery Autocomplete Plugin.
The code they provided in the demonstration is:
<?php
$q = strtolower($_GET["q"]);
$items = array(
"Peter Pan"=>"peter#pan.de",
"Molly"=>"molly#yahoo.com",
);
$result = array();
foreach ($items as $key) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key
));
}
}
echo json_encode($result);
?>
I'd like to know how I can modify this code to output my own array from my MySQL database.
I've tried on my own modification, but I'm not doing it correctly. This is what I am trying:
$q = strtolower($_GET["q"]);
$sql = "SELECT name from user_info";
require("connection.php");
$result = mysql_db_query($DBname,$sql,$link) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
foreach ($rows as $key) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
$key
));
}
}
}
print json_encode($rows);
And this is my jQuery/Javascript:
$("#email").autocomplete('emails.php', {
multiple: false,
dataType: "json",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.name,
result: row.name
}
});
},
formatItem: function(item) {
return format(item);
}
}).result(function(e, item) {
$("#content").append("<p>selected " + format(item) + "</p>");
});
});
As a result, Firebug shows that it throws the following error:
value is undefined
Any help on getting my query setup properly would be greatly aprpeciated. Thanks!
I think that this occurs because you using a array converted in json, then you need to use how an array too in jquery result. Or you can do a json string without using json, in the format: '[{"name":"john","year":2009},{"name":"tom","year":2000},...]'.
Your jquery is fine. After several hours I found out that it was the formatting in the 'format' function that was triggering the error.
If you look at the source code at
http://jquery.bassistance.de/autocomplete/demo/json.html
You'll see the following, seemingly inconsequential function
function format(mail) {
return mail.name + " <" + mail.to + "&gt";
}
If you're leaving out the 'less than' and 'greater than' representations, then you're probably getting the
value is undefinded
error after the first record is looped through in your console. For some strange reason the less than and greater than symbols are significant. Make sure you keep them in your format function.

Categories