Im trying to call a c# method on select changed event of a dropdown list,The select change event triggers but the ajax does not work
<script type="text/javascript">
$(document).ready(function () {
$('body').delegate('#drpselect1', 'change', function () {
var groupname = $("#drpselect1 option:selected").text();
alert(groupname);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "sample.aspx/getdata",
dataType: "json",
{"text":groupname},
success: function () {
alert("works");
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
/* $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "sample.aspx/getdata",
data:{"text":groupname}
dataType: "json",
success: function () {
alert('Successfully Saved');
//window.location.href = "ClubCreation.aspx";
},
Error: function () {
}
});*/
});
});
</script>
c# method
[WebMethod]
public static void getdata(String text)
{
//do stuff
}
You have to decorate getdata method with
[WebMethod] attribute.
In your c# code [WebMethod] is missing.
try this
check this line
data:'{"text":"'+groupname+'"}',//put "data:"
now,
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "sample.aspx/getdata",
dataType: "json",
data:'{"text":"'+groupname+'"}',//put "data:"
success: function () {
alert("works");
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
Probabky you missing attributes:
[System.Web.Services.WebMethod()]
public static void getdata(String text)
Look here for more informations: Using jQuery to directly call ASP.NET AJAX page methods
Related
I have this code on my JavaScript file:
temp="string";
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: myJson,
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(temp.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
console.log(errorThrown);
ConnectionChanged();
}
});
And this controller:
[HttpPost]
public string updateStatus(string updatedJson)
{
var Player = JsonConvert.DeserializeObject<GameDataClass>(updatedJson);
var Opponent = JsonConvert.DeserializeObject<GameDataClass>(System.IO.File.ReadAllText(System.IO.Path.Combine(_env.WebRootPath, Player.OpponentID + ".json")));
... }
I tried to change $.ajax to $.post method, also changed
public string updateStatus
to
public JsonResult updatedStatus
But neither of this didn't work. myJson on javascript contain data but when it reaches controller updatedJson is empty. I've never had this kind of experience so I'm using this code from another project and it works very well there. So can somebody suggest me what I'm doing wrong?
temp="string";
// (0)
var myJson = JSON.stringify(temp);
$.ajax(
{
url: '/MemoryGame/updateStatus?updatedJson=' + temp, // (1)
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '', // (2)
success: function (response) {
alert("success");
if (response == 'Okay') {
checkStatus(response.myID);
}
else {
ConnectionChanged();
}
},
error: function (errorThrown) {
ConnectionChanged();
}
});
Or if this does not have to be passed as a parameter, then do the following:
(0) var formData = new FormData(); formData.append('updatedJson', temp);
(1) url: '/MemoryGame/updateStatus',
(2) data: formData,
$.ajax is a fonction from the jQuery library, does your project include it ?
You can also check the Javascript console of your browser to see if it contains errors. On Firefox and Chrome you can access it by pressing F12.
I'm trying to call a script on button click .. Here function summarydata does not call.
Also when I check console there is not a single error. Where is the problem? any solution please?
<button id="chartid" type="button" runat ="server">Show</button>
CODE
[WebMethod]
public static string summarydata()
{
try
{
T1 sd = new T1();
var data = new TrackDataEntities1().spsumdata().Select(s => new { name = s.Month, data = new int[] { s.data.Value } }).ToArray();
return Newtonsoft.Json.JsonConvert.SerializeObject(data);
}
catch (Exception)
{
throw new Exception();
}
}
UPDATED
<script type="text/javascript">
alert("iooooooooooooo");
$(function () {
$('[ID*=chartid]').on('click', function () {
alert("i");
$.ajax({
type: "POST",
url: "WebForm1.aspx/summarydata",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert("i");
},
error: function (error) {
alert(error);
}
});
});
</script>
When i set breakpoint on web method and click on button then breakpoint does not call
your js code should be in $(document).ready()
<script type="text/javascript">
alert("iooooooooooooo");
$(document).ready(function(){
$("#chartid").click(function() {
alert("i");
$.ajax({
type: "POST",
url: "WebForm1.aspx/summarydata",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert("i");
},
error: function (error) {
alert(error);
}
});
});
});
</script>
Have you tried other option like using .on() like this one
<script type="text/javascript">
alert("iooooooooooooo");
$(document).ready(function(){
$("#chartid").on( "click",function() {
alert("i");
$.ajax({
type: "POST",
url: "WebForm1.aspx/summarydata",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert("i");
},
error: function (error) {
alert(error);
}
});
});
});
</script>
Place inside document ready / include script before end of body tag / use $(document).on("click","#chartid",function(){} ) instead .click . Because it will search for element with ID as chartid from root document object.
I have methos to display content of page at server side like
DisplayDetails(Page PageNema)
{
///
}
How can i call this function from javascript as well as how can i pass Page argument from Javascript
If it's WebForm you must set this method as WebMethod, so then you can call this method from jQuery. Something like that:
Client Side.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Server side:
public partial class _Default : Page
{
[WebMethod]
public static string DisplayDetails()
{
//your code to retrieve details here
return Details;
}
}
[WebMethod]
public static string DisplayDetails(parameter1,parameter2,etc...)
{
return something;
}
Client side code
<script type="text/javascript">
function functionName(callback) {
$.ajax({
type: "POST",
url: 'PageName.aspx/DisplayDetails',// your function name
data: '{"argument1","argument2",etc...}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// If u want something from serverside function then write your code here
},
error: function (e) {
}
});
}
</script >
I'm working with jQuery UI Auto Complete extenders for populating list.
Here i include this article for more reference of my code detail.
Here I modify method for auto complete. In article this calls from css class and I want from the ID of the control.
This is my jQuery script :
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#<%=txt_reason.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#<%=txt_reason.ClientID %>").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
And this is my method:
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
[System.Web.Services.WebMethod]
public static List<string> SearchReasons(string prefixText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Reasons.Where(r => r.ReasonText.Contains(prefixText)).Select(r => r).ToList();
List<string> reasons = new List<string>();
foreach (var item in query)
{
reasons.Add(item.ReasonText.ToString());
}
return reasons;
}
}
The problem is not detecting this textbox not displaying result.
Use this
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt_reason").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#txt_reason").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
Using this you can also try
$(document).ready(function () {
$("#textbox").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (retrieveddata) {
if (retrieveddata.length > 0) {
}
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
Take Tern Variable in Code
I'm try using jQuery Ajax for popularize a jqxGrid, but is not success
my jQuery code:
$.ajax(
{
url: "Cliente.aspx/GetClient",
type: "POST",
data: {},
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function(msg) {
alert("error"); //msg is returning error
}
});
I'm try get data with Entity Framework
[WebMethod]
public static string GetClient()
{
string dados;
using (SysContext db = new SysContext())
{
dados = new JavaScriptSerializer().Serialize(db.Clients.ToList());
}
return dados;
}
Where is my error? why
Look over here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
You are missing:
contentType: "application/json; charset=utf-8",
Which is needed to go to the Webmethod. So it will be:
$.ajax(
{
url: "Cliente.aspx/GetClient",
type: "POST",
data: {},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg);
},
error: function(msg) {
alert("error"); //msg is returning error
}
});