I want to read data which is posted in JSON in my c#.net application? I am very new with this JSON and POST method?
Can anyone please help me?
I am posting data from page1. to other page2 (smsstaus.aspx in my case) for testing purspoe.
I want to read that JSON posted data in PageLoad of Page2.
Sample code.....
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
You could define a WebMethod in your smsstatus.aspx (SendStatus for example)
An implementation could look something like this (from the top of my head)
[WebMethod]
public static void SendStatus(string sid, string status)
{
// retrieve status
}
Now you can create a request to consume this method, like this:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx/SendStatus",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
.NET wil deserialize the json string to and pass them as arguments to SendStatus
when you are using Jquery and you throw JSON in the data thingy it will change in a normal Post but what you are now doing is gonna give problems change the code to:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: {"SmsSid":$("#<%= txtSmsSid.ClientID%>").val(),"SmsStaus": $("#<%= txtSmsStaus.ClientID%>").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
and you can use the normal POST but if you want to play with JSON in C# see this aritcle
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Do not change the contentType if you want to request the aspx (WebForm) and not the WebMethod. (When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded").
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
dataType: "json", // The type of data that you're expecting back from the server.
success: function (msg) {
alert(msg.d);
},
error: function () { }
});
Receive data from the Page_Load handler,
//Read Form data
string testData = Request["SmsSid"] + " " + Request["SmsStaus"];
//Prepare Json string - output
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{ \"d\": \"" + testData +"\" }");
Response.Flush();
Response.End();
Related
Salam aleykum, i'm trying here to call an ajax server-side method using the mappage route but it always says: POST 404 (Not found)
here is the code c#:
[System.Web.Services.WebMethod]
public static bool RemovePhotofromAlbum(string list_photos_hotel)
{
.....
return true;
}
and here the jquery code should like :
function RemovePhotofromAlbum(list_photos_hotel) {
$.ajax({
type: "POST",
url: $(location).attr('pathname') + "/RemovePhotofromAlbum",
data: '{list_photos_room_type: "' + list_photos_hotel + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
....
},
failure: function (response) {
alert(response.d);
}
});
}
Without using the mappage route it's working.
but here i want to use the mappage route
i know that there is a problem with the URL in the ajax method but i don't know how to fix it.
any help would be appreciated.
:)
If it's impossible just tell me
$(location).attr('pathname')
This line is used for add attribute in DOM
So if you want to save baseurl,Keep it in web.config, hidden field or any other js file and than use it
You should use $(location).attr('href') and not $(location).attr('pathname')
and you have an error with your parameter name it should be 'list_photos_hotel' and not 'list_photos_room_type'
try this :
function RemovePhotofromAlbum(list_photos_hotel) {
$.ajax({
type: "POST",
url: $(location).attr('href') + "/RemovePhotofromAlbum",
data: '{list_photos_hotel: "' + list_photos_hotel + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.d);
}
});
}
assuming you run the script from the same aspx page your server method runs.
Edit :
Because you use map route, you get 404. you should pass the physical location.
Your method is in the path : Manage/admin_2/index.aspx :
function RemovePhotofromAlbum(list_photos_hotel) {
$.ajax({
type: "POST",
url: "/Manage/admin_2/index.aspx/RemovePhotofromAlbum",
data: '{list_photos_hotel: "' + list_photos_hotel + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.d);
}
});
}
I am making an ajax call to C# function but it is not being call.
This is ajax call:
$('#button1 button').click(function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data:{username1:username,firstname1:firstname},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
return false;
});
This is C# code:
[WebMethod]
public static string ServerSideMethod(string username1, string firstname1)
{
return "Message from server with parameter." + username1 + "hello" + firstname1;
}
This method is not getting hit and shows a error message like this:
object XMLHttpRequest]parsererrorundefined
Any help will be highly appreciated.
$('#button1 button').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
url: "/practiced_final.aspx/ServerSideMethod", type: "GET", dataType: "json",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
});
});
$('button#button1') or $('#button1') or $('#button1 button')
check u selector also. put one alert message inside click event and see
Finally it is working.This is the final code.
Thanks everyone for your wise replies.
$.ajax({
type: "POST",
url: "practiced_final.aspx/hello_print",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$('#myDiv').text(msg.d);
}
})
return false;
Enjoy.
In your code I can see : dataType: "json",
But you're not sending a Json through your C# function... When you're telling ajax that the dataType is a json, it will JSON.parse() the response. Maybe that's where the failure is.
Try changing the dataType, or removing it (jQuery will try to guess it).
Please Change below line in Jquery function.
data:{username1:username,firstname1:firstname},
to
data:"{'username1':'" + username + "','firstname1':'" + firstname + "'}",
Hope this will help you.
$('button#button1') //Or check selector put one alert inside onclick
$('#button1').live('click', function () {
var username = "username_declared";
var firstname = "firstname_declared";
$.ajax({
type: "GET",
url: "practiced_final.aspx/ServerSideMethod",
data: JSON.stringify({ username1: username, firstname1: firstname }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#myDiv').text(msg.d);
},
error: function (a, b, c) {
alert(a + b + c);
}
})
return false;
it may help
Try changing this line:
data:{username1:username,firstname1:firstname},
to
data:JSON.stringify({username1:username,firstname1:firstname}),
Edit:
I'm not sure if this is the cause of the problem, but this is one thing I noticed different between our jQuery ajax calls. Also, changed result string to reflect #dana's criticism in the comments of my answer.
I have just started to Learn the Json and binding data to Gridview using Json but I am not able to understand what is the contentType and dataType and data ?
I used the Following code............
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Gridview.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].OfficeName + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
</script>
The contentType referres to the mime content type that specifies the type of content set to the server. This could indentify FORM-Encoded, XML, JSON and a plethora of other content types. It helps the server to determine how to handle the content.
dataType helps JQuery with regards to how to handle the data. if specifying json then the returned data will be evaluated as json and data passed to the success handler will be an object instead of a string
The data property is used for data passed to The server. If you pass in an Object literal. JQuery will pass it either as part of the request body (if type is post) or as part of the query string (if type is get)
if we specify the data type as Json then the returned data will be evaluated as Json and data passed to the success handler will be an object instead of string,Lets see the example
$.ajax({
type: "POST",
url: "ProductWebService.asmx/GetProductDetails",
data: "{'productId':'" + productId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Product = response.d;
$("#spnProductId").html(Product.Id);strong text
$("#spnProductName").html(Product.Name);
$("#spnPrice").html(Product.Price);
$("#outputTable").show();
},
failure: function (msg) {
alert(msg);
}
});
I need to call a handler (ashx) file from jQuery to fetch some data at runtime.
My jQuery function looks like:
var pID = 3;
var tID = 6;
$("#Button1").click(function() {
var urlToHandler = "Controller/TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: "{'pID':'" + pID + "', 'tID':'" + tID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
}
});
});
My handler code:
<%# WebHandler Language="C#" Class="TestHandler" %>
using System;
using System.Web;
public class TestHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
String pID = context.Request.Params["pID"];
String tID = context.Request.Params["tID"];
context.Response.ContentType = "text/plain";
context.Response.Write(pID + " " + tID);
}
public bool IsReusable
{
get {
return false;
}
}
}
The problem is the code execution doesn't reach to the handler code.
I can call other web forms (aspx) files from the same jQuery function from the same directory, where the handler file is residing. So it isn't any path issue.
I am new to this handler file concept. I googled a lot but couldn't find anything wrong in my code.
It worked after changing the way I was passing the json data (as suggested by #DRAKO) and removing the contentType from the ajax post back call. Also corrected the path.
$("#Button1").click(function() {
var urlToHandler = "TestHandler.ashx";
$.ajax({
type: "POST",
url: urlToHandler,
data: { pID: pID, tID: tID },
dataType: "json",
success: function(msg) {
//do something with the msg here...
}
});
});
I think the way you are passing the json data to the handler is incorrect.
Also make sure the path to the handler is correct and write a line to the console in the handler to check if it is getting called. Try this code out
$("#Button1").click(function(){
$.ajax({
type: "POST",
url: "/Controller/TestHandler.ashx",
data: {pID:pID, tID:tID},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(){
alert("Error");
}
});
});
I want to use jQuery to make a call to a c# web service called c.ashx which checks whether that username is valid and returns an error message as a string.
What should I put for data: and content type: if the return value of the c# webservice is a string value?
jQuery.ajax({
type: "GET",
url: "/services/CheckUserName.ashx",
data: "",
contenttype: "",
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
I have created a .asmx file instead, but it doesn't get called by the jQuery. Is the following correct?
jQuery.validator.addMethod("UsernameCheck", function (value, element) {
jQuery.ajax({
type: "POST",
url: "/services/CheckUsername.asmx?CheckUsername",
data: '{ "context": "' + jQuery("#username").value + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert("success");
},
error: function (msg, text) {
alert(text);
}
});
});
Data should contain the parameters of the method you are calling in a web service. However, the ashx extension is for an HTTP Handler, which is not a good choice for this scenario. A web service should by used instead.
So if you were calling /services/LoginServices.asmx?CheckUserName, and CheckUserName.asmx had a webmethod ValidateUser such as
public string ValidateUser(string username)
then the data attribute for jQuery would be
data: '{ "username": "' + usernameValue + '"}'
your contentType should be application/json; charset=utf-8, and dataType should be "json".
Note that you're not going to call /services/CheckUserName.asmx, the name of the method in the web service has to be appended to the webservice url, /services/LoginServices.asmx?CheckUserName.
Also, you'll need to change your type to "POST".
Here's a complete example:
$.ajax({
type: 'POST',
url: 'LoginServices.asmx/CheckUserName',
data: '{"username": "' + usernameValue + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}});
Hope this helps
The jQuery code wasn't working because it wasn't calling the webservice. I fixed this by creating a HTTP handler class and passing it the username. I changed the value for data: to the following and it passed the username entered by the user:
data: "username=" + jQuery("#username").val(),