I have ajax call to JSON object:
$.ajax({
type: "GET",
url: 'file.json',
dataType: "JSON",
success: function(answer) {
alert(answer);
},
error: function(answer) {
alert("Error")
}
});
and a JSON file:
{
"saveTime": 1396522039
}
I want to get alert not a value of "saveTime" but volue of object. I mean the result of alert must be exactly "saveTime".
Appreciate your help.
Try this for get property name
$.ajax({
type: "GET",
url: 'file.json',
dataType: "JSON",
success: function(answer) {
for (prop in answer) {
alert(prop); // alert property name => saveTime
}
},
error: function(answer) {
alert("Error")
}
});
this will help you
var keys = Object.keys(answer); // This will return all keys of an object as an array.
now use it as
alert(keys[0]);
Try this you get saveTime:
$.ajax({
type: "GET",
url: 'file.json',
dataType: "JSON",
success: function(answer) {
$.each(answer, function(key, val) {
console.log('Key: '+key+' Val: '+val);
});
},
error: function(answer) {
alert("Error")
}
});
Related
I have a variable in a javascript function which needs to be sent to the controller. This is the code in the javascript function.
var testString = "Test";
$.ajax({
type: "POST",
url: "#Url.Action("GetJavaScriptString")",
dataType: "json",
data: JSON.stringify(testString),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
And this is the controller method
public ActionResult GetJavaScriptString(string data)
{
return null;
}
The variable "data" in the GetJavaScriptString method remains null.
You need to send a name/value pair when the name matches the name of your parameter
var testString = "Test";
$.ajax({
type: "POST",
url: "#Url.Action("GetJavaScriptString")",
dataType: "json",
data: { data: testString }, // change this
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
Note that you do not need JSON.stringify(), but if you did it would be data: JSON.stringify({ data: testString }), and you would need to the contentType: 'application/json', option
I have a DoughnutChart chart and I would like to change the color of its parts regarding color hexa-codes saved in the database I used this Ajax method to get the color string by invoking an action method that returns JSON Result ,
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// return data;
},
error: function (data) {
// return "Failed";
},
async: true
});
but instead of receiving the string I received Object {readyState: 1} in the console window
However, I can find the color value stored in ResponseText element.I need your help in how can I get the color value as string.
EDIT :
To make things more clear that's where I would like to invoke the ajax method to receive the color string then I will be able to push in the chart color array .
getColorArray: function getColorArray(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
console.log(this.getcolors("Risk"));
//colors.push(this.getcolors(categories[i]));
}
return colors;
}
Why your code is like this?
success: function (data, textStatus, jqXHR) {
// return data;
},
Did you use it?
success: function (data, textStatus, jqXHR) {
console.log(data);
}
Ok, i got it. When you use an ajax request your will work with asynchronous data, to do this you need return a promise in your method. Please, try to use the code below.
getcolors: function getcolors(name) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
And for use your function use this code:
getcolors("name").done(function(result){
console.log(result);
});
Or you can use a callback
getcolors: function getcolors(name, success, error) {
return $.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
success(data);
},
error: function(data){
error(data);
}
});
}
... And for use with callbacks:
getcolors("name", function(data){
//success function
console.log(data);
}, function(){
//Error function
console.log(data);
})
Try one of this options and tell the result.
The Solution
First of all I would like to thank Mateus Koppe for his efforts, through his solution I got the way to solve my problem ..
What I did simply is just I received the ResponseText from the incoming successful result in my Ajax method and then I passed it to a callback function that handles the result like the following :
getcolors: function getcolors(name, handleData) {
$.ajax({
url: "/api/ideas/getcolors",
data: { name: name },
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
handleData(data.responseText);
//return data.responseText;
},
error: function (data) {
handleData(data.responseText);
//return data.responseText;
},
async: false
});
then I worked with getColorArrayModified to loop through my categories list and populate its own color.
getColorArrayModified: function getColorArrayModified(categories) {
var colors = [];
for (var i = 0; i < categories.length; i++) {
this.getcolors(categories[i], function (output) {
colors.push(output);
});
}
return colors;
}
Thanks for all :).
i got my json string inside the ajax as function like this way
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
here i get data like
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
i want it in a variable like
var myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
There you go :
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
var jsonobject = data;
},
error: function () {
alert('Error');
}
});
Also I strongly advise you to use promises to make API calls: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var jsonobject= null;
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
jsonobject=data;
alert('Success');
},
error: function () {
alert('Error');
}
});
If you want wait for ajax response and fill up variable then pass async: false in ajax request options.
Based on your comment, you need to parse the JSON in your success handler,
success: function (data) {
alert('Success');
var myjsonobject = JSON.parse( data );
},
I can't return the value of an ajax request in Jquery. Here's my code:
function ajaxUniversal(datos, url) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
return data; //This does not returns the data
},
error: function (errorThrown) {
return false;
}
});
}
And if I add the return statement to the final:
function ajaxUniversal(datos, url) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
return data;
},
error: function (errorThrown) {
return false;
}
});
return data;//This is the statement but not works
}
And I get this error:
Uncaught ReferenceError: data is not defined
How can I return the data? Thank you. And sorry for my bad english but I speak spanish.
Ajax calls are asynchronous so you can not return value immediately from them. Instead they return a promise to return a value so what you can do is:
function ajaxUniversal(datos, url, callback) {
return $.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html"
});
}
And call it like this:
ajaxUniversal( datos, url, callback ).then( function(data){
//manipulate data here
});
Ajax calls are asynchronous, therefore you cannot return data with them. If you want to use that data, you need to use a callback function instead.
function ajaxUniversal(datos, url, callback) {
$.ajax({
url: url,
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
callback(data);
},
error: function (errorThrown) {
callback(errorThrown);
}
});
}
Elsewhere...
ajaxUniversal(someData, someUrl, function(data){
// Do work with data here
console.log(data);
});
As the others have said, this is failing due to the request being asynchronous. You could either fix your code as they suggest, by handling it asynchronously, OR you can set your request to be synchronous using async: false.
function ajaxUniversal(datos, url) {
var data;
$.ajax({
url: url,
async: false, // <---- this will cause the function to wait for a response
data: {
valores: datos
},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
data = data;
}
});
return data;
}
You can't return the item cause it no longer exists. try to define it first, like this:
function ajaxUniversal(datos, url) {
var returlVal;
$.ajax({
url: url,
async: false,
data: {valores: datos},
type: "POST",
dataType: "html",
success: function (data) {
console.log("Datos recibidos: "+data)
returlVal = data;
},
error: function (errorThrown) {
returlVal = false;
}
});
return returlVal;
}
Hi people, I am craving myself from past 3 days and I just couldn't find the way to access json response seen on my browser
Here is my Ajax code :
$("[id*=btnModalPopup]").live("click", function () {
$("#tblCustomers tbody tr").remove();
$.ajax({
type: "POST",
url: "CallDataThroughJquery.aspx/GetLeadDetails",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hi Json");
alert(data.Leadno); // **Says data.leadno is undefined**
response($.map(data.d, function (item) { // **here I am going some where wrong**
//**cannot catch response. Help!**
}))
},
failure: function (response) {
alert(response.d);
}
});
});
Please help me on this.. Thanks in Advance!
I see that your JSON is an array with an object. Try data[0].Leadno
$.ajax({
type: "POST",
url: "CallDataThroughJquery.aspx/GetLeadDetails",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Hi Json");
alert(data.d[0]['Leadno']); // **Says data.leadno is undefined**
response($.map(data.d, function (item) { // **here I am going some where wrong**
//**cannot catch response. Help!**
}))
},
failure: function (response) {
alert(response.d);
}
});
Try your alert with 'data.d[0]['Leadno']'.