Returning String Result from Ajax Method - javascript

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 :).

Related

Jquery - $.When not trigger ajax on done menthod

Was try to implement another ajax call based on the first two results with Jquery $.When method. Basically, all three Ajax will populate a carousel on the page based on the results. Therefore I choose $.When for continuous checking. But the third Ajax which under Done() method is not called even there was no result from above two APIs or with initial values zero(0). Not sure if I missed anything!
jQuery:
let itemCat1Count = 0;
let itemCat2Count = 0;
$.when(
$.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
$.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (typeof (data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function (jqXHR, status, error) {}
}),
).done(function (xhrSavedRings, xhrShoppingBagItems) {
if (itemCat1Count == 0 && itemCat2Count == 0) {
$.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (jObject) {
console.log(jObject);
// carousel inital codes
},
error: function (jqXHR, status, error) {}
});
}
});
Few things to highlight - $.when() requires promises as arguments. $.when does not have the powers to know when functions you passing are done or completed
From the official documentation of $.when You have return promises or return something from your ajax calls.
Here what its says => In the case where multiple Deferred objects are passed to jQuery.when(), the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed.
I have assigned a retrun value from each $.ajax call you are making. $.when will know check if there is something coming from return and is resolved then it will go to .done
Run snippet below to see the console log on .done
let itemCat1Count = 0;
let itemCat2Count = 0;
function first() {
return $.ajax({
url: "/webmethod/GetItemsCatOne",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
console.log(data.ResponseObject.Items.length)
itemCat1Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
function second() {
return $.ajax({
url: "/webmethod/GetItemsCatTwo",
type: "POST",
data: '',
contentType: "application/json; charset=utf-8",
success: function(data) {
if (typeof(data.ResponseObject) !== undefined && data.ResponseObject !== null) {
itemCat2Count = data.ResponseObject.Items.length;
// carousel inital codes
}
},
error: function(jqXHR, status, error) {}
});
}
$.when.apply(first(), second()).done(function() {
console.log("First and Second is done running - I am from done");
if (itemCat1Count == 0 && itemCat2Count == 0) {
return $.ajax({
url: "/webmethod/GetItemsSpecial",
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(jObject) {
console.log(jObject);
// carousel inital codes
},
error: function(jqXHR, status, error) {}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Can not send data from c#(controller) to javascript

I have this code on my JavaScript file:
temp="string";
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: myJson,
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(temp.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
console.log(errorThrown);
ConnectionChanged();
}
});
And this controller:
[HttpPost]
public string updateStatus(string updatedJson)
{
var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json")));
... }
I tried to change $.ajax to $.post method, also changed
public string updateStatus
to
public JsonResult updatedStatus
But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?
temp="string";
// (0)
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '', // (2)
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(response.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
ConnectionChanged();
}
});
Or if this does not have to be passed as a parameter, then do the following:
(0) var formData = new FormData(); formData.append('updatedJson', temp);
(1) url: '/MemoryGame/updateStatus',
(2) data: formData,
$.ajax is a fonction from the jQuery library, does your project include it ?
You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.

Passing parameter over jQuery GET call receive null on server side

I'm trying to make a GET call in jQuery passing a parameter here is what I'm doing
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere",
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
}
On server side the controller is called but the data I'm getting is always null...
[HttpGet]
public IEnumerable<TypeOfObject> GetDataHere([FromBody]string id)
{}
Any idea how's that happening?
You need to give the value a key so that the ModelBinder can recognise and work with it:
data: { id: id },
You also need to remove the [FromBody] attribute in the action signature, as GET data is sent in the URL (either as part of the querystring, or in a routing structure).
Lastly, the options object of $.ajax() has no failure property so that can be removed as it's redundant.
I upvoted #RoryMcrossan, but there is another solution.
you could just add it to the end of the url.
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});

jquery ajax - second array push not working [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
i have this code that needs to populate an array that will be used on some diagramming tools. so there's a button that will show the results and a checkbox that enables the user to add another set of rows to the array. i use .push() for the array and it works. now, the problem is that the second push on my second ajax calls did not add the data to the array. here's my code:
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one fails
alert("pushed");
});
},
failure: function (data) {
alert(data.d);
}
});
drawChart(rows);
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});
i really don't know why it fails. what happens is that even if the condition is satisfied and the second ajax call succeeds, the contents of the array rows is still the first array push. what's the problem with the code?
the result you are getting is actually expected because of async nature of ajax
you should call the method within the success callback of the second ajax call like this
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values);
});
drawChart(rows); // here
},
failure: function (data) {
alert(data.d);
}
});
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});

pass a object list view to controller with Ajax function in Javascript

I have a list object. I want to pass my list view to controller with Ajax function My code like :
function Save()
{
debugger;
if(!ValidateInput()) return;
var oRecipe=RefreshObject();
var oRecipeDetails=$('#tblRecipeDetail').datagrid('getRows');
var postData = $.toJSON(oRecipe);
var mydetailobj= $.toJSON(oRecipeDetails);
// postData="Hello world!!!!!!! Faruk";
//return;
$.ajax({
type: "GET",
dataType: "json",
url: '/Recipe/Save',
data: { myjsondata : postData, jsondetailobject : mydetailobj},
contentType: "application/json; charset=utf-8",
success: function (data) {
debugger;
oRecipe = jQuery.parseJSON(data);
if (oRecipe.ErrorMessage == '' || oRecipe.ErrorMessage == null) {
alert("Data Saved sucessfully");
window.returnValue = oRecipe;
window.close();
}
else {
alert(oRecipe.ErrorMessage);
}
},
error: function (xhr, status, error) {
alert(error);
}
});
}
Normally my code run successfully if my list length <=3/4 but when my list length >4 here a problem arise. I could not find out what is bug? please any one suggest me
Note : Here i try to pass by list object convert to JSON data
Why type "GET"? It is obvious that you want to post your data back to the controller. Change it to "POST" and try.
$.ajax({
type: "POST",
dataType: "json",
...

Categories