I am making JQuery Ajax call in asp.net, I am returning String with my WebMethod, But on success of ajax call I am getting complete HTML of page in result.I also used type: "get" but no luck, below is my code for ajax call
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData", //url to point your webmethod
success: function (Result) {
if (Result != "")
alert( Result);
},
error: function () { alert('error'); }
});
[System.Web.Services.WebMethod()]
public string GetData()
{
//getting value from Database and returning
}
I am calling this Ajax in MyPage.aspx
Try it like this. With the contentType: "application/json; charset=utf-8"
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData", //url to point your webmethod
contentType: "application/json; charset=utf-8",
success: function (Result) {
if (Result != "")
alert( Result);
},
error: function () { alert('error'); }
});
Related
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;
},
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:
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.
I have been able to call WCF methods with .ajax. How do I call a method that returns a value? I need to call this method to see if data is ready and if not wait one second. The WCF method is:
[OperationContract]
[WebGet]
public bool IsDataReady(string requestGUID)
{
if (Global.publicDataDictionary.Keys.Contains(requestGUID))
return true;
else return false;
}
My JavaScript so far is:
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
}
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service never passes a requestGUID. Can't i use the same input variable?
var guid = "<%= this.guid%>";
// var input = '{"SbiId":"' + guid + '"}';
// var input = {requestGUID:"ca222cf7-be5e-431a-ab93-9a31e8ae2f4a"};
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service is never getting called:
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
else {
//Continue as data is ready
callUpdateGrid(input);
}
The return value will be contained in the data parameter passed to the success callback setup in your ajax call.
You will need to check the value here, then if false, setup a timeout, which on expiry will attempt the ajax call again.
It would be best IMO to wrap up the Ajax call inside a function, that you can call in a recursive fashion when the timeout has expired. e.g.
function CallIsDataReady(input){
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
if (!data){
setTimeout(function(){CallIsDataReady(input);}, 1000);
}
else{
//Continue as data is ready
}
}
});
}
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
CallIsDataReady(input);
});
When you view source on this page is:
var input = {requestGUID:"<%=guid %>"};
showing correctly in the javascript? If you put a breakpoint in your IsDataReady method, do you see if requestGUID has a value? Is your service on the same domain as the page calling it?
EDIT:
In your service change: [WebGet]
to:
[WebGet(
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json]
Read up on RESTful web services:
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
I am doing jquery ajax call in asp.net, I am getting some value from database in a textbox and on base of it I am making jquery progressbar.
Its getting value in textbox, but its not taking value of progress bar first time, I have to reload the page for value of progress bar.
Below is my code
$(function () {
GetValue();
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
});
function GetValue() {
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
$("#txtcount").val(Result.d);
},
error: function () { alert('error'); }
});
}
[System.Web.Services.WebMethod()]
public static string GetCount()
{
//Get values from DB and return it
}
I also tried with document.ready but no luck, Which event of Jquery should I use to make my progress bar on first time.
try this:
async:false, add to ajax call
$(document).ready(function(){
GetValue();
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
});
})
function GetValue() {
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:false,
success: function (Result) {
$("#txtcount").val(Result.d);
},
error: function () { alert('error'); }
});
}
ajax means Asynchronous, that said, means that you need wait untill your first request suceed, and after pocess with value.
Some pseudocode:
$.ajax({
type: "POST",
url: "MyPage.aspx/GetCount", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
$("#txtcount").val(Result.d);
//HERE ASSIGN TO PROGRESS BAR
var l_count= parseInt($("#txtcount").val());
$("#sliderlicense").progressbar({
max: 100,
value: l_count
});
// --------------------------
},
error: function () { alert('error'); }
});