Pass variable from jQuery to WebMethod (Authentication failed) - javascript

I create a new WebForms Application in VS2013. I didn't change anything and created a simple page. I want to load this table on client side when user clicks button
<table id="tblHelpRow">
<thead>
<tr class="title">
<th>F2
</th>
<th>F3
</th>
</tr>
</thead>
<tbody id="helpRowBody">
<%=MyRow %>
</tbody>
</table>
<asp:LinkButton ID="lnkEdit" runat="server" onclick="fnEdit();" />
This is my script code:
function fnEdit() {
BindGridView();
};
function BindGridView() {
rowid = {rowID:2};
$.ajax({
type: "POST",
url: "Default.aspx/GetRow",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
success: function (data) {
alert(data);
}
});
}
I have a WebMethod in my code-behind which stores result in the public property. DataSource I store in session, but rowID I need to pass from jquery.
[WebMethod]
public static string GetRow(int rowID)
{
DataTable dt = (DataTable)HttpContext.Current.Session["SourceData"];
MyRow = "<tr>" +
"<td>" + dt.Rows[rowID]["F2"].ToString() + "</td>" +
"<td>" + dt.Rows[rowID]["F3"].ToString() + "</td>" +
"</tr>";
return "done";
}
But I don't get any result. When I have put the breakpont in success I got "Authentication failed" error and this webmethod wasn't executed. What's the problem? I didn't change ant Authentication settings.

Try removing the ScriptMethod attribute. You are specifying a POST action type but I believe the ScriptMethod forces the request to be a GET by default. Also, I believe your param needs to be a JSON string instead of just an integer:
var param = {rowID:2};
$.ajax({
type: "POST",
url: "Default.aspx/GetRow",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(param),
dataType: "json",
success: function (data) {
alert(data);
}
});

In my VS2013 web forms project the culprit turned out to be:
var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Permanent};
Using default settings for FriendlyUruls solved the problem--do not use RedirectMode.Permanent.
The ajax call like this, where the data params are complex.
$.ajax({
type: "POST",
contentType: "application/json",
url: applicationBaseUrl + "mypage.aspx/Calc",
data: params // data is json
}).success(function (data, status, xhr) {
//...
}).error(function (xhr, status, error) {
//...
});
The WebMethod like this
[WebMethod]
public static string Calc(IEnumerable<AiApp> aiApps, Guid guid)
{ //...

Use
$.ajax({
type: "POST",
url: "Default.aspx/GetRow",
contentType: "application/json; charset=utf-8",
data: {rowID:2},
dataType: "json",
success: function (data) {
alert(data);
}
});

Related

How can i solve Ajax Ckeditor value post problem

I am trying to send a CKeditor value post with ajax but i cant response anyway! I cant find anything
function send_days(tourId){
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: dataString,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});
}
but when i chance ajax method like this. It is succesfull
$.post(url, {data:value}, function (response) {
$('.tour_popup_container').html(response);
})
here is my codeigniter php file (it is not important actually)
public function save_days($tourId)
{
$value=$this->input->post("data");
print_r($value);
}
It looks like you used dataString instead of value.
var url = baseUrl + "tour/save_days/" + tourId;
var value = CKEDITOR.instances.tour_textarea_days.getData();
$.ajax({
url: url,
method: "POST",
data: value /*dataString*/,
contentType: false,
processData: false,
cache:false,
success: function (data) {
$('.tour_popup_container').html(data);
}
});

How to simplfy the passing of parameter

