How to access json response that have the following format - javascript

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]);
}
}
});

Related

Html for response when i want a string

I have the function below:
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
const dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: dataValue,
contentType: "application/json: charset = utf8",
dataType: "text",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
fail: function () {
alert('Failed')
}
});
}
And i have this on my server:
[WebMethod]
public static string GenerateHtmlFromMarkdown(string markdownFormat)
{
string htmlFormat = "Some text";
return htmlFormat;
}
I have on response html code, not the string that i want. What am I doing wrong?
And if i change the "dataType: json" it doesn't even enter either the success nor fail functions
Your data type of ajax must be json like this
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(dataValue),
dataType: "json",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
error: function () { alert("Failed"); }
});
}
try with this.
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var obj={};
obj.markdownFormat=markdownFormat;
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
document.getElementById("generatedPreview").innerHTML = response.d;
},
failure: function () {
alert('Failed')
}
});
}

ajax send 2d array to action method error - asp.net mvc

i want to send 2d array from javascript file to action method.
My javascript function
function _tbdata() {
var dataarr = [];
for(var i = 0; i<svarr.length; i++)
{
var trangthai = $("input[name='" + svarr[i] + "']:checked").val();
var lydo = $("#" + svarr[i]).val();
dataarr[i] = new Array(2);
dataarr[i][0] = trangthai;
dataarr[i][1] = lydo;
}
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(dataarr ) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
And my controller
[HttpPost]
public ActionResult testMethod(List<List<string>> info)
{
return RedirectToAction("Index");
}
And when i debug in chrome, i got error
POST http://localhost:56602/DiemDanh/testMethod 500 (Internal Server
Error)
Sorry about my Enligsh is bad, Hope suggest from everybody!!!
I think you should change your javascript. Two dimensional array sholud be [[]]
I've write an example for your code. It works fine.
function Test() {
var dataarr = [[]];
for (var i = 0; i < 1; i++) {
dataarr[i][0] = "A" + i.toString();
dataarr[i][1] = "B" + i.toString();
}
var model = JSON.stringify(dataarr);
$.ajax({
url: '/Home/testMethod',
data: model,
type: "POST",
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
Change your ajax like this.
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(ngay) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
change your method parameter with string multi dimensional array it will work because list of list strings parameter won't work it'll not accepting 2d array
[HttpPost]
public ActionResult testMethod(string [][] info)
{
return RedirectToAction("Index");
}

How to get json in javascript or ajax

I have json data
how can i get this data using javascript
thanks :)
this is my code
var getJsonData = function(uri,callback){
$.ajax({
type: "GET",
dataType: "jsonp",
url: uri,
jsonpCallback: 'response',
contentType: "application/json",
success: function(json){
console.log(json);
callback(json);
}
});
}
var uri = pbxApi+"/confbridge_participants/conference_participants.json?cid="+circle;
getJsonData(uri, function(res){
}
var uri = pbxApi+"/confbridge_participants/conference_participants.json?cid="+circle;
getJsonData(uri, function(res){
var data = JSON.parse(res);
for(var objectIndex=0; objectIndex < data.length; objectIndex++){
var tempObject = data[objectIndex];
var id = tempObject.id;
var uid = tempObject.uid;
....
var updated_at = tempObject.updated_at;
}
}
you don't need use jsonp to get json data,
var getJsonData = function(uri,callback){
$.ajax({
type: "GET",
dataType: "json",
url: uri,
contentType: "application/json",
success: function(json){
console.log(json);
callback(json);
}
});
}
var uri=pbxApi+"/confbridge_participants/conference_participants.json?cid="+circle;
getJsonData(uri, function(res){
console.log(res
}

How to get return value in a function with inside Ajax call - JQuery

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

JSON.Parse causes error in javascript

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);

Categories

Resources