getting parsererror from presumed empty json response - php

EL PROBLEMO
My JSON returns an associative array that I take elements from and display on the page. Sometimes one or more of the sub-arrays will be empty, and this is expected behavior. For those I want nothing displayed on the page. My problem is that currently anytime one of those sub-arrays is empty, I get a "parsererror". In my application, you switch between months, and this AJAX call is made when the dropdown selection is changed to a different month. On months where all the sub-arrays have values, I dont get an error. I only get it when one or more of the sub-arrays are empty.
PHP
first I perform the SQL queries, which I'm leaving out to keep this as short as possible, but these are the 3 resulting arrays:
$income = $results->fetchall(PDO::FETCH_ASSOC);
$expense = $results->fetchall(PDO::FETCH_ASSOC);
$recurring = $results->fetchall(PDO::FETCH_ASSOC);
Then I want to assign those to an array, which I then json_encode:
$array = array(
'income' => $income,
'expense' => $expense,
'recurring' => $recurring
);
echo json_encode($array);
AJAX
This is basically calling the previous php code, then displaying each record from the database in a table.
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "JSON",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
$('#income tbody tr, #expense tbody tr').remove();
for(var i = 0; i < response.income.length; i++) {
$('<tr><td id="' + response.income[i].cat_id_PK + '">' + response.income[i].cat_name + '</td><td id="' + response.income[i].cat_id_PK +
'">$' + response.income[i].cat_amount + '</td></tr>').appendTo("#income");
}
for(var i = 0; i < response.expense.length; i++) {
$('<tr><td id="' + response.expense[i].cat_id_PK + '">' + response.expense[i].cat_name + '</td><td id="' + response.expense[i].cat_id_PK + '">$' + response.expense[i].cat_amount + '</td></tr>').appendTo("#expense");
}
for(var i = 0; i < response.recurring.length; i++) {
$('<tr><td id="' + response.recurring[i].cat_id_PK + '">' + response.recurring[i].cat_name + '</td><td id="' + response.recurring[i].cat_id_PK + '">$' + response.recurring[i].cat_amount + '</td></tr>').appendTo("#expense");
}
});
request.fail(function(jqxhr, textStatus){
alert("Request failed: " + textStatus);
});
};
JSON
Here's an example JSON response with two empty sub-arrays.
{
"income": [],
"expense": [],
"recurring": [
{
"cat_id_PK": 67,
"cat_name": "Grooming",
"cat_amount": "40.00",
"recur_begin": 1,
"recur_end": 12
}
]
}

Count the number of rows you get from sql query result.
if they are greater than 0 then send an extra field as
$d['status'] ='OK';
if no record exists then send the error handling as
$d['status'] ='ERR';
so check the status field in the data success
dataType: 'json',
data: you data,
success: function( data ) {
if(data.status == "OK"){
alert('success');
} else{
alert('failure');
}
}
});
try like this ,just to test and then use data

Related

Ajax code for live search bar.If no data is found it is not showing error

If the return has data then the code works fine. But if it is empty it is supposed to show error log. But not happening
$.ajax({
type: "POST",
url: "<?php echo base_url();?>homecontroller/category_search_name",
data: {search_name: search_text},
success: function(data){
var mainObj = JSON.parse(data);
var j = 1;
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td class="column1">' + j + '</td>';
k+= '<td class="column2">' + mainObj[i].s_name + '</td>';
k+= '<td class="column3">' + mainObj[i].s_admissionno + '</td>';
k+= '<td class="column4">' + mainObj[i].s_dob + '</td>';
k+= '<td class="column5">' + mainObj[i].s_address + '</td>';
k+= '</tr>';
j++;
}
k+='</tbody>';
document.getElementById('tbody').innerHTML = k;
},
error:function(jqXHR, textStatus, errorThrown){
alert("error");
}
});
Actually, the "error" parameter in ajax won't get triggered even if you get no results. The "error" parameter in ajax gets triggered only if the AJAX itself failed to execute due to some exceptions or something alike in code.
If you want to trigger "error" when no result is found, just return a parameter "countOfRecords" from backend check the value of it in "success" parameter of AJAX.
For example:
success: function(data){
var mainObj = JSON.parse(data);
if(mainObj.countOfRecords == 0) {
//Your "Error" code here
}
}
You can also refer to the following example in fiddle
enter code here
Fiddle link
Taken the fiddle from following link
Stack overflow post

When I try to send data to the server, I do not get the result expected

