jquery POST data in aspx page - c#

I post data to my aspx file qith the following code:
$.ajax({
type: 'POST',
url: "Ajax_Text.aspx?rand=" + myRand
+ "&id=" + $(".articleID").attr('title')
+ "&text=" + $("#text").val(),
cache: false,
beforeSend: function () {
},
success: function (data) {
alert(data);
}
});
Why i catch the text value by using the following code
string text = "";
if (!String.IsNullOrEmpty(Request.QueryString["text"]))
{
text = Request.QueryString["text"].ToString();
}
else
{
text = "";
}
and not this code:
string text = "";
if (!String.IsNullOrEmpty(Request.Form["text"]))
{
text = Request.Form["text"].ToString();
}
else
{
text = "";
}
Why is that? I expected Request.Form to work as i post data with jquery! Any ideas?
I suspect that the problem is that i have my input in the url parameter. Maybe i should put it to a data parameter but that means it will become a json request!

POST data are not send in query string but added to the request body. Try this code:
$.ajax({
type: 'POST',
url: "Ajax_Text.aspx",
data: {'rand': myRand, 'id': $(".articleID").attr('title'), 'text': $("#text").val()},
cache: false,
beforeSend: function () {
},
success: function (data) {
alert(data);
}
});

You are "posting" the data (text) as a query string (as part of URL) so you have to use Request.QueryString.

Related

How to call codebehind method from Jquery after autocomplete selection

I have a autocomplete text box as and when the user types the city names are prompted. Once the user selects city name the selected value is retrieved using the following code:
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now I need to pass the selected value and call method in aspx.cs (code-behind) to retrieve further details of selected city.
How can I call a method from JQuery can somebody guide me towards that
You must call ajax in autocompleteselect like this
$('#txtName').on('autocompleteselect', function (e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({url: "aspx.cs",data:{value:ui.item.value}, success: function(result){
//response from server
}});
});
Server Side changes
You need to mark that method with WebMethod attribute to call it from the client side or you need to create a web service.
[WebMethod]
public static yourObject GetCityDetails(string cityId)//name this method as per your needs.
{
//Do whatever you want.
return yourObject; //it can also be in JSON format.
}
Client Side changes
Make an ajax call to the method from the client side.
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "yourpage.aspx/GetCityDetails", //same method name here.
data: { cityId: this.value },
success: function(result) {
//do whatever you want with server side data here.
}
});
});
You Can use Web Method
function GetDetails(cityId) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetDetails',
data: {"cityId":cityId},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (e) {
console.log(e);
}
});
}
$(document).ready(function() {
$('#txtName').on('change', function() {
$('#selectedItem').html('You selected: ' + this.value);
}).change();
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
GetDetails(ui.item.value);
});
in your aspx page
[WebMethod] //Default.aspx.cs
public static void GetDetails(cityId)
{
//Your Logic
}
Use $.Ajax to send the selected value to the server (code-behind) and get the response:
$('#txtName').on('autocompleteselect', function(e, ui) {
$('#selectedItem').html('You selected: ' + ui.item.value);
$.ajax({
url: "your-page.aspx/GetCityDetails",
data: { Name: this.value },
success: function(result) {
//Process the result from the code-behind.
}
});
});
Your code-behind must have a webmethod named GetCityDetails that accepts the name parameter and returns a city object as JSON.
This is what solved my issue:
The following is the code in jquery part in .aspx
function SetCityName(cityName) {
$.ajax({
type: "POST",
url: 'Default.aspx/GetCityDetails',
data: JSON.stringify({ cityName: cityName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("CityName:" + cityName + "\n\nRequest: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
}
This is the code in .aspx.cs
[WebMethod]
public static string GetCityDetails(string cityName)
{
MessageBox.Show(cityName);
return "success";
}
The trick part is using the following piece in JQuery. I have tried above alternatives provided but none worked apart from the below piece of code:
data: JSON.stringify({ cityName: cityName }),

jquery webmethod call returns whole page html

I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this

How to call webmethod in Asp.net C#

I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.

C# Jquery Ajax Post Multiple Data Parameters

In my c# mvc4 application I have three objects I wish to pass to an ActionResult using an AJAX post with Jquery. The objects are two strings and a form collection. Ive had no problems passing only the form collection, but cant seem to get the syntax correct for passing all three. Here is what Ive tried:
$(document).ready(function () {
$('#ChangeName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {tdata + origname + newname},
url: "Home/ChangeName",
success: function (result) { success(result); }
});
});
Ive also tried commas after each variable name in the data: section with and without the brackets. How can I pass all three? When its been successful both string values have populated correctly when debugging but the values dont appear in the ActionResult and show null instead.
Ive also tried placing this below data: contentType: "application/x-www-form-urlencoded",
Here is the beginning of my ActionResult as well:
public ActionResult ChangeName(string Name, string updatedName, FormCollection mCollection)
Can you try:
$(document).ready(function () {
$('#ChangeName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
Name: origname,
updatedName: newname
},
url: "Home/ChangeName",
success: function (result) { success(result); }
});
});
I think the problem is how you are putting the origname and newname in the ajax request.
Try this:
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
url: 'Home/ChangeName',
type: "POST",
data: $("#form1").serialize() + "&origname =" + origname + "&newname =" + newname,
success: function (result) { success(result); }
});

why does this ajax error happen when I post html with stringify

Why does this ajax error happen when I try post html in the string with stringify.
It looks like the stringify escapes the charactors automatically.
do I have to escape? thanks
var s;
//s = "my test test"; //if I post this it works
s = "my test test<br />"; //if I post this it break when I add the html
var a = { "myText": JSON.stringify(s) };
$.ajax({
type: "POST",
url: "test.aspx",
data: a,
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
then on the page load I'm trying to read the posted data with
HttpContext.Current.Request.Form("myText")
Try this:
var s = "my test test<br />",
a = { "myText": s };
a = JSON.stringify(a)
$.ajax({
type: "POST",
url: "test.aspx",
data: a,
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
You don't need to call JSON.stringify().
JSON.stringify is intended to serialize the object to JSON string, but you're passing a string to it and it's wrong.
Just pass the object with $.ajax() call:
var s = "my test test<br />";
.ajax({
type: "POST",
url: "test.aspx",
data: {
myText: s
},
success: function (data) {
//pass
},
error: function () {
alert("error");
}
});
Also jQuery documentation:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}.
So in our particular example we used a "map" of the form, namely JavaScript object.

Categories

Resources