I have these method in c# which requires 3 parameters
public void Delete_AgentTools(int ID,int UAM,int mode)
{
some code etc.
}
and I use javascript ajax to call this method and pass the parameter
function Delete_AgentTools(toolAccess, toolId, UAM) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: "{'toolAccess':'" + toolAccess + "', 'toolId':'" + toolId + "', 'UAM':'" + UAM + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
}
you see for me I want to simpilfy on how I pass the parameter in javascript. Is it possible to pass it as an object to the c# or simplify the passing of parameters in javascript
You can convert a js object as a JSON using JSON.stringify
var data = {};
data.toolAccess = value1;
data.toolId = value2;
data.UAM = value3;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
function Delete_AgentTools(toolAccess, toolId, UAM) {
var data = {};
data.mode = toolAccess;
data.ID = toolId;
data.UAM = UAM;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
No need to change in your C# code.

Unable getting string from WebService customer

i need to read string from my customer server.
the string that i need to call is:
http://xxx.xxx.xxx.xxx:8082/My_ws?applic=MyProgram&Param1=493&param2=55329
The result I get is a string.
If I run it in the browser I get an answer string - OK
i need to get it in my HTML & javascript program
i try this:
function Look() {
$.ajax({
ServiceCallID: 1,
url: 'http://xxx.xxx.xxx.xxx:8082/My_ws?applic=MyProgram&Param1=493&param2=55329',
type: 'POST',
data: '{"Param1": "' + 2222 + '"}',
data: '{"Param2": "' + 3333 + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:
function (data, textStatus, XMLHttpRequest) {
ALL = (data.d).toString();
},
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
Try this, you need to use stringify if the data is Json otherwise remove JSON.stringify, you cannot have 2 data parameters either, your using utf-8 presume that is a MS web srvc, if your sending data up it's post (usually).
$.ajax({
type: 'Post',
contentType: "application/json; charset=utf-8",
url: "//localhost:38093/api/Acc/", //method Name
data: JSON.stringify({ someVar: 'someValue', someOtherVar: 'someOtherValue'}),
dataType: 'json',
success: someFunction(data), // pass data to function
error: function (msg) {
alert(msg.responsetext);
}
});

$.ajax method not calling the controller action method

I am calling javascript function on #Html.ActionLink clicked event. The Javascript function calls the jquery function in which I have written the $.ajax method for calling the json controller method. But it is not calling the controller method.......
Here is my code:
View
#Html.ActionLink("Submit", "AdminEvaluate", "Application", new { onclick = "Show('" + Model.applicationList.ApplicationId + "','statusList')" })|
Here, ApplicationId is coming from database and statusList is Radio Button group name from where I need to find the selected radio button.
Javascipt and jQuery code
function Show(appId, appStatus) {
$.fn.gotof(appId,appStatus);
}
Getting parameter from view and passing to jQuery function
jQuery function
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/Application/UpdateApplicantStatus',
data: { id: appId , status: selectedItem},
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
Controller Method
public JsonResult UpdateApplicantStatus(int id, string status){
return Json("Correct", JsonRequestBehavior.AllowGet);
}
I have put break point on controller method but it is not coming at a break point.
Thanks in Advance.
May be this sample help you :) let me know
ajax call with type :
$.ajax({
type: "GET",
url: '#Url.Action("UpdateApplicantStatus", "Application")',
contentType: "application/json; charset=utf-8",
data: { id: appId , status: selectedItem },
dataType: "json",
success: function() { alert('Success'); }
});
controller :
public ActionResult UpdateApplicantStatus(int id, string status){
return Json(// blah blah blah ...
}
This should work else let me know
Your ajax call is wrong.
If your controller method signature is
public JsonResult UpdateApplicantStatus(int id, string appStatus)
Then you MUST have parameter names matching with your parameters of your ajax call.
So, instead of
data: { id: appId , status: selectedItem}
Just write
data: { id: appId , appStatus: selectedItem}
If you have any other problem, just post the error(s) you should have in your browser's console.
Maybe parameter names of controller function and ajax calling function should match.
you can try this
data: { id: appId , appStatus: selectedItem},
Do that way actually 3 mistakes 1 was notify by #Mr Code the type is missing 2nd your parameters not match as your function takes one you send the data in wrong format..
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/ApplicationController/UpdateApplicantStatus',
data:"{'id':'" + appId + "', 'appStatus': '" + selectedItem+ "'}",//here you format is wrong i correct it
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
sat on this for hours:
When using ajax - json in a js.script file:
the url is written with its real path e.g. - url: '/contoller/Action',
$.ajax({
url: '/NextPage/GetSpDropDown',
data: {'segInputVal': segInputVal},
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;.....
If the script is written in your HTML page then you must use
#(Url.Action(Action,controller))
$.ajax({
url: "#(Url.Action("GetSpDropDown", "NextPage"))",
data: { 'segInputVal': segInputVal },
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;....
And dont forget not to include the word controller in your controller name.
I have had SO MUCH help from stackoverflow- hope to pay a little back

Server does not receive data from ajax call

I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});

Categories

Resources