Unexpected identifier on JSON Eval function at Object.success - javascript

i got error on the line eval it says this is na error eval('result = ' + data.d);
this is my json format. i want may data to set pagination limit in 5 per page but when i increase the data. its show all. i want to limit the data per 5 data per page there is variable pagesize = 5 but its not working because of the eval() error
{
"d": [
{"FChaOnline":"0","FChaName":"Testing10"},
{"FChaOnline":"1","FChaName":"Testing1"},
{"FChaOnline":"0","FChaName":"Testing28"}
]
}
Uncaught SyntaxError: Unexpected identifier
at Object.success (JRGMain.js:191)
at Object.resolveWith (jquery-1.5.1.js:862)
at done (jquery-1.5.1.js:6591)
at XMLHttpRequest.callback (jquery-1.5.1.js:7382)
$.ajax({
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: './WebService/GetUserFriendList',
data: '{"PageNo" : "' + PageNo + '", "PageSize" : "5", "UserID" : "' + UserID + '"}',
success: function(data) {
var result, TotalItemCount, list;
eval('result = ' + data.d);
TotalItemCount = result.TotalItemCount;
list = result.List;
PageCount = Math.ceil(TotalItemCount / 5);
var html = '';
if (list.length > 5) {
$.each(list, function(index, obj) {
if (obj.FChaOnline == '0') {
html += '<li class="off">' + obj.FChaName + '<span class="state"><img src="./Images/Icon/off_icon.gif" alt="on"></span></li>';
} else {
html += '<li class="on">' + obj.FChaName + '<span class="state"><img src="./Images/Icon/on_icon.gif" alt="on"></span></li>';
}
});
} else {
html = '<li class="nothing">There are no friends registered.</li>';
}
$('#relation-list').html(html);
$('#page-no').text(PageNo);
$('#total-page').text(PageCount);
},
error: function(data) {
alert(data.status + ' : ' + data.statusText + ' : ' + data.responseText);
}
});

Related

MySQL AJAX PHP Notification Module

Can anyone help me with this code? I would like to convert this async ajax to sync ajax. How do I do it? Here is the code that is written below. The system just lags when I leave it for 20 mins without even doing anything. So, maybe the problem is within the code.
function addmsg20(type, msg, data) {
$('#display20').html(data);
}
function waitForMsg20() {
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
var data = JSON.parse(data);
if(data.data.length > 0){
var res = data.data;
var printed = "<ul class='menu'>";
$.each(res, function(k, v){
var empext = v.employee_ext;
if(empext == null){
empext = "";
}else{
empext = v.employee_ext;
}
printed += "<li>" +
"<a href='#'>" +
"<h4>" +
" "+v.employee_fname + " " +
v.employee_mname+" "+v.employee_lname+" " +empext+ "<small>" +
v.status_desc+ "</small>" +"</h4>" +
"<p>" + v.subj_name + "</p>" +
"</a></li>";
})
printed += "</ul>";
}else{
printed = "";
}
addmsg20("new", data.count, printed);
setTimeout(
waitForMsg20,
1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg20("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg20,
15000);
}
});
};
$(document).ready(function() {
waitForMsg20();
});
I am completely new to Javascript and/or AJAX so I really need help about this.
To make the AJAX call synchronous, just set async to false:
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: false,
cache: false,
timeout: 50000,
.
.
.

JSON.stringify output to display in table

I POST my table data using ajax in database. Now I want to get back when I give click the open button.
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
debugger;
//var p = JSON.stringify('[' + data + ']');
// alert(p.GetPageInfoResult[0])
//var k = data.main[0];
//alert(data.length);
//var jsonObj = $.parseJSON('[' + data + ']');
//alert(JSON.parse(data));
var jsonPretty = JSON.stringify(JSON.parse(data), null, 2);
},
error: function () {
alert('Error');
When I give my file name I want to display my pageinfo. I get data like
[{"main":{"sub":[],"tittle":"oops","startvalue":"21","stopvalue":"45","status":"","accumalated":"","comment":""}}]
You have not cleared where you want place your resultant Json. Below is that Success result placed in div having table . It is just a sample you may change as per your requirement:
function OnSuccess(response) {
debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var page = xml.find("Table");
var row = "";
$('#popupdiv tbody').html('');
page.each(function () {
var page = $(this);
row = " " + page.find("tittle").text() + " " + page.find("startvalue").text() +
" " + page.find("stopvalue").text() + " " + page.find("status").text() +
" " + page.find("accumalated").text() + " " + page.find("comment").text() + "";
$('#popupdiv tbody').append(row);
});
}

AJAX Jquery request error

I'm getting a "Uncaught SyntaxError: Unexpected end of input" error, when i take out the below snippet the error goes away. Maybe its because ive been up all night but i cant for the life of me find the issue. Can anyone please shed some light?
$.ajax({
url: "scripts/getWorkerPendingJobs.php",
type: "get",
data: {uid: userId},
success: function(dataa) {
var daa = JSON.parse(dataa);
var amtt = parseInt(daa.length);
var htmll = "";
if (amtt > 0) {
$.each(daa, function(indexx) {
var status;
var acc = daa[indexx].accepted.toString();
if (acc == 1) {
status = "Pending";
}
if (acc == 2) {
status = "Accepted";
}
htmll += '<li><img src="./noimage.png" /><h3>' + daa[indexx].dateadded + ' | ' + daa[indexx].shortdesc + '</h3><h2>Status : ' + status + '</h2><p>' + daa[indexx].description + '</p></li>';
$('.worker-applied-jobs').html(htmll).promise().done(function() {
$(this).listview("refresh");
});
});
} else {
$('.worker-applied-jobs').html('<p style="margin-left:10px;">You have not applied for any jobs.</p>');
}
}
});

How do I get specific value key pair in ajax javascript for datatype json?

I want to get the value of "status" from data in the code below,
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
$("<span class=\"label label-success\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});
Following is some part of the console.log result:
key: 2014-11-11
value: {"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
I want get the value of "status" i.e 0, as seen in the above result, in order to include it in the for loop (for (var key in data) {...}) to change the class 'label-success' to 'label-failure' if the status is 0. Could you help me?
Hello maybe I am wrong but
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
returns the whole data object in string format when you say JSON.stringify(data);
You want the value which is returned when you give data a specific key to read values from:
console.log('key: ' + key + '\n' + 'value: ' + data[key]);
EDIT: Im not sure if data[key] will return a [object Object]... if it does try JSON.stringify(data[key])
I would also suggest Itterating through data with the
for(var i = 0; i < data.length; i++){}
this makes it readable and is measured the most performant way of extracting data.
EDIT nr 2:
This is your object:
{"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
this is a bit nested, so try to get an overview of what you have:
data = {
"2014-11-11": [],
"2014-11-12": []... }
This object has a length method that returns the length of your object. this allows you to itterate over the Data Object will give you "2014-11-11" as key and with this key you can access your values like this: data[key] this will return your array...to read data from your array you will have to itterate again data[key][i]... now you can read the data inside each array element like this
data[key][i]["status"];
Hope this helped somehow... cant be bothered to write all this code :D
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
var status = data['status'];
var klass = status === 0 ? 'label-failure' : 'label-success';
$('<span class="label '+klass+'">' + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
Try this code instead.
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
for (var i in data[key]) {
$("<span class=\"label " + ((data[key][i] === "0") ? "label-failure" : "label-success") + "\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
}
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});

Passing JSON to controller action issue

I have the following javascript.
Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null?
I checked the javascript and the variable "cnt" is 1 not 2.
Why would that be?
Malcolm
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';
var ing = "";
var cnt = 0;
$("#ingredients tr.ingredientdata").each(function () {
if ($("td.ingredient", this).text() != "") {
ing += '{ "IngredientName": "' + $("td.ingredient", this).text() + '",';
ing += '"Units": ' + $("td.units", this).text() + ',';
ing += '"Measure": "' + $("td.measure", this).text() + '"} ,';
}
cnt = cnt + 1;
});
alert(cnt);
if (ing != "") {
jsontext += '"Ingredients": [';
ing = ing.substring(0, jsontext.length - 1);
jsontext = jsontext + ing;
jsontext += ']';
}
jsontext += '}';
var json = eval('(' + jsontext + ')');
//var json = { Field: 1 };
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
I would recommend a refactoring of your javascript as it would help you identify the errors more easily. Also checkout with FireBug the actual JSON request being sent to the controller:
$("#Save").click(function () {
var ingredients = $('#ingredients tr.ingredientdata').map(function(index, element) {
return {
ingredientName: $('td.ingredient', element).text(),
units: $('td.units', element).text(),
measure: $('td.measure', element).text()
};
});
var json = {
RecipeTitle: $('#recipetitle').val(),
CategoryID: $('#category').val(),
PrepTime: $('#prepTime').val(),
PrepTimePeriod: $('#lstPrepTime').val(),
CookTime: $('#cookTime').val(),
CookTimePeriod: $('#lstCookTime').val(),
Rating: $('#rating').val(),
Method: $('#method').val(),
Ingredients: ingredients
};
$.ajax({
url: '/Recipe/Save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function () {
//alert("DONE!!");
}
});
});

Categories

Resources