I'm having some problems with JSON.Parse in my code and I cant find the reason of this I have a function which call two ajax functions, one on the start and another on the success function . Its working fine but when I'm try to parse the second one response the code breaks without giving any error and the real mystery is JSON.parse(object); dosent give any problem but when I use a variable to store the result like this var list =JSON.parse(object); my code broke and I dont what is the reason behind this my current code is given below
function getData()
{
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData",
data: JSON.stringify({ data: data})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = JSON.parse(response.d);
var temp = 0;
for (var i = 0; i < result.length; i++) {
if (result[i].data > 1) {
var subList = JSON.parsegetFullData (result[i].id));
}
}
});
}
function getFullData (id) {
var sublist;
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData2",
data: JSON.stringify({ id: id }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
return response.d;
}
});
}
any thought will help a lot
When you use $.ajax with dataType:"json", the response is already parsed for you. And there doesn't seem to be a reason to try to parse response.d.
Simply use
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData",
data: JSON.stringify({ data: data})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
for (var i = 0; i < results.length; i++) {
console.log(results[i].id, results[i].LastName);
Related
I try to pass parameters into aspx.cs page from js script. When I omit:
contentType: "application/json; charset=utf-8"
in ajax request I get by Request.Form["ORDER"] sth like {%7b%22ORDER_ID%22%3a126333%7d}. It means that this data comes to aspx.cs, but it is not decoded.
When I add contentType I get nothing in request.
Below I attach request.
It is important to read parameters from Request.Form["ORDER"] in aspx.cs;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ORDER_ID: orderKeyId }),
dataType: "json",
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});
According to #Rory McCrossan comment, below ajax state worked:
$.ajax({
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: "ORDER_ID=" + encodeURIComponent(orderKeyId),
url: sUrl,
success: function (data) {
var s = 0;
},
error: function () {
var s = 0;
}
});
Im new in js and razor,part of my code should be repeated and this imposed more lines of code to my project,it could be nice if i can make it reusable,for example Ajax,where should i create a ajax to a specific URL to just call it when i need?in a separated razor file?in the following code,i have two click events and my ajax call and url is repeating,i want to get rid of this repeat:
function seriesClick(e) {
var _clicketBarChart = e.series.categoryField;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "name": _clicketBarChart }),
success: function (result) {
faultstatChart(result);
}
});
function changeEvent(e) {
var _clicketCellGrid = e.categoryCell;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"name": _clicketCellGrid }),
success: function (result) {
faultstatChart(result);
}
});
}
You have to create single method that can handle two situations, please refer to this example (based on your):
var ajaxHandler = function(targetName) {
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("faultstatistics","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"name": _clicketCellGrid }),
success: function (result) {
faultstatChart(result);
}
});
}
var seriesClick = function(e) {
var targetName = e.series.categoryField;
ajaxHandler(targetName);
}
var changeEvent = function(e) {
var targetName = e.categoryCell;
ajaxHandler(targetName);
}
I get a response like this:
{
"data": [
"http:\/\/www.domain.com.br\/anunciantes\/jorgediaz.y.com.r\/26\/img1.jpg",
"http:\/\/www.domain.com.br\/anunciantes\/jorgediaz.t.com.r\/26\/img2.jpg"
]
}
I have tried:
$.ajax({
url: "/imovel/recuperar_fotos",
datatype: 'JSON',
contentType: 'JSON',
success: function (data) {
var i = 0;
while(i < 3)
{
alert(data[i]);
i++;
}
}
});
and also data[0][i] doesn't work.
It is because you are receiving an object that has a data property that is an array. Therefore you could iterate over response.data (or data.data, following your code naming).
Here you have 3 ways to iterate over an array (and avoid the while loop)
Using array's forEach method
$.ajax({
url: "/imovel/recuperar_fotos",
datatype: 'JSON',
contentType: 'JSON',
success: function (response) {
var photos = response.data;
photos.forEach(function(photo) {
console.log(photo);
})
}
});
Using the for ... in
$.ajax({
url: "/imovel/recuperar_fotos",
datatype: 'JSON',
contentType: 'JSON',
success: function (response) {
var photos = response.data;
for (var i in photos) {
console.log(photos[i]);
}
}
});
Using the classig for loop
$.ajax({
url: "/imovel/recuperar_fotos",
datatype: 'JSON',
contentType: 'JSON',
success: function (response) {
var photos = response.data;
for (var i = 0; i < photos.length; i++) {
console.log(photos[i]);
}
}
});
Try this
$.ajax({
url: "/imovel/recuperar_fotos",
contentType: 'application/json',
success: function(res) {
for (i = 0; i < res.data.length; i++) {
alert(res.data[i]);
}
}
});
// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you
this may sound very easy to few of you, but i am not able to figure out why I am not able to get the return value, even after chceking many posts :(
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
Now if I call var count = getMessageCount();
it gives me undefinted :(
while inside the method count is coming correct, i.e. service is working fine.
I agree with the first line by ahren that
'That's because the $.ajax() call is asynchronous.'
you could try adding a setting - async:false
which is true by default. This makes the call synchronous.
you can edit your code as :
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
} //success
});
return count;
}
That's because the $.ajax() call is asynchronous.
If you edit your code to something like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if(typeof callback === "function") callback(count);
} //success
});
}
Then when you call it:
getMessageCount(function(count){
console.log(count);
});
use a callback:
call function like:
getMessageCount(function(result) {
//result is what you put in the callback. Count in your case
});
and the other like:
function getMessageCount(callback) {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
if (callback) {
callback(count);
}
} //success
});
}
Why you don't just pass it to a function?
function getMessageCount() {
var count;
$.ajax({
type: "POST",
url: "http://localhost:43390" + "/services/DiscussionWidgetService.asmx/GetMessageCount",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
count = data.d;
countMessages(count);
} //success
});
}
function countMessages(counted) {var counted = counted; console.log(counted);}
function ajax_call(url,data){
return $.ajax({ type: "POST",
url: url,
data: data,
async:false,
success: function(status){
}
}).responseText;
}
Now you will get the response text from server side via ajax call