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.
Related
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);
}
});
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 have the following ajax call to web service in asp.net.When I simply run the program, it won't work. In console, it shows
'http://mywebservice.asmx/add' in red color for a second and dissapear.
function btn_add1()
{
var aData = [];
aData[0] = $("#tb_a").val();
aData[1] = $("#tb_b").val();
aData[2] = $("#tb_c").val();
var jsonData = JSON.stringify({ aData: aData });
$.ajax({
type: "POST",
url: "mywebservice.asmx/add",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
cache:false,
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert("success");
alert(response.d);
console.log(response.d);
}
function OnErrorCall(response) {
console.log(response.d);
}
}
But when I apply breakpoint and run the program it gives the desired result.
I am really confused and frustrated by this behavior.
Here's my webservice code
[WebMethod, ScriptMethod]
public int add(List<string> aData)
{
int cal = Convert.ToInt32(aData[0]) + Convert.ToInt32(aData[1]) + Convert.ToInt32(aData[2]);
return cal;
}
I have an ASP.NET application where I am invoking a controller methode from JavaScript. My JavaScript code looks like this:
function OnNodeClick(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (data) {
if (data != null) {
$('#GridView').html(data);
}
},
error: function (e) {
alert(e.responseText);
}
});
}
This calls the Home controller's DeviceManifests() method.
This is what the method looks like:
public ActionResult DeviceManifests(Guid selectedRepo)
{
var repoItem = mock.GetRepoItem(selectedRepo);
return View("Delete", repoItem.childs);
}
The method gets invoked but the problem is the Delete-View doesn't get rendered. There's no error, just nothing happens.
How can I update my code to get my desired behaviour?
Do like below code so if you have error you will have it in alert box or success result will rendered in DOM
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
dataType: "html",
success: function (data) {
if (data != null) {
$('#someElement').html(data);
}
}
},
error: function (e) {
alert(e.responseText);
}
});
You can do the redirect in the javascript side.
function OnNodeClick(s, e) {
$.ajax({
type: "GET ",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (msg)
{
window.location = msg.newLoc;
}
});
}
Make sure you include the redirect url in action and return JsonResult and not ActionResult. I'd also include pass the guid so that the destination Action and let it look up the data.
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",
...