parse error from ajax call - javascript

I have written some ajax code using an open source library to do jquery pagination.
when the page first loads, it properly queries and displays the first 25 records from my database. But all subsequent requests fail with a parse error.
I can't see anything different between the formatting of data in the first page vs. other pages.
I've tried to use JSON Lint but none of my json passes, even the query for page 1.
My json data looks like this:
"[{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"and the final update\",\"number\":\"72212\",\"updatedname\":\"28112\",\"createdname\":\"conversion script\",\"user\":\"28507\",\"position\":\"1\",\"device_id\":\"2\",\"user_id\":\"2\",\"password\":\"Wh16dteaR\",\"updateddatetime\":\"2013-10-07 15:14:28\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"Bauer\",\"number\":\"72787\",\"createdname\":\"conversion script\",\"user\":\"28509\",\"position\":\"2\",\"device_id\":\"4\",\"user_id\":\"4\",\"password\":\"EHVOzIx1\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\" Woosly\",\"number\":\"72822\",\"createdname\":\"conversion script\",\"user\":\"28510\",\"position\":\"3\",\"device_id\":\"5\",\"user_id\":\"5\",\"password\":\"IP8rsdOE\"}]"
And then I use the parseJSON method to convert the above string into an object.
Here's the main routine that makes the ajax call and parses:
$.ajax({
url: mypath + '?startpos=' + page_index * items_per_page + '&numberofrecordstograb=' + items_per_page + '&viewtype=json',
dataType: 'json',
success: function(data){
data = $.parseJSON(data); //converting to a javascript object vs. just string...
if (data !=null) {
for(var i=0;i<data.length;i++){
var deviceobj = data[i];
newcontent = newcontent + "<TR>";
newcontent=newcontent + '<TD>';
//add EDIT hyperlink
if ($("#editdevicesettings").val() == "true") {
var temp = $("#editlinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]) + ' ';
}
//add DELETE hyperlink
if ($("#deletedevice").val() == "true") {
var temp = $("#deletelinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]);
}
newcontent=newcontent + '</TD>';
newcontent=newcontent + '<TD>' + deviceobj["number"] +'</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["user"] + '</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["password"] + '</TD>';
if (deviceobj["name"]) {
newcontent=newcontent + '<TD>' + deviceobj["name"] + '</TD>';
}
else {
newcontent=newcontent + '<TD> </TD>';
}
newcontent=newcontent + '<TD>' + deviceobj["description"] + '</TD>';
newcontent = newcontent + "</TR>";
}// end for
// Replace old content with new content
$('#Searchresult').html(newcontent);
}//end if
},
error: function(request, textStatus, errorThrown) {
console.log(textStatus);
},
complete: function(request, textStatus) { //for additional info
//alert(request.responseText);
console.log(textStatus);
}
});
// Prevent click eventpropagation
return false;
}//end pageselectCallback()
I'm not sure how to go about troubleshooting this.
Any suggestions would be appreciated

I decided to reduce the number of records returned to one per page... to narrow down the offending record.
now that I know which record it is, i should be able to resolve problem.

Related

Laravel: Variables showing as undefined when appending to table

I'm retrieving data from a database via AJAX GET call, ater succesfull response I print the data by appending an html template to my table, I am getting the results back all right (in JSON format) but when appending them to table they all appear as undefined:
Here is my controller method:
public function index()
{
$reviews = Review::all();
return response()->json([
'success' => 'Todas las opiniones recogidas',
'reviews' => $reviews,
]);
}
This is my JQuery code where I append the results, I'm fairly certain the error is in here:
$.ajax({
async: true,
url: '/reviews',
type: 'GET',
dataType: 'JSON',
success: function (data) {
$('.row[data-link=' + linked_entry + ']').remove();
$.each(data, function (index, item) {
var reviews_row = '<tr class="row" data-link="reviews">';
reviews_row += '<td>' + data.body + '</td>';
reviews_row += '<td>' + data.author + '</td>';
reviews_row += '<td>' + data.site + '</td>';
reviews_row += '<td style="text-align:center;"><input type="checkbox" name="isVisible" '+(data.isVisible ? 'checked' : '')+'></td>';
reviews_row += '</tr>';
$('.entry_table_container[data-link=' + linked_entry + ']').append(reviews_row);
});
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Change this:
$.each(data, function (index, item) {
To this:
$.each(data.reviews, function (index, item) {
and then:
item.body, item.author etc in your loop as one of the other contributors mentioned

Loading Ajax Data Dynamically

I have a bunch of jQuery functions which gets JSON data from a MySQL database and displays it on certain pages within my application.
i have about 15 of these functions that look similar to the below and i would like to tidy them up and convert them to one major function which returns data based on the variables passed to the function. IE getdata(subscriptions) would display the subscriptions.
My issue is i'm not sure how to pass the column names to the function from the ajax query and remove the value.column-name from the function.
Example function from application
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value+
'</td><td>' + value.subscription_name +
'</td><td>' + value.subscription_cycle +
'</td><td>' + value.subscription_cost +
'</td><td>' + value.subscription_retail +
'</td><td>' + value.subscription_profit +
'</td><td>' + value.subscription_margin +
'</td><td>' + value.subscription_markup +
'</td></tr>';
});
$('#subscription-results').html(trHTML);
},
});
}
Any help is very much appreciated as i'm fairly new to jQuery
You can refer to this code:
function GetSubscriptions(){
$.ajax({
url: 'jsondata.php',
type: 'POST',
dataType:'json',
timeout:9000,
success: function (response)
{
$('#subscription-results').html(parseColumns(response));
},
});
}
function parseColumns(columns) {
var html = '';
if (Object.prototype.toString.apply(columns) === '[object Array]') {
$.each(columns, function(key, value) {
html += parseColumn(value);
})
} else {
html += parseColumn(columns);
}
function parseColumn(column) {
var trHTML = '<tr><td>' + column + '</td>';
for (var key in column) {
trHTML += '<td>' + column[key] + '</td>'
}
trHTML += '</tr>';
return trHTML;
}
return html;
}

Uncaught ReferenceError: x is not defined at HTMLTableRowElement.onclick

I've looked around for a solution but I might just be missing something really obvious because they don't solve my issue. I am no JS wiz at all, just a disclaimer.
I have an ASP project where JavaScript calls some C# code some times. I start my code with this:
window.onload = function () {
LiveSearch();
getCredentials();
getAllUsers();
getIsAdmin();
};
All of these functions work just fine. But the one of interest is getAllUsers() because it contacts the backend via an AJAX call to get some data to fill in a table.
function getAllUsers() {
var result_body = "";
$.ajax({
type: 'GET',
url: '/Home/GetAllUsers',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(""),
success: function (users) {
PushToScope("users", users);
var dict = scope[2];
if (dict.key.length > 0) {
for (var key in dict.value) {
result_body += '<tr onclick="getClickedUserObject(' + dict["value"][key].Initials + ')\">';
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Name + '</td>'
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Title + '</td>'
result_body += '<td class=\"col-xs-4\">' + dict["value"][key].Department + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].PrivatePhone + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkEmail + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkPhoneLandline + '</td>'
result_body += '<td style=\"display: none\">' + dict["value"][key].WorkPhoneMobile + '</td>'
result_body += '</tr>';
}
} else {
result_body += '<tr>';
result_body += '<td style=\"col-xs-12\"><b>No Data. Try again, or Contact IT Support.</b></td>';
result_body += '</tr>';
}
$('#result-table').html(result_body);
}
});
}
Like I said, the above works, but the problem comes forth when I click an element in my table. "getClickedUserObject()" below:
function getClickedUserObject(lettercode) {
if (lettercode != undefined) {
var users = scope[2];
var user = users["value"][lettercode];
$('#result-title').html(user.Title);
$('#result-name').html(user.Name);
$('#result-department').html(user.Department);
$('#result-email').html('' + work.WorkEmail + '');
$('#result-work-mobile').html(user.WorkPhoneMobile);
$('#result-work-landline').html(user.WorkPhoneLandline);
$('#result-private-mobile').html(user.PrivatePhone);
if (lettercode == scope[0]) {
$("#HidePrivate").show();
$("#HidePrivate").disabled = false;
$("#HidePrivate").checked = user.HiddenPrivatePhone;
} else {
$("#HidePrivate").hide();
$("#HidePrivate").disabled = true;
}
}
return false;
}
This function never fires, instead I get the error in the title, saying that whatever lettercode I would get from clicking a row is not defined. This is odd to me because looking in the Google Chrome inspector I see this:
So what gives?
I'm not familiar with your function, but maybe the argument should be a string? Looks like you don't have any quotes around it in the function call.
Like so:
result_body += '<tr onclick=\"getClickedUserObject(\'' + dict["value"][key].Initials + '\')\">';

Selecting a row in a html table

I am trying to select a row in a table I have created and need use the values. The issue I am having is I created it using doms in javascript and got the values from a stored procedure which then populates the table.
so i use a simple div with an id -
<div id="Tab1" class="tab-pane fade in active"></div>
to create the table and populate it i use an ajax call -
function GetcarData() {
$.ajax({
type: "post",
data: JSON.stringify({
price: slidval,
}),
url: "/index.aspx/GetData",
dataType: "json",
contentType: "application/json",
success: function (object) {
responseData(object);
},
complete: function (object) {
},
error: function (object) {
}
});
}
function responseData(object) {
var stringed = JSON.stringify(object.d)
var arr = JSON.parse(stringed);
var i;
var out = "<table id='table' class='table table-striped'>";
var rowHeader = $("<tr></tr>").appendTo(out);
out += "<td><font size='4'>Make</font></td>";
out += "<td><font size='4'>Model</font></td>";
out += "<td><font size='4'>Version</font></td>";
out += "<td><font size='4'>Engine</font></td>";
out += "<td><font size='4'>(AV)Price new</font></td>";
out += "<td><font size='4'>(Av)Price used</font></td>";
out += "<td><font size='4'>Image</font></td>"
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Make +
"</td><td>" +
arr[i].Model +
"</td><td>" +
"£" + arr[i].version +
"</td><td>"+
arr[i].Engine_size +
"</td><td>" +
"£" + arr[i].price_new +
"</td><td>" +
"£" + arr[i].price_used +
"</td><td><img src="+arr[i].image_url+" width='150' height='100'>" +
"</td></tr>";
}
out += "</table>";
document.getElementById("Tab1").innerHTML = out;
}
Now the issue I have is I cant seem to select a row.
I tried
("#table tr").click(function(){
alert("selected");
});
but that did not work.
Anyhelp would be appreciated
You created a set of elements that weren't in the DOM when page and were only added after initial DOMContentLoaded
To listen for events on elements that are dynamically added, removed via JavaScript DOM manipulations, you need to use slightly different event listener.
$(document).on('%eventName%', '%selector%', function() { // do your stuff });

Displaying data from json file

I'm trying to get content from a json file, but until now I get nothing.
I have the status connection == 200 and I can see the content in the chrome console
but I get nothing when I try to display the data to html table, but when I use the same jquery code with api from another service like import.io things works fine.
Can you tell me what am I doing wrong?
This api is from kimonolabs.
$(document).ready(function () {
var tabel = '<table><THEAD><caption>Calendário</caption></THEAD>';
tabel += '<th>' + 'Hora' + '</th>' + '<th>' + 'Equipas' + '</th><th>' + 'jornda' +
'</th><th>' + 'Data' + '</th>';
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/1dm6b',
dataType: 'json',
success: function (data) {
console.log(data);
$('#update').empty();
$(data.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td>' + '<td>' + this.golos + '</td></tr>';
}); //each
tabel += '</table>';
$("#update").html(tabel);
} //data
}); //ajax
}); //ready
According to JSON structure you should iterate over data.results.m_Marcadores array:
$(data.results.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td><td>' + this.golos + '</td></tr>';
});
Another problem. In header of the table you setup 4 colums, but in loop you are creating only two of them. Number of header columns should be the same as other row td.
Also you need to wrap th elements in tr. For example, fixed table header:
var tabel = '<table>' +
'<THEAD><caption>Calendário</caption></THEAD>' +
'<tr>' +
'<th>Hora</th><th>Equipas</th><th>jornda</th><th>Data</th>' +
'</tr>';
Demo: http://jsfiddle.net/onz02e43/

Categories

Resources