I am trying to call a server-side function using Jquery ajax, it doesn't work, I get no error. what can be the problem ? is there a set of rules to make sure my $ajax will work?
//HTML
<asp:DropDownList ID="DDL" runat="server">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
//JS
$(document).ready(function () {
$("#DDL").change(function () {
$.ajax({
type: "POST",
url: "signToCity.aspx/getStreets",
contentType: "application/json; charset=utf-8"
});
});
});
//Serverside
[WebMethod]
public static void getStreets()
{
string test="no return:just checking by breakpoint if function is working."
}
Here are the detail of rules to make a AJAX Call : See Here in detail
$.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description = $('<p>').text(data.talks[0].talk_description);
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
Change your server side code to the following: (change void to string and return value)
c#
[WebMethod]
public static string getStreets()
{
return "no return:just checking by breakpoint if function is working.";
}
jQuery: (add handlers for ajax response)
$.ajax({
type: "POST",
url: "signToCity.aspx/getStreets",
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response.d);
},
error: function (response) {
console.log('error ' + JSON.stringify(response));
}
});
Are you setting the clientidmode to static for your web control somewhere? If not, ASP.NET renders it with an entirely different id
You labeled the follwing as HTML:
<asp:DropDownList ID="DDL" runat="server">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
but it is not HTML, it is your aspx page that will be processed and output html. Look at the page source and see the actual HTML that is rendered. You will notice your dropdown list is a select element with an id something like ctl00$ContentPlaceHolder1$Page$#DDL
Your jQuery cant find$("#DDL") because it doesnt exist.
Option 1:
If your javascript is directly on the .aspx page and not external, you can use the following to print the generated client id to your page
...$("#<%=DDL.ClientID%>").change(function () {
$.ajax({...
Option 2:
Your other option is to set the ClientIDMode of your DropDownList to static, so it doesn't change when the page is rendered
<asp:DropDownList ID="DDL" runat="server" ClientIDMode="static">
<asp:ListItem>aaa</asp:ListItem>
<asp:ListItem>bbb</asp:ListItem>
</asp:DropDownList>
Could your url be the problem?
signToCity.aspx/getStreets doesn't look right. Perhaps it's supposed to be signToCity/getStreets.aspx?
Or even just signToCity/getStreets?
Related
I am trying to perform ajax using webmethod on Asp.net,
And I am using JQuery-3.1.1
I want to pass the value to server and get back the value. I don't know what I did wrong.
Asp.net Code
<div class="row">
<asp:Button ID="btnSave" runat="server" CssClass="btn btn-info" Text="save" />
</div>
Jquery Code
$(document).ready(function () {
$('#btnSave').click(function () {
var name= 'xxx';
$.ajax({
type: "POST",
url: "AjaxWebMethod.aspx/getFileExistOrNot",
data: '{fileName:'+name+'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("failed ="+response.d);
},
error: function (response) {
alert("error ="+response.d); //This alert is executing
}
});
function OnSuccess(response) {
alert("Result ="+response.d.mydata);
}
return false;
});
});
C# code
public partial class AjaxWebMethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string mydata="ajaxworking";
return mydata;
}
}
I don't know really where I did my mistake
Error message on console
{Message: "Invalid JSON primitive: xxx.",…}
ExceptionType:"System.ArgumentException"
Message:"Invalid JSON primitive: xxx."
Can you give the solution with proper reason. that will good for me to understand more, thanks
Your postData is invalid JSON, a string needs quotes around it:
'{fileName:'+name+'}'
It should be:
'{fileName:"'+name+'"}'
The jQuery call that you are making is set up to expect JSON format in the response. It would appear that your server side code is simply returning a string which is not encoded as JSON. You either need to change the output from the server or change what is expected from the ajax invocation.
I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!
You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!
Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?
I am trying to link two drop down lists using JQuery AJAX, but I'm not getting anything.
My ASP.NET code for the drop downs is:
<td>Park*</td><!-- PARK -->
<td>
<asp:DropDownList class="form-control" ID="parkDDL" ClientIDMode="Static" onchange="ShowCurrentBuilding()" style="width:150px;" runat="server">
<asp:ListItem text="ALL" value="ALL"></asp:ListItem>
<asp:ListItem text="Central" value="C"></asp:ListItem>
<asp:ListItem text="West" value="W"></asp:ListItem>
<asp:ListItem text="East" value="E"></asp:ListItem>
</asp:DropDownList>
</td>
<td>Building </td><!-- BUILDING -->
<td>
<asp:DropDownList class="form-control" AutoPostBack="true" ID="buildingDDL" runat="server" style="width:300px;" OnSelectedIndexChanged="buildingToRoom"></asp:DropDownList>
</td>
My code for the JQuery in between JS tags (As you can see, I'm not quite sure how to output what is returned to the drop down list):
function ShowCurrentBuilding() {
$.ajax(
{
type: "POST",
url: "CreateRequest.aspx/GetCurrentBuilding",
data: '{name: ' + $('#<%= parkDDL.ClientID %> option:selected').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
I have also tried the following which i put in the document ready function :
$(document).ready(function () {
$('#<%=parkDDL.ClientID %>').on("change",function ShowCurrentBuilding() {
$.ajax(
{
type: "POST",
url: "CreateRequest.aspx/GetCurrentBuilding",
data: '{name: "' + $(this).find("option:selected").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessBuilding,
failure: function (response) {
alert(response.d);
}
});
});
function OnSuccessBuilding(response) {
alert(response.d);
}
});
Finally, here is my C# code:
namespace Team11
{
public partial class CreateRequest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate my initial drop down lists etc
}
}
//here is the function that is called in the JQuery function
[System.Web.Services.WebMethod]
public string GetCurrentBuilding(string name)
{
string textbx = "";
textbx = name;
return textbx;
}
I just want to filter the drop down list via ajax so the page doesn't reload with AutoPostBack = "true".
Thanks in advance to anyone that can help!!
Use the client side function, onchange, instead of server side, OnSelectedIndexChanged.
Can any body help me out.
I have this code
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GOTO() {
var datastring = "id=2";
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: datastring,
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
//alert("an error occurred: " + error);
alert("Error saving data. Please contact support.");
}
});
}
function Complete(result) {
if (result == "success") {
alert("Success");
}
else {
alert("Failed");
}
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
and My Controller Code is this
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
return Json(new { foo = "bar", baz = "Blech" });
}
But it never hits my controller at all, is that Something I am doing wrong in my View?
thanks
Try passing the data like this:
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: { datastring: 'foo bar' },
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
alert("Error saving data. Please contact support.");
}
});
function Complete(result) {
if (result == "success") {
altert("Success");
// ^ beware!
You have a syntax error in your code.
Moreover, you don't need to specify the JavaScript: protocol in the onclick attribute, you're merely defining a label at that place. Even better, don't assign event listeners in HTML attributes at all, but use unobtrusive JavaScript, including a fallback for the rare case when JavaScript is unavailable.
Update: if you get the "$.ajax is undefined" error, you probably didn't include jQuery in your page. Add
<script type="text/javascript" src="path/to/jquery-X.X.X.js"></script>
To your page above the script element that uses $.ajax (or any other jQuery function).
it could be down to what data you are passing in. Your method expects a parameter called datastring but you are passing in 'id=2'.
It does seem like it wouldn't be possible since callback functions seem to be page specific but in case it's possible I'd like to do that.
You can call static page methods marked with the WebMethod attribute using ASP.NET Ajax if you configure the ScriptManager to do so:
<form id="form" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
.
.
.
</form>
[WebMethod]
public static int Foo(string bar)
{
return 42;
}
Then in your client-side code:
function callFoo(bar)
{
return PageMethods.Foo(bar);
}
You can also do the same with jQuery:
function callFoo(bar)
{
$.ajax({
type: "POST",
url: "YourPage.aspx/Foo",
data: {
"bar": bar
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(message) {
// Do something.
}
});
}