ajax script alert jquery - javascript

I create static web method and then i try to call this into script like this
UPDATE SCRIPT
<script type="text/javascript">
debugger;
alert("1");
$(function () {
$.ajax({
type: "GET",
url: "Maintenance.aspx/data_call",
//data: "",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("12");
debugger;
var re = JSON.parse(result.d).response;
debugger;
console.log(JSON.parse(result.d).response);
debugger;
},
error: function (error) {
alert(Error);
}
});
});
</script>
UPDATE
code
[WebMethod]
public static string data_call()
{
string result="";
Data td=new Data();
List<spselect_data_Result> selectdata=td.spselect_data().ToList();
DataTable dt=new DataTable();
dt.Columns.Add("RegionID",typeof(int));
dt.Columns.Add("Region",typeof(string));
dt.Columns.Add("StartDate",typeof(DateTime));
dt.Columns.Add("EndDate",typeof(DateTime));
foreach(var add in selectdata)
{
dt.Rows.Add(add.RegionID,add.Region,add.StartDate,add.EndDate);
}
result=DataSetToJSON(dt);
return result;
}
public static string DataSetToJSON(DataTable dt)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
// dict.Add(dt.TableName, arr);
dict.Add("response", arr);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
}
protected void Page_Load(object sender, EventArgs e)
{
// data();
}
when i debug code then an alert show like this
function Error (){[native code]}
and when when i set debugger on jquery and check then debugger comes on alert 1 and then on this line $(function() { then after this directly execute on this line means ajax not call
first i try to display data on console
error on console
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
When I try this the call only shows alert("1"). alert("12") is not called. Where is the problem?

This problem maybe caused by maxJsonLength property in web.config file. To solve the problem You can chnage the MaxJsonLength property on your web.config:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
The MaxJsonLength property is an integer property that by default set to 102400(100k) and cannot be unlimited.

I see some problems in the code you posted.
First of all you don't need type: "POST" as you are not posting/sending any data.
So update that portion in ajax request.
$(function() {
$.ajax({
type: "GET",
url: "Maintenance.aspx/YourMethod",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
alert("12");
debugger;
},
error: function (error) {
alert(Error);
}
});
});
Or else to work it with post you will have to set
data: "{}",
See instead of setting cache:false in ajax request set it from a common place like
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
Next on server side no need to call the method data in page load.
Just write it directly in class outside page load.And add the attribute WebMethod from System.web.services.
[WebMethod]
public static string YourMethod()
{
return "whatever you want";
}
Note : Also another thing I noticed that you made your method name as data,so my advice is change it to something meaningful as data is a ajax call parameter key and it could conflict.

Related

AJAX indicates that WEBMETHOD was successful, but it never actually triggers the webmethod on code behind

I've been through countless posts and cant figure out what I am doing wrong. I have a asp.net website with C# code behind. In it, I need for a javascript function on the .aspx page to trigger a method on the aspx.cs page. I wrote the following code:
.aspx page (my ScriptManager):
</head>
<body id="bodycontainer">
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePartialRendering="false" EnablePageMethods="true"/>
The Javascript function using ajax on the .aspx page:
function ValidateForm() {
$.ajax({
type: "POST",
url: "default.aspx/Save",
data: {},
contentType: "application/json; charset=utf=8",
// dataType: "json", // NOT NEEDED IF NO RETURN VALUE
async: true, // OPTIONAL
success: function (msg) {
alert("success");
},
error: function (msg) {
alert("failed");
}
});
}
The aspx.cs page (Code Behind page):
[WebMethod]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default();
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
public void btnSave_Click()
{
// METHODS CODE HERE
}
The ValidateForm function responds with "success", however, it doesn't seem like it is even triggering the WebMethod on the Code Behind page. If I use the I.E. Console Network tab, I can see the POST request. However, on the code behind method, it never triggers the breakpoints in debug (Not sure if it should according to some posts). At one point I inserted line to throw a DivideByZero exception and it never raised the exception.
So, to summarize, I get confirmation that he Javascript call to the WEBMETHOD worked by virtue of the success message and the POST message in the F12 Console Network tab. However, it doesn't seem that the WEBMETHOD ever fires. Any help would be appreciated !
You could try this to test an error instead of throwing an exception
Response.Clear();
Response.StatusCode = 500;
Response.End;
Not sure what I did, but I think adding "UseHttpGet = false" allowed it to finally execute the webmethod.
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default(); // SINCE THIS METHOD IS STATIC, WE HAVE TO INSTANTIATE AND INSTANCE OF THE DEFAULT PAGE CLASS TO ACCESS METHODS ON THIS PAGE
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
function ValidateForm() {
var text = "This is a Test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
data: "{}",
url: "default.aspx/Save",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("status: " + textStatus);
alert("Error: " + XMLHttpRequest.responseText);
}
});
}

Value passed by ajax from Javascript to C#, Replied but not saved

I pass a value to my C# part with ajax and I get a response back. But I can't save the value or use it in my C# code. More information below:
Ajax Call: (gallery.aspx)
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&typeIds=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
Code Behind (CodeFile):(gallery.aspx.cs)
Update: Full C# code snippet
public partial class gallery : System.Web.UI.Page
{
public List<string> images = new List<string>();
public List<string> imagesList = new List<string>();
public List<string> filteredImagesList = new List<string>();
public List<string> testList = new List<string>();
protected string imagesName;
protected string filterType;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["call"].ParseString() == "ajax")
{
Response.Write(Request["typeIds"].ParseString().TrimEnd(','), true, ResponseType.Json);
filterType = Request["typeIds"].ParseString().TrimEnd(',');
}
else
{
filterType = "Not Assigned!";
}
}
}
Output on the page: Not Assigned!
Meaning <h1><%=filterType%></h1> in aspx file returns the else statement from aspx.cs file
But I get the response back in my javascript while console.log("From AJAX: " + resp) shows the result.
BUT I can't use filtertype's value in my c# codefile.
I can't understand how come the Response.Write(Request["type"].ParseString().TrimEnd(','), true, ResponseType.Json); gives back the Request["type"] to js part but don't save it for my codefile. Should it be anything like Response.Read or Response.Save or something?
Does someone know what is going on in here?
You can store the ajax response in a hidden field and then access that hidden field value in server side code.
<asp:HiddenField ID="HiddenField1" runat="server" />
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&type=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
$('#<%=HiddenField1.CliendId%>').val(resp);
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
You can then access in server side code like this:
HiddenField1.Value
OK. It will never be assigned in the way how you did it. Simply because when the page is loading and all controls are rendering no ajax calls are taking into account Page Life Cycles. Because of that on page load filterType is not assigned.
Although you have a couple of options
Use Ajax with update panel and PageRequestManager class
Change the value through JQuery or Vanilla JS by using <%=filterType.ClientID%>
If you need only front-end representation you can use either option. If you need it for further back-end I'm afraid option 1 only choice for you.

Pass javascript function from .Net code behind shared function or web method to page

I need to send a script to the page from WebMethod used by Ajax that fires when click HTML link. I couldn't use the script manager with "Me" or "Page" control and can't reference any controls.
I just need to return that session is nothing , Any Ideas?
The button clicked to send Ajax is HTML link and all I need to check if session expired (which I can check it on load) so if it's expired want to alert user since I already don't complete the process after checking it in code behind
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
''''' my code
''''''''''''''''''''''
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Return "Success"
Else
Return "noSession"
End If
Catch ex As Exception
Return "failure"
End Try
Else
ScriptManager.RegisterStartupScript(Me, GetType(String), "Checkeng", [String].Format("LevelsMsg();"), True)
End If
End Function
JQuery Ajax
It's more complecated but I thinkk this is the main part:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
},
error: function() {
alert("There is a problem in saving data");
}
});
});
Your WebMethodis a Shared function which is equivalent to a Static function in C#. This means you will not be able to access any variables other than those declared inside of this Shared function. However, the nature of WebMethods allow a return to "its" caller via "Success" or "error" which can be "intercepted". Thus, no need to use ScriptManager.RegisterStartupScript since your POST will return to AJAX realm anyway, which means you can call any JavaScript function there.
You could Change your code this way:
VB.NET Code-Behind:
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
' YOUR CODE
Return "Success"
Catch ex As Exception
Return "Failure"
End Try
Else
Return "NoSession";
End If
End Function
JavaScript:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
/* since we put "NoSession", then we should check for it here */
if(response.d == "NoSession") {
/* This is where you "replace" the use of RegisterStartupScript
by safely calling any JS function here */
LevelsMsg();
}
},
error: function() {
alert("There is a problem in saving data");
}
});
});

populate drop down list with json

I am trying some stuff and populating drop down list with a json and javascript for some reason I am getting a console error when trying to populate
I am using Scripts/jquery-2.0.2.js
this is the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
POST //localhost:9819/Home/Home/Test 404 (Not Found)
jquery-2.0.2.js:7858 send jquery-2.0.2.js:7858 jQuery.extend.ajax
jquery-2.0.2.js:7314 RetrieveData Index:45 (anonymous function)
Index:64 jQuery.event.dispatch jquery-2.0.2.js:4692 elemData.handle
This is the View Code:
<script>
$(document).ready(function () {
var Load = false;
function RetrieveData() {
if (Load == false) {
Load = true;
$.ajax({
url: <%= Url.Action("Test", "Home") %>
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
$("#selectMe").html(data);
Load = false;
},
error: function (data, status, jqXHR) {
alert("Error: " + data);
Load = false;
}
});
}
}
$(document).on("click", "#test", function () {
RetrieveData();
});
});
</script>
<input type="submit" id="test" />
<select id="selectMe"></select>
Controller:
public string GenerateHTMLforDropDownList(Dictionary<string, string> myData)
{
string HTMLString = "";
foreach (KeyValuePair<string, string> k in myData)
{
HTMLString += "<option value=\"" + k.Key + "\">" + k.Value + "</option>";
}
return HTMLString;
}
[HttpPost]
public JsonResult Test()
{
Dictionary<string, string> myData = new Dictionary<string, string>();
myData.Add("0", "Mike");
myData.Add("1", "Mark");
myData.Add("2", "Karl");
myData.Add("3", "Rhona");
return Json(GenerateHTMLforDropDownList(myData), JsonRequestBehavior.AllowGet);
}
any help of how I can fix this thanks
As the error states, the resource is not found. Look at the URL in the error:
http://localhost:9819/Home/Home/Test
Assuming you're not doing anything more custom, if you have a Test action on a Home controller then the URL should be:
http://localhost:9819/Home/Test
Notice also how you're specifying the URL in your code:
url: "Home/Test"
If you're currently at http://localhost:9819/Home/Anything then that relative URL says to look for a resource called Test in a "subdirectory" (using the word loosely) of the current resource. So there's your problem.
Instead of specifying the URL manually like that, use the Url.Action method in MVC. Something like this:
url: '#Url.Action("Test", "Home")'
This will generate a fully-qualified URL from server-side code regardless of where your current context is, so you don't have to adjust it based on the current URL or anything like that.
I have not done this in MVC but I've done this countless times in Web Forms and it looks like your URL might be the problem...
//localhost:9819/Home/Home/Test
In your ajax call you should probably adjust this line...
url: "Home/Test"
and make it look something like ...
url: <%= Page.ResolveUrl("~/Home/Test.asmx") %>
Sorry if this is way off base for MVC.
You need to change your button type to 'button' not submit as this is ajax call

ASP.Net call codebehind on $.ajax success

I have a page (default.aspx) with codebehind. The a$.ajax url is getting a response from one place, and on its success I want to call the codebehind function.
(In case I made a mistake while obfuscating the code, the $.ajax works perfectly and I get the desired response).
How is this possible?
Code I'm using:
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
$.ajax({
type: "POST",
url: URL,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var resultCount = response.d
alert("*** RESULT ****" + resultFields);;
var string = StringReturn(); // the codebehind
alert(string);
},
error: function (e) {
alert("Unavailable");
}
});
Codebehind:
[WebMethod]
protected static string StringReturn()
{
return "StringReturn() success";
}
However, I'm getting error messages saying that StringReturn isn't a valid function.
Any help would be appreciated?
I've added the following lines of code to the page as advised:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
I've also changed the code to call a javascript function on the Success event, the function being:
function HelloWorlds() {
alert("HelloWorld() method");
message = PageMethods.StringReturn();
message.toString();
alert(message);
}
however that doesn't appear to work. What am I missing?
You need to have a scripmanager on your page and then you can call it like this PageMethods.StringReturn()

Categories

Resources