How to send data from JQuery Ajax to ASP.NET page? - javascript

I'm using JQuery Ajax to send a data from one domain to an ASP.NET page that is in another domain. I'm able to get the response back from ASP.NET page but I'm not able to send the data from JQuery Ajax. Here is my code:
$.ajax({
url: 'http://somewebsite/dbd/leap.aspx',
data: '{ year: "' + $('#txtYear').val() + '"}',
type: 'POST',
async: true,
cache: false,
dataType: 'jsonp',
crossDomain: true,
contentType:"application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
I can reach leap.aspx page. Note http://somewebsite is just a placeholder.
leap.aspx has the following:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="leap.aspx.cs" Inherits="_Default" %>
<%=output %>
leap.aspx.cs has the following: Note I'm using Request.Params["year"] to get the value of year passed by Ajax call but no luck.
using System;
public partial class _Default : System.Web.UI.Page
{
public string output = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["callback"] != null)
{
output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')";
}
}
[System.Web.Services.WebMethod]
public string GetData(string year)
{
return "From outer space! " + year;
}
}
When I run this code, in console I see
"result: From outer space!"
but I do not see the data sent for year by Ajax. I'm using JSONP because I'm making a cross-domain request to get around Same Origin Policy. I'm not getting any error. I'm just not getting the getting the value of year returned from ASP.NET page.
How do I get the year?

Change the data setting to remove the quotes like this:
data: { year: $('#txtYear').val() },

Had the same issue with a pre-defined object and this helped me.

Related

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.

How to call a non-static method from aspx

I've a Method in the code behind of my aspx page, I need to call Two methods from Javascript, the problem that I'm Having is that I was trying to do it with a Json request and a WebMethod, but this method has to be static and the page components and other methods cannot be accessed from this method.
I was trying something Like:
javascript Function
function Func(Value) {
var conf=confirm('Sure? '+valor)
if (conf==true)
{
BlockAction();
}
}
function BlockAction() {
$.ajax({
type: "POST",
url: 'frmVentaTelefonica.aspx/BlockAction',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
})};
Code-behind code:
[WebMethod]
public static void BlockAcction()
{
try
{
frmVentaTelefonica venta = new frmVentaTelefonica();
venta.ConsultarVentaTelefonica();
venta.ImprimirTiquetes();
}
catch (Exception e)
{
throw;
}
}
I want to call those two methods when the confirm is true.
Update:
In need to accesses to two methods like this:
public void ConsultarVentaTelefonica()
{
DatosImpresion = new List<Impresion>();
IServicioVentas servicioVentas;
servicioVentas = SATWebServiceLocator<IServicioVentas>.ObtenerServicio();
string Tiquetes = string.Empty;
foreach (GridDataItem dataItem in gridInfoVentaTelefonica.MasterTableView.Items)
{
if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked)
{
Tiquetes = Tiquetes + (dataItem["Tiquete"]).Text + ",";
}
}
Tiquetes = Tiquetes.TrimEnd(Tiquetes[Tiquetes.Length - 1]);
Tiquetes = " " + Tiquetes + " ";
DataSet dsResultado = servicioVentas.EntregaTelefonica(sessionR8A.Turno.IdTurno, Tiquetes);
if (dsResultado.Tables.Count > 0 && dsResultado.Tables[0].Rows.Count > 0)
Just run it when is true, those methods update in the database and print a ticket(first reading a grid checked items)
If you are trying to update the UI controls, or read their values, then what you are describing is the UpdatePanel control. A page webmethod cannot update any control and refresh the UI (unless through JavaScript). If you want to update the state of the page async, UpdatePanel is what you are looking for.
If you are trying javascript just because you dont want to refresh the page, then go for Update Panel . The answer for your question is 'No' you cant access non-static methods like how you want to do.
The reason it supports only static methods is that page instantiation is not done, if you want to use non static web methods then go for web service(.asmx).

onserverclick event not working using html builder in C#

I am using anchor tag and I want to fire event on click anchor tag.But unfortunately it is not working . Here is my code :
html.Append("<a id='dltTag' class='ca_quy_e' runat='server' onserverclick='Delete_Click'>");
html.Append("<i class='fa'>");
html.Append("</i>");
html.Append("</a>");
protected void Delete_Click(object sender, EventArgs e)
{
//My code
}
Every thing working perfect like table is forming , but only onserverclick not working.
You have to make use of javascript or jQuery i.e. clientside scripting for calling serverside method from client side
a. create method with wemethod attribute
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
b. register client call with element
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txtData.Attributes.Add("onblur", "focuslost()");
}
c. make use of jquery Ajax
function IsExists(pagePath, dataString, textboxid, errorlableid) {
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
if you are not getting than here is full article : Calling Server Side function from Client Side Script
if you are using scriptmanager than you can use this Execute server side code from JavaScript using Script Manager
you need to use _dopostBack for psotbacking to server or make use of ajax to call server side method
Read:
Usage of doPostBack in a Real Environment
Example
html.Append("<a id='dltTag' class='ca_quy_e' runat='server' onclick='DoPostBack()'>");
html.Append("<i class='fa'>");
html.Append("</i>");
html.Append("</a>");
function DoPostBack()
{
__doPostBack('DeleteButton','');
}

Ajax POST never gets triggered, neither success nor error

What I am trying to do by using AJAX is when I click "Select" Button, all the related information coming from SQL DB will be assigned to the related labels.
The problem is that the AJAX code below($.ajax) never gets triggered (neither success nor error). alert(res[0]) is showing the true result on screen (so the clientid parameter is true).
This is from a WebApplication Project in Asp.Net
function BindClientSummaryForm() {
var skillsSelect = document.getElementById('<%= ddlSFoundClients.ClientID %>');
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
var res = selectedText.split('-');
document.getElementById('<%= hiddenClientID.ClientID %>').value = res[0];
alert(res[0]);
$.ajax({
type: "POST",
url: "Default.aspx/GetClientSummaryData",
contentType: "application/json;charset=utf-8",
data: "{ 'clientid': " + res[0] + "}",
dataType: "json",
success: function (data) {
alert("deneme");
document.getElementById('<%= lblClientNameSurnameD.ClientID %>').innerHTML = data.d.Firstname + " " + data.d.Lastname;
document.getElementById('<%= lblDateOpenedD.ClientID %>').innerHTML = data.d.DateFileOpened;
document.getElementById('<%= lblCityD.ClientID %>').innerHTML = data.d.City;
...
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error occured while filling ClientSummary part.");
}
});
return false;
}
<asp:Button runat="server" CssClass="btnSelect fieldButton" ID="btnSSelect" Text="Select" OnClientClick="return BindClientSummaryForm()"></asp:Button>
CodeBehind
[WebMethod]
public static MyClient GetClientSummaryData(String clientid) //GetData function
{
...
return client;
}
the debugger never drops to the GetClientSummaryData(clientid) method in c# as well.
I appreciate for your helps.
Try to change the value of content-type to text/plain on both, the client and the server, and use eval ('('+data+')') in the success function.
I know that this is not correct because the server response is json, but happened to me the same thing and I discovered (i don't know the reason) when you return the content as content-type: application/json on the server, jQuery does not call the success function.
What for do you specify POST as a request type? It seems like it will be more natural if you use GET (even method name tells us about that).
Also I'm not sure about this syntax data: "{ 'clientid': " + res[0] + "}" because I prefer to write scripts in separate files. Anyway, you can try to write data: { clientid: res[0] } instead

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

Categories

Resources