I have a Jquery function that is using getJson. I am trying to form something like www.mysite.com/?state=oregon. According to Jquery ("Data that is sent to the server is appended to the URL as a query string..."), but I get all the values in the json data. What I am doing wrong.
Here is my code
function changeLine(line){
$('#table_lines').html('');
$.getJSON("../index.php", {, line}, function(data){
var line_data = '';
$.each(data, function(key, value){
line_data += '<tr id="' +value.line_id+'">';
line_data += '<td>' + otherValueTime(value.MatchTime)+'</td>';
line_data += '<td>' + value.home+'</td>';
line_data += '<td>' + value.away+'</td>';
for(i=0; i < value.Cases.length; i++){
console.log(value.Cases[i].CaseType + ' ' + value.Cases[i].CaseAway + ' ' + value.Cases[i].CaseHome);
if(value.Cases[i].CaseType === "Game"){
line_data += '<td>' + value.Cases[i].CaseAway +'</td>';
line_data += '<td>' + value.Cases[i].Total +'</td>';
line_data += '<td>' + value.Cases[i].Over +'</td>';
}
}
});
$('#table_lines').append(line_data);
});
}
On the line with this code "{, line}", I tried putting the key value from the json array, like {id: line}. What I want to do is to get a group of cases according to the key.
I would like to know how you do that. I want to change it according to the option value. I do get data from the server, but I get all the data. Here is how I call that function
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str = $( this ).val();
$.ajax({
method: "POST",
url: "../index.php",
data: { 'id' : str }
})
});
changeLinea(str);
})
.change();

PHP - JSON to HTML

I am trying to display json_encode data from my back end controller to view using together with AJAX. The AJAX runs successfully and received the response that I needed. However, i am unable to display out on my HTML.
I have double-checked that there is certainly a response coming from the back end. Please do help me.
AJAX jQuery
$.ajax({
type: 'post',
url: 'index.php/Status/facility',
dataType: "json",
data: {id:id},
success: function (response) {
var len = response.length;
console.log(len);
for(var i=0; i<len; i++){
var id = response[i].facility_id;
var username = response[i].name;
var tr_str = "<li class='pointer' id='" + (i+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append(tr_str);
}
$('#exampleModalCenter').modal('show');
}
});
HTML
<ul class="nav nav-pills" id="tabAjax"></ul>
Controller
public function facility(){
echo json_encode($data);
//$this->load->view('templates/student/footer');
}
Response
{"facility_list":[{"facility_id":"1","name":"Table 1","facility_category":"1"}]}
I believe you need to access the data within facility_list so to do so firstly get a reference to that level of the response data and then iterate through it's child objects
var json=response.facility_list;
for( var n in json ){
var obj=json[n];
var id=obj.facility_id;
var name=obj.name;
var cat=obj.facility_category;
var tr_str = "<li class='pointer' data-category='"+cat+"' id='" + (n+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";
$("#tabAjax").append( tr_str );
}
The best way to implement this handle it at backend. You can prepared html at backend and send prepared html in response(in any key of array) and append according that. That will be more easy to handle response and no need to reload page every time.
$response = array(array('facility_id' => 1, 'facility_category' => 2, 'name' => 'abc'));
$returnResponse = array('status' => 'false', 'data' => '');
$str = '';
foreach ($response as $key => $resp) {
$str .= '<li class="pointer" data-category="' . $resp['facility_category'] . '" id="' . ($key+1) . '" onclick="changeClass(this.id)"><a> ' . $resp['name'] . ' </a></li>';
}
$returnResponse['status'] = true;
$returnResponse['data'] = $str;
Now in js file you can use:-
var html = response.data;
and append above html where you want.

JSON values not showing properly

I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.

How to display array of json data properly in html?

My Ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$("#main_content").slideUp("normal",function(){
$(".the-return").html("<br />JSON: " + data);
//how to alter this part to display data for each record in one div?
});
}
});
return false;
});
My query
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
The result displayed currently in this form:
JSON: jack,55421894ab602,test,55439324cc43d
But I want to display like:
Name:jack,
Id:55421894ab602
.....and some other info-
Name:test
Id:55439324cc43d
.....and some other info-
This part:
$(".the-return").html("<br />JSON: " + data);
I tried: data[0];
But when I do this, only the first record displayed obviously.
What I'm trying is :
data[0] itself is an array. How to display that array together with other records fetched in nice html?
edited: WIth these edited code, i can only retrieve the last result, it's not looping through the array.
ajax
success: function (data) {
$("#main_content").slideUp("normal",function(){
//$(".the-return").html("<br />JSON: " + j_data);
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
console.log(data); // this shows nothing in console,I wonder why?
//alert(j_data);
});
}
php
$json = array();
while( $row = $statement->fetch()) {
//array_push($json, array($row['Name'], $row['PostUUID']));
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
First, to get the names of the fields in your template, you need store them in your array:
array_push($json, array("name" => $row['Name'], "id" => $row['PostUUID']));
Result after json_encode -> {"name":"TheName","id":"TheID"}
Next, in your js code, if the json that it receives is valid, you can do a loop:
success: function (data) {
$("#main_content").slideUp("normal",function(){
for (i = 0; i < data.length; i++) {
$(".the-return").html("<div>Name:" + data[i].name + "<br/>Id:" + data[i].id);
}
}
}
Of course, you can add style or class to the div.
I hope it helps.

Categories