I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...
Related
View:
#Html.DropDownList("bolumler", null, "lutfen bolum secin",
new {#class = "form-control",
#onchange="SelectedIndexChanged(this)"})
<script type="text/javascript">
function SelectedIndexChanged(item) {
var value = item.value;
$.ajax({
type: "POST",
url: "#Url.Action("GoTo")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data:JSON.stringify( value ),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
Controller:
[HttpPost]
public async Task<IActionResult> GoTo([FromBody] string d)
{
var personeller = await _iluPersonelService.getPersonelWithDepartment(d);
List<SelectListItem> valuesForPersonel = (from x in personeller
select new SelectListItem
{
Text = x.Name,
}).ToList();
ViewBag.personeller = valuesForPersonel;
return View();
}
I can't figure out this problem. In .cshtml side, I change dropdownlist selection item and controller post method triggering. I did some operations on the data and I want to return new data to view and display it.
Note: there are no changes on the page and it is not refreshed
Do you want to alert(data) ?
If so , do you want the below way ?
change the action like below:
[HttpPost]
public async Task<IActionResult> GoTo([FromBody] string d)
{
...
return Json(valuesForPersonel);
}
public IActionResult Goto()
{
return View();
}
2.In the view:
change the success method code in your ajax:
$.ajax({
type: "POST",
url: "#Url.Action("GoTo")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(value),
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].text);
window.location.href = "https://localhost:7169/RtCd/Goto";
}},
failure: function (errMsg) {
alert(errMsg);
}
});
result:
I've got an odd thing happening. On my index page I've got an ajax call that grabs a parameter off of an SVG and then hits the following code:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
HttpContext.Session.SetObject("CurrentFilters", SearchFilters);
SearchFilters.State = state;
return RedirectToPage("/Search");
}
I'm able to attach a debugger and see everything is working fine behind the scenes. The problem, the UI doesn't ever update and take me to the Search page. If I manually navigate there all the data is loaded and everything is fine.
Not seen this behavior before and I've used the same code in previous projects.
Here is the AJAX call in case it's relevant:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json"
}).done(function (data) {
console.log(data.result);
location.reload();
});
});
});
You can change your code like bellow.
Action:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
//...
return new JsonResult(new { redirectToUrl = "/Search" });
}
In your Ajax:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
});
});
Test Result:
I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);
Can some one show me how to configure the WCF Endpoint for the following RESTful Web Service to be called from a JQuery Ajax call. My example service code:
namespace MyService
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebGet(UriTemplate = "/GetDepartment")]
public Department GetDepartment()
{
... code
};
return data;
}
}
jQuery code:
var jData = {};
$.ajax({
cache: false,
type: "POST",
async: true,
url: "MyService/GetDepartment",
data: JSON.stringify(jData),
contentType: "application/json",
dataType: "json",
success: function (jsondata) {
... code
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Try following-
function SaveBook() {
var bookData = {};
$.ajax({
type: “POST”,
url: “MyService/GetDepartment″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks
Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});