Jquery error in fetching json array - javascript

members = $.parseJSON(members);
$.each(members, function (i, item) {
$.ajax({
type: "POST",
url: "'.base_url(" / panel / listNottifications ").'/'.$id.'/" +
valueSelected,
data: {
list: item[i]
},
dataType: "json",
success: function (data){
var w = $("#Eventprogress").width() + perRequest + "%";
$("#Eventprogress").attr("data-original-title", w);
$("#Eventprogress").animate({
width: w
}, 600);
}
});
});
Members is an returned json var from get request equal as example
["11111|22222|3333|4444|555555"]
the error i got in fetching is ..
Uncaught SyntaxError: Unexpected token |
any ideas how to fetch the returned data ?
Thanks

this is not a JSON response, the json response should be an object with key, value syntax or an array or such objects,
this is neither one of them, but anyway you can check if the JSON is valid in Json Link

Related

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON

I need to append this div to another div , but it give me this error :
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
This is my javascript code:
var str = {'message': message,'text': text};
$.ajax({
type: "POST",
url: "api/reply",
data: str,
dataType: "json",
cache: false,
success: function(response)
{
var respons = jQuery.parseJSON(response);
var type = respons.status
if (type == 'success') {
$("<div></div>").html(respons.message).appendTo("#messages");
}
else
{
toastr.error(respons.message)
}
}
})
Simply change
var respons = jQuery.parseJSON(response);
to
var respons = response;
Explanation:
If the configuration of your AJAX call is having dataType: json you'll get a JavaScript object so it's no longer necessary to use JSON.parse().
This is a hackish and unorthodox way of parsing JSON, but if you still want to use JSON.parse() from an AJAX call or simply on JSON that is already parsed and isn't a string, you can use JSON.stringify() inside it:
var respons = JSON.parse(JSON.stringify(response));
Problem is you're not parsing a string, you're parsing an already parsed object.
the values in your object seem to be undefined.
change
var str = {'message': message,'text': text}; to
var str = {message: 'message',text: 'text'};

How to parse JSON with multiple rows/results

I don't know if this is malformed JSON string or not, but I cannot work out how to parse each result to get the data out.
This is the data.d response from my $.ajax function (it calls a WebMethod in Code Behind (C#)):
{"Row":[
{"ID1":"TBU9THLCZS","Project":"1","ID2":"Y5468ASV73","URL":"http://blah1.com","Wave":"w1","StartDate":"18/06/2015 5:46:41 AM","EndDate":"18/06/2015 5:47:24 AM","Status":"1","Check":"0"},
{"ID1":"TBU9THLCZS","Project":"2","ID2":"T7J6SHZCH","URL":"http://blah2.com","Wave":"w1","StartDate":"23/06/2015 4:35:22 AM","EndDate":"","Status":"","Check":""}
]}
With all the examples I have looked at, only one or two showed something where my 'Row' is, and the solutions were not related, such as one person had a comma after the last array.
I would be happy with some pointers if not even the straight out answer.
I have tried various combinations of response.Row, response[0], using $.each, but I just can't get it.
EDIT, this is my ajax call:
$.ajax({
url: "Mgr.aspx/ShowActivity",
type: "POST",
data: JSON.stringify({
"ID": "null"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblResErr').html('<span style="color:red;">' + thrownError);
}
});
At the moment I have just been trying to get ID1 value and ID2 value into the console.
EDIT (Resolved): Thanks to YTAM and Panagiotis !
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
data = JSON.parse(data);
console.log(data);
}
Now the console is showing me an array of two objects, and now I know what to do with them !!
First you have to parse the string with JSON.parse
var data= JSON.parse(rowData);
Then you will get object like given below,
data = {
"Row": [
{
"ID1":"TBU9THLCZS",
"Project":"1",
"ID2":"Y5468ASV73",
"URL":"http://blah1.com",
"Wave":"w1",
"StartDate":"18/06/2015 5:46:41 AM",
"EndDate":"18/06/2015 5:47:24 AM",
"Status":"1",
"Check":"0"
},
{
"ID1":"TBU9THLCZS",
"Project":"2",
"ID2":"T7J6SHZCH",
"URL":"http://blah2.com",
"Wave":"w1",
"StartDate":"23/06/2015 4:35:22 AM",
"EndDate":"",
"Status":"",
"Check":""
}
]}
Here I am giving two options either direct retrieve data from data variable or through loop.
data.row[0].ID1
data.row[0].Project
data.row[0].ID2
and so on
OR
use loop,
var result = json.row;
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
}
}
Hope this helps.
you may be getting a json string from the web method rather than an actual JavaScript object. Parse it into a JavaScript object by
doing
var data = JSON.parse(response);
then you'll be able to iterate over data.Row

Not able to get value from JSON object using AJAX call

I have sample code for getting json value from servlet through Ajax call.
In success function I am getting response. It is showing Object : [{"userId":"dfeterter"}] in console.
But I am not able to get value of userId
$.ajax({
url: "Registration",
dataType: "json",
data: {
jsonbhvalue: bhvalue,
jsonuid: uid,
jsonpassword: password,
jsonfname: fname,
jsonlname: lname,
jsonmobile: mobile,
jsonemailid: emailid
},
success: function(variable) {
var obj = $.parseJSON(JSON.stringify(variable));
console.log("Object : " + obj);
console.log("cval : " + obj.userId)
});
});
Thanks To #RobertoNovelo.
You have to remove $.parseJSON as you are already setting JSON by ajax configuration. dataType: "json"
You need to use:
obj[0].userId
Your response is array of objects.
That is because your object is an array. You should either use obj[0] or assign the array to a variable and then use its members
objs = [{"userId":"dfeterter"}]
firstobj = objs[0]
console.log("Object : " + objs);
console.log("cval : " + objs[0].userId);
console.log("cval : " + firstobj.userId);

Passing an array to a web method in Javascript

I am currently trying to pass an array that I have created in Javascript to my webmethod in my aspx.cs.
Heres what I have:
JAVASCRIPT
function callServer(requestMethod, clientRequest) {
var pageMethod = "Default.aspx/" + requestMethod;
$.ajax({
url: pageMethod, // Current Page, Method
data: JSON.stringify({ request: clientRequest }), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 60000, // AJAX timeout
success: function (result) {
ajaxCallback(result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
function myButtonCalls()
{
var values=[];
values[0] = "Hello";
values[1] = "goodbye";
callServer("myMethod", values);
}
ASPX.CS
[WebMethod]
public static string myMethod(string[] request)
{
return "This is test";
}
It fails before it even gets to my web method. I know this code works for regualr strings but The ajax code that uses JSON doesnt see to want to work with arrays.
Any ideas of what i need to change?
Thanks
In the aspx.cs, I needed to accept with type list not array. Thanks for the comments!

Array of Objects via JSON and jQuery to Selectbox

I have problems transferring a dataset (array of objects) from a servlet to a jsp/jquery.
This is the dataset sent by the servlet (Json):
[
{aktion:"ac1", id:"26"},
{aktion:"ac2", id:"1"},
{aktion:"ac3", id:"16"},
{aktion:"ac4", id:"2"}
]
The jsp:
function getSelectContent($selectID) {
alert('test');
$.ajax({
url:'ShowOverviewDOC',
type:'GET',
data: 'q=getAktionenAsDropdown',
dataType: 'json',
error: function() {
alert('Error loading json data!');
},
success: function(json){
var output = '';
for (p in json) {
$('#'+$selectID).append($('<option>').text(json[p].aktion).attr('value', json[p].aktion));
}
}});
};
If I try to run this the Error ('Error loading json data') is alerted.
Has someone an idea where the mistake may be?
Thanks!
If the error function is running, then your server is returning an error response (HTTP response code >= 400).
To see exactly what is going on, check the textStatus and errorThrown information that is provided by the error callback. That might help narrow it down.
http://api.jquery.com/jQuery.ajax/
The way you are setting the data parameter looks a bit suspect (notice JSON encoding in my example below). Here is how it would look calling a .Net asmx
$.ajax({
url: "/_layouts/DashboardService.asmx/MinimizeWidgetState",
data: "{'widgetType':'" + widgetType + "', 'isMinimized':'" + collapsed + "'}"
});
Also the return data is by default placed in the .d property of the return variable. You can change this default behavior by adding some ajax setup script.
//Global AJAX Setup, sets default properties for ajax calls. Allows browsers to make use of native JSON parsing (if present)
//and resolves issues with certain ASP.NET AJAX services pulling data from the ".d" attribute.
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
},
dataFilter: function(data) {
var msg;
//If there's native JSON parsing then use it.
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
//If the data is stuck in the "."d" property then go find it.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, textStatus, errorThrown);
}
});

Categories

Resources