AJAX GET REQUESTS - c#

Please help, I'm stuck here. I have a problem with passing input parameter to my C# controller. I tried really a lot of things I found here, but still there's some mistake.
Here is code:
var a = $.ajax({
type:"GET",
url: "/Weather1/Weather_get",
data: "location=Paris%",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
And here is controller:
[HttpGet]
public JsonResult Weather_get(String location) etc etc...
Everything I tried gives me input location NULL. I know my controller is working fine because I get data from it, but I really need that data to be for specific location, so that's why I need it like this. Also don't want to change it to POST because this is homework problem so I have to have both HttpPost and HttpGet in my controller.

Try this
var place="Paris%";
var a = $.ajax({
type:"GET",
url: '#Url.Action("Weather_get","Weather1")',
data: '{ "location":"' + place+ '"}',
dataType: 'json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;

just include the parameter name in your controller and the value you want to pass like this.
$.ajax({
type:"GET",
url: '#Url.Action("Weather_get","Weather1")',
data: { location:paris},
dataType: 'json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;

The way ASP.Net binds the HTTP request URL to the model used by your controller is controlled in part by the routing engine.
If you navigate to
/Weather1/Weather_get/Paris
do you see the data from Paris?
If so, you could modify your AJAX this way
$.ajax({
type:"GET",
url: "/Weather1/Weather_get/Paris"
(etc.)
})

You should probably use JSON.stringify.
something like this:
var data = {
location: "Paris%"
};
var a = $.ajax({
type:"GET",
url: "/Weather1/Weather_get",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;

Related

Ajax function failing to hit method on code behind on server

I have the following ajax function
var jsonId = JSON.stringify(sortedIDs);
$.ajax({
type: "POST",
data: { ids: jsonId },
datatype: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
And the following method in the code behind page
[WebMethod]
public static string GetData(string[] data)
{
return "this is the string from the code behind file";
}
The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.
You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:
var json = JSON.stringify({data: sortedIDs);
$.ajax({
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
Also, datatype: should be dataType:

ASP.NET C# Ajax Call Error

I'm going straight to the point here.
I'm trying to get the value pass from my ajax to controller and console.log the value. however, when I try to console.log the value it gives me error 500..
here's my code:
I've been doing ajax on php for a long time.. however, I'm still new to asp.net C# mvc so please bear with me.
AJAX:
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data:{id: province_id},
success: function (data) {
console.log(data);
}
});
});
CONTROLLER:
[HttpPost]
public ActionResult GetCities(int id)
{
return Json(new { success = true });
}
here's the error I don't know what's wrong with my controller though.
POST http://localhost:43969/Property/GetCities 500 (Internal Server
Error)
if using contentType: 'application/json; charset=utf-8' then use JSON.stringify to convert the data being sent to a JSON string.
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
var data = JSON.stringify({id: province_id});
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (data) {
console.log(data);
}
});
});
As mentioned in the comments by #StephenMuecke
It does not need to be stringified if contentType: 'application/json; charset=utf-8', is removed (so that it uses the default application/x-www-form-urlencoded; charset=UTF-8').
you can add error function to check for possible error on your ajax.
Ex.
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}

Jquery ajax call - how to alert the value from the return object

My requirement is to get the proper value. I got the success alert. result set contains one and only one value. How can I show/alert that value in result?
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
alert("success");
if(result.d.length>0)
{
alert("success");
}
}
});
try
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
dataType : 'json', // expecting json returned from server
success: function (result)
{
alert("success");
if(result.d.length>0)
{
// access first element
alert(result.d[0]);
}
}
});
Whenever you want to see the data in json, in jquery write console.log(result) and check what you want to retrieve in browser console. This is the best way to debug json.
By typeing alert(result) in you success function, result is the object returned by the ajax call
try this , you can explore result value in console.
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
alert("success");
if(result.d.length>0)
{
Console.log(result)
}
}
});
See console output (CTRL/CMD+SHITF+I) to degub, seeing what coming form server:
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
console.log(result);
}
});
I thing you have json string so please parse that to object.
Using JSON.parse(result.d);
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
alert("success");
var jsonObject=JSON.parse(result.d);
if(jsonObject.length>0)
{
Console.log(jsonObject[0].BlockRefHandle);
}
}
});

Ajax URL - Incorrect .net #c

Been following some tutorials, as i'm learning C#, however was just attempting to make an ajax call to the server, i'm using my localhost.
As far as I can tell i'm doing its right, but it's obviously not.
Maybe it my folder structure or just the name of the file.
The Default.aspx file is at the project root
Here is my ajax call
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx",
dataType: "json",
data: "{'FirstName':'test','LastName':'test1','City':'test3','EmailID':'test4'}",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});
I know eventually it will have to call a method within the file, but its not even finding it at the moment.
Thanks in advance, James
You can use controller Home and create the one action.
Example:
public ActionResult FirstAjax()
{
return Json(true, JsonRequestBehavior.AllowGet);
}
After that your jquery ajax is:
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "Home/FirstAjax",
dataType: "json",
data: "",
success: function (data) {
console.log("Woo!");
},
error: function (result) {
console.log("fail!");
}
});

Cannot get response in ajax success

My AJAX code is below. In this i cannot get the response from server side C# code. But there is no issues with my server side code ( I have checked it by debugging ). From server side i am returning string to this ajax.
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]' +"provider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
}
});
Server side code is below
public string GetState(string CountryId)
{
int i= Convert.ToInt32(CountryId);
var Details = objUserAccount.SP_Getstate(i).ToList();
if(Details.Count>0)
{
return "Success";
}
else
{
return "False";
}
}
Add datatype in your ajax request like this, if datatype is not matched with received data from server then the ajax error will call instead of success
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
dataType: "json",
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
Either one of the success or failure call back will be initiated if the request is made from this snippet. Might be a server issue, most probably. And make sure that this is the code snippet getting executed. Happens to me all the time.

Categories