ReferenceError: json is not defined when AJAX call the server method - javascript

I want to call the server method through the AJAX call. But when I am click the button and call the AJAX function at that time it shows an error.
Here is my code
<input type="button" id="btn_findsubmit" value="Edit" class="button" />
$(document).on("click", "#btn_findsubmit", function (e) {
var c = $find("<%=cmbobx_search.ClientID %>");
$.ajax({
type: "POST",
url: "schoolregistration.aspx/GetSchoolName",
data: json.stringify({ schoolname: c.get_textboxcontrol().value }),
contenttype: "application/json; charset=utf-8",
datatype: "json",
success: OnSuccessGetSchoolName,
failure: function () {
alert("error! try again...");
}
});
});
[WebMethod]
[ScriptMethod]
public static string GetSchoolName(string schoolName){
//Here is the code
}
Now when I click the button at that time JavaScript button click event is working but the ajax method do not calling the server method GetSchoolName (I know by doing debug mode).
And throws a error that:
ReferenceError: json is not defined

It should be JSON.stringify, not json.stringify

<input type="button" id="btn_findsubmit" value="Edit" class="button" />
<script>
$(document).on("click", "#btn_findsubmit", function (e) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSchoolName",
data: JSON.stringify({ schoolName: "school name" }),
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
alert(data.d);
},
failure: function () {
alert("error! try again...");
}
});
});
</script>
[WebMethod]
public static string GetSchoolName(string schoolName)
{
//Here is the code
return "success";
}
first of all it must be JSON.stringify not json.stringify, second it must be contentType not contenttype third the name of parameters in [WebMethod] must be same as in your ajax data.
in this case schoolName not schoolname.
hope it help you.

Related

500 Internal Server Error in ajax when calling web server method in C#

When I am calling server method from AJAX call at that time showing 500 internal server error. And this error also happens sometimes only, while sometimes it is working fine.
I am really confused that what is going on that it is sometimes working and sometimes not working. In fact I didn't change anything after working the code but when I check second day it is coming this type of error.
Here is my code
<input type="button" id="btn_save" value="Save" class="button" />
$(document).on("click", "#btn_save", function (e) {
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: JSON.stringify({ schoolName: $('#txt_schoolname').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function () {
document.getElementById("txt_schoolname").value = "";
alert("Error! Try again...");
}
});
});
function OnSuccess(response) {
document.getElementById("txt_schoolname").value = "";
alert(response.d);
}
[WebMethod]
public static string EntrySave(string schoolName)
{
//Here is the code
}
Sometimes working fine but sometimes not coming call in this entrysave method.
try this:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: { "schoolName": $('#txt_schoolname').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (data) {alert('ok');},
error: function () {alert('error');}
});

Calling WebMethod in aspx.cs returning HTML page

I have the following code in my aspx.cs file:
[System.Web.Services.WebMethod]
public static string PostPin() {
return "Rahul";
}
And the following Javascript:
$.ajax({
type: "POST",
url: "/adfs/ls/RequestPinForm.aspx/PostPin",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error : function(data , data2 , data3) {
alert(data);
}
});
I'm using the alert's to see the returns of what is coming back, but I can never get it to return the string.
Any ideas guys?

How do I call a server side VB.net function from jquery in an asp.net form?

I am trying to call a method in my server-side vb code from jquery.
import System.Web.Services
...
'my VB.net Code
<WebMethod()> _
Public Shared Function SubmitReport_Click()
'this is where my code will go
Return Nothing
End Function
In my javascript code the alert is being called but the SubmitReport_Click is not being called.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script type="text/javascript">
$("#<%= FileInput.ClientID%>").on('filebatchselected', function (event) {
alert("file input");
pagemethods.SubmitReport_Click();
})
</script>
I'd make a function that fires on the click event and calls over to your web method using AJAX, and use JSON to pass any relevant data.
$(".clickMe").click(doWebMethod);
function doWebMethod () {
var data = { 'name': 'jessikwa' , 'location': 'ny' }
var params = "{'dataPackage': '" + JSON.stringify(data) + "'}";
$.ajax({
type: "POST",
url: webMethodUrl,
async: true,
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function () {
alert("fail");
}
});
}
//VB HERE
<WebMethod()> _
Public Shared Function SubmitReport_Click(ByVal dataPackage as String) as String
Dim rtnStr As String = "OK"
//deserialize data package here
Return rtnStr
End Function
You can use an Ajax request. I just typed this up, so you may need to Google the syntax in case I messed it up.
$.ajax({
type: "GET",
url: "FileName.aspx/SubmitReport_Click",
success: function(){
alert('It Worked!');
},
failure: function() {
alert('It Failed!');
}
});

trigger a javascript function before on any AJAX call

Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method

ajax call to webmethod doesn't hit success in asp.net

i have an ajax request in a page say Test.aspx
$.ajax({
type: "POST",
url: "Test.aspx/TestMethod",
data: "{ 'Parameter':'Parameter'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
alert('success');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error getting Regions');
}
});
and in the code behind
[WebMethod()]
public static string TestMethod(string Parameter)
{
return "teststring";
}
Issue is control is not going in to success inside ajax, any idea?''
Testtry this
$.ajax({
type: "POST",
url: "Test.aspx/TestMethod",
data: "{ 'Parameter':'Parameter'}",
contentType: "application/json; charset=utf-8",
success: function (res) {
var s = JSON.stringify(res);
alert(s);
},
error: function () {
alert('error getting Regions');
}
});
There are few things you need to make sure you are doing.
First thing you need to add script manager with enable page method property true like below.
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
See my blog post about How to call ASP.Net page method with jQuery
Check the Page URL and everything. It should be correct and should be exactly same as page name and method name as it is case sensitive.
Check parameter also. There is another good post with parameter is also below for your reference.
http://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

Categories

Resources