ASP.NET C# Ajax Call Error - c#

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

Related

Trying to redirect from AJAX post

I am trying to call a webmethod from AJAX which is redirecting to a url like this:
HttpContext.Current.Response.Redirect(StoreCode.ToLower() + "/App/home.html?EventClick=True", false);
AJAX call:
function TokenPost() {
var token = $('#hdnToken').val();
$.ajax({
url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
type: 'POST',
data: "{data:'" + token + "'}",
contentType: 'application/json; charset=UTF-8',
datatype: 'JSON',
success: function(response) {
},
error: function(response) {
alert(response.d);
}
});
}
But my AJAX call is not redirecting to that url.Thanks in advance.
I think it' s not possible in HttpPost Methods. But you can return link in your HttpPost method from server. And redirect with Javascript Code if ajax returns success.
$.ajax({
url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
type: 'POST',
data: "{data:'" + token + "'}",
contentType: 'application/json; charset=UTF-8',
datatype: 'JSON',
success: function (link) {
window.location.href = link;
},
error: function (link) {
alert(response.d);
}
});
In Server Method (I am using this in ASP.NET MVC):
string link = "https://...Your Link";
return Json(link, JsonRequestBehavior.AllowGet);
If you are using WebMethod, I think you can return just string, too.
[System.Web.Services.WebMethod]
public static string ChkToken(string data)
{
string link = "...";
// Do things
return link;
}
This time ajax return can be like this,
success: function (link) {
window.location.href = link.d;
},

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:

Passing json object to webmethod via jquery ajax

I am trying to pass a json object to my .net webmethod.
Here is my C#:
[WebMethod]
public static string Guncelle(string personel)
{
return "It came.";
}
And my jquery ajax:
var saveData = {};
saveData.Isim = isim;
saveData.Soyad = soyisim;
saveData.Firma = firma;
.
.
.
var result = JSON.stringify({ personel: saveData });
$.ajax({
type: "POST",
url: "Personeller.aspx/Guncelle",
data: result,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
})
When I run code, it returns 'undefined' with alert. What is the correct way of passing json object to C# Webmethod ? I tried other examples for passing an object but none of them worked for me.
try this: data: "{personel:'" + saveData+ "'}"

Send file with ajax of jQuery to web service in C# (asmx)

I'm using web service with this method:
$.ajax({
type: 'POST',
url: 'page.asmx/method',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{}'
});
Sending json string, and it works, but if I try to append with FormData the content of input and passing it in data value I have 500 response. What have I to do?
You need to serialize you data....
var data = new FormData();
var files = $("#YOURUPLOADCTRLID").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/fileupload/uploadfile",
contentType: false,
processData: false,
data: data
});
And inside the controller you can have something like
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
Hope it helps...
You can send form object like : new FormData($(this)[0]) which send both input values and file object to the ajax call.
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'page.asmx/method',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
Send Client side value server side through jquery and ajax call.
Click On butto send value client side to server side
<script>
$(document).ready(function () {
$("#additembtn").click(function () {
jQuery.ajax({
url: '/TelePhone/Edit',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
Name: $('#txtUsername').val(),
Address: $('#txtAddress').val(),
},
error: function (request, status, error) {
},
sucess: function (data, status, request) {
}
})
});
});
</script>
// Web Servics Telephone.asmx
[HttpPost]
public ActionResult Edit(string data)
{
}

AJAX GET REQUESTS

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;

Categories