I am calling a controller method from java script the method works fine i can see the alter but while debugging the control never goes to the controller method .. here is the
script
<script type="text/javascript">
function confirmDelete(customerID) {
if (confirm('Are you sure you want to Delete?')) {
$.ajax({
url: 'Home/Delete',
data: { ID: customerID },
success: function () {
alert('Added');
}
});
}
else {
// Do nothing!
}
}
</script>
here is the "Home" controller method
public ActionResult Delete(String ID)
{
data.Delete(ID);
return View("Home");
}
Update:
and here is how i am calling this JS function
<img alt="delete" src="../../Images/icons-png/delete-black.png" />
Here is Solution :
Add base URL Before your controller name
$.post(baseUrl + '/' + controller + '/' + method, data, onSuccess).error(function (err) {
if (onError) onError(err);
});
here baseUrl Will be like
'httpsORhttp://Domain/SiteName'
Use This
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify("VARIABLE TO PASS"),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
Related
I have Controller PdfViewerController
inside of this controller I have a method
private static string GeneratePdfUrl(string test)
{
string aUrl;
//some action//
return aUrl
}
and I have pdfviewercontroller.js
inside or this js I want to crete a function that will return a string from Controller using GeneratePdfUrl()
something like this
function _doUrl() {
$.ajax({
type: "GET",
url: ep.utilities.replaceEPCommand('PdfViewer/GeneratePdfUrl'),
data: { "test": "R"}
});
}
what I'm doing wrong. Do I need something like .done ?
I try to create ajax Get function and expected to get string inside of my javascript
Assuming that you have an MVC Home controller
[HttpGet]
public JsonResult ForAjaxCall(string test)
{
var aUrl=GeneratePdfUrl(test);
return Json(person, JsonRequestBehavior.AllowGet);
}
This controller will call your custom method
public string GeneratePdfUrl(string test)
{
string aUrl;
//some action//
return aUrl
}
Inside your js file do something like :
function _doUrl() {
$.ajax({
type: "GET",
url: "/Home/ForAjaxCall",
data: { { "test": "R"} },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("You got your URL "+ response.aUrl);
},
failure: function (response) {
alert("Something wrong");
},
error: function (response) {
alert(response.responseText);
}
});
}
Hope this will help you understand the flow.
I'm creating a modal when I click I will pass the id and action to the serverside to save a logs.
Here is my sample code but can't get it to work. I'm using a usercontrol.
$("a.modal_show2").click(function () {
$(this).each(function () {
if ($(this)) {
var storecheckid = $(this).attr("id");
$.ajax({
type: "POST",
url: "TalkTalk.aspx/saveLogs",
data: {
action: 'video_tag',
clickedlinktag: storecheckid
},
dataType: "text",
success: function (response) {
console.log(response);
}
});
}
});
});
[System.Web.Services.WebMethod]
public static string saveLogs(string action, string clickedlinktag)
{
DataHelper.InsertLogs("TalkTalk", Convert.ToInt16(clickedlinktag), Convert.ToInt16(TwwId));
return clickedlinktag;
}
Thanks
data: JSON.stringify({ action: 'video_tag', clickedlinktag: storecheckid })
// response is a wrapper for your data. your data is in `d`.
success: function (response) {
console.log(response.d);
}
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}
I am new to MVC and trying out the ajax functionality on my website. Whenever, I run my ajax function it returns 500 in alert.
This is my controller code
[HttpPost]
public ActionResult JsonNewsfeed(int id)
{
var db = new dekhosaleEntities1();
sale s = db.sales.First(m => m.sale_id == id);
List<sale> sale1 = db.sales.ToList();
saleviewmodel model = new saleviewmodel
{
currentsale = s,
Sales = sale1
};
return Json(model);
}
This is my Jquery ajax function
$('.b1').click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: '#Url.Action("JsonNewsfeed", "Home")',
data:"{ id: 5}",
success: function (data) {
alert(data);
},
error: function (response) {
alert(response.status);
}
});
});
public ActionResult JsonNewsfeed(int id)
{
try
{
....logic here....
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//TODO: log exception
return new HttpStatusCodeResult(401, ex.Message);
}
}
you could also return like this instead:
return Content(jsonObject.ToString(), "application/json");
or
return Content("Your message",...
Then in your ajax call change the success to:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/someDir/someAjaxControllerMethod",
data: jStr,
success: function (json) {
...do something...
var s = JSON.stringify(json);
alert(s);
},
error: function (event) {
alert(event.statusText);
}
});
Try to correct you ajax request ...
like URL...(url: 'Url.Action("JsonNewsfeed", "Home")')
data (data: {id:id}) (if needed check that too)
here is the reference..
Documentation: http://api.jquery.com/jquery.ajax/
I'm trying to get started with ASP.NET MVC Ajax calls.
Controller:
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
View:
<head runat="server">
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
I just need to print an alert with the controller method returning data. Above code just print "chamara" on my view. An alert is not firing.
UPDATE
I modified my controller as below and it start working. I don't have an clear idea why it's working now. Some one please explain. The parameter "a" does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
Remove the data attribute as you are not POSTING anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor and use #Url.Action rather than a static string:
$.ajax({
url: '#Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '#Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
After the update you have done,
its first calling the FirstAjax action with default HttpGet request
and renders the blank Html view . (Earlier you were not having it)
later on loading of DOM elements of that view your Ajax call get fired and displays alert.
Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.
You can't directly render JSON its plain data not HTML.
Use a Razor to dynamically change your URL by calling your action like this:
$.ajax({
type: "POST",
url: '#Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
If you just need to hit C# Method on in your Ajax Call you just need to pass two matter type and url if your request is get then you just need to specify the url only. please follow the code below it's working fine.
C# Code:
[HttpGet]
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Java Script Code if Get Request
$.ajax({
url: 'home/FirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
Java Script Code if Post Request and also [HttpGet] to [HttpPost]
$.ajax({
url: 'home/FirstAjax',
type:'POST',
success: function(responce){ alert(responce)},
error: function(responce){ alert(responce)}
});
Note: If you FirstAjax in same controller in which your View Controller then no need for Controller name in url. like url: 'FirstAjax',
First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..
Here is your controller code:
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
This is how your view should look like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = "Test";
$.ajax({
url: "../../Home/FirstAjax",
type: "GET",
data: { a : a },
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
});
</script>
It's for your UPDATE question.
Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:
UPDATE:
[HttpGet]
public ActionResult FirstAjax()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
Some Code--Some Code---Some Code
return View();
}
And please refer this link for further reference of how a method becomes an action. Very good reference though.
View;
$.ajax({
type: 'GET',
cache: false,
url: '/Login/Method',
dataType: 'json',
data: { },
error: function () {
},
success: function (result) {
alert("success")
}
});
Controller Method;
public JsonResult Method()
{
return Json(new JsonResult()
{
Data = "Result"
}, JsonRequestBehavior.AllowGet);
}
instead of url: serviceURL,
use
url: '<%= serviceURL%>',
and are you passing 2 parameters to successFunc?
function successFunc(data)
{
alert(data);
}
Add "JsonValueProviderFactory" in global.asax :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}