i am calling this javascript method "test" in .net1.1 onload of body.My webmethod returns string data,but i am not able to get that data in my Jquery method.
In HiddenPage.aspx
==============================
function test()
{
debugger;
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
//async : false,
//data: "i=1",
contentType: "application/json",
//dataType: "text",
success: function(msg)
// error: function(, textStatus, errorThrown) {
{
debugger;
alert(msg.d);
},
error: function(msg)
//complete: function (jqXHR, textStatus) {
{
debugger;
alert(msg.d);
alert("Error! Try again...");
//return false;
}
})
// return '';
}
In HiddenPage.aspx.cs i have put webmthod.My WebMethod is :-
[WebMethod()]
public static string GetServerTime()
{
return DateTime.Now.ToString();
}
Can you please post your code of returning data.
I suggest you to create an ASMX file to use a webservice. It is easy to use.
Create a webservice and Then make sure that you have add below line in your webservice before your webmethod.
[System.Web.Script.Services.ScriptService]
After that you can add your web method same as you have written.
Your jquery should be like this.
$.ajax({
type: "POST",
url: "webservice/WebService1.asmx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
function OnSuccessCall(msg) {
alert(msg.d);
}
function OnErrorCall(msg) {
alert(msg.status + " " + msg.statusText);
}
It may help you. Happy coding.
Not quite sure about how your return data looks like but you can try the following.
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
//async : false,
//data: "i=1",
contentType: "application/json",
dataType: "html",
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus) {
debugger;
if (jqXHR.status === 0) alert('Not connect.\n Verify Network.');
else if (jqXHR.status == 404) alert('Requested page not found. [404]');
else if (jqXHR.status == 500) alert('Internal Server Error [500].');
else if (textStatus === 'parsererror') alert('Requested JSON parse failed.');
else if (textStatus === 'timeout') alert('Time out error.');
else if (textStatus === 'abort') alert('Ajax request aborted.');
else alert('Uncaught Error.\n' + jqXHR.responseText);
//return false;
}
//return '';
}
try the following
$.ajax({
type: "POST",
url: "HiddenPage.aspx/GetServerTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
// Do something interesting here.
}
});
Related
My c# action looks like:
[HttpPost]
public JsonResult GetItems(int id)
{
var productsQryList = some-query-to-getitems.ToList();
if(productsQryList != null)
{
return Json(productsQryList);
} else
{
return Json(new());
}
}
In my view, the autocomplete configuration looks like:
$("#productInfo").autocomplete({
minLength: 1,
source: function( request, response ) {
$.ajax({
type: "GET",
url: "/api/purchase/SearchProductsSimple",
data: {
term: request.term
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function( data ) {
response( data );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
select: function (event, ui) {
if (ui.item) {
$("#order-items-table tbody tr").remove();
$.ajax({
cache: false,
type: "POST",
url: "/api/purchase/GetItems",
data: { "id": ui.item.value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (itemList) {
for(const item of itemList) {
appendOneRow(item);
counter++;
}
countTrSetIndex();
return false;
}))
},
failure: function (response) {
alert(response.d);
}
});
}
}
});
In firefox plugin RESTED,
The GetItems method runs good if I change its attribute to HttpGet.
But, if The attribute is HttpPost, I got 400 error.
By the way, The select event must be POST call.
wait for resolution.
Thank you guys.
You might have [AutoValidateAntiforgeryToken] attribute on your controller, so you must send forgery token value at ajax call.
data: { "id": ui.item.value,
"__RequestVerificationToken":$( "input[name='__RequestVerificationToken']" ).val() },
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
I have a webapi method defined like the following in a controller:
[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing
public object VerifyResourceURL([FromBody]string url, int resourceID)
When I call it with jquery ajax the variable url is always null, why?
(resourceID has the correct value)
$.ajax({
url: '/api/resources/15/VerifyUrl',
type: "POST",
async: true,
dataType: "json",
data: { url: 'some-url-to-verify' },
success: function (data) {
if (data.Exist === false) {
urlIsValid = true;
}
else {
alert('URL already exist');
urlIsValid = false;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus, "Error: " + errorThrown);
}
});
You're sending an object with a url property, but expecting the body to be a string.
Try changing datatype and data as such:
dataType: "text",
data: 'some-url-to-verify',
I have sample code and you can try something like this
//JavaScript
var command = {
url: $("#txtOrigin").val()
};
$.ajax({
type: "POST",
url: "/api/booking",
contentType: "application/json",
data: JSON.stringify(command),
dataType: "text",
success: Created,
error: Failed
});
//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{
}
I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
Ajax:
var test = "test";
$.ajax(
{
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { input: test },
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# function:
[WebMethod]
public void function(string input)
{
}
The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.
I have also tried setting the dataType to "text" with similar results.
What am I missing?
I would suggest that you shouldn't send your data as JSON. Just remove the
contentType: "application/json; charset=utf-8"
and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.
try this one may be resolve your issue
var test = "test";
$(document).ready(function () {
$.ajax({
type: "POST",
url: "project/function",
contentType: "application/json; charset=utf-8",
datatype: "json",
data:JSON.stringify({ 'input': test }),
success: function (response) {
$("#lblMsg").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});