I have this simple ajax request on the client side:
var name = $("#txtNewsletterName");
var email = $("#txtNewsletterEmail");
$.ajax({
url: "/Handlers/Handler.ashx",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
op: "register_to_newsletter",
name: name.val(),
email: email.val()
},
async: true
});
and this code on the C# server side:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
switch (context.Request["op"])
{
case "register_to_newsletter":
string recipientName = context.Request["name"].Trim();
string recipientEmail = context.Request["email"].Trim();
break;
default:
break;
}
}
The problem is that the data from the request is not passed to the server, so the context.Request["op"], context.Request["name"] and context.Request["email"] are null.
I've also checked context.Request.Form.AllKeys and it's string[0]
So obviously the data does not get to the server.
When checking the Network tab in chrome debugger I see that there are 2 requests sent so I've added a screenshot of the Network data from chrome debugger:
There is a redirect occurring, which seems to be dropping the data.
If you look at the the second screenshot you see a GET HTTP 200, but the data is no longer in the request.
The redirect is from "/Handlers/Handler.ashx" to "/handlers/handler.ashx". Maybe there's an urlrewrite in the web.config that enforces lowercase urls and does a redirect if it matches an uppercase character?
What if you change the url to all lowercase:
url: "/handlers/handler.ashx",
And remove the contentType setting:
contentType: "application/json; charset=utf-8",
Because you're not deserializing the data on the server, but want to send it as the default contentType application/x-www-form-urlencoded; charset=UTF-8.
The dataType is for the response, the contentType for the request.
Try to change the data like:
data: '{"op":"register_to_newsletter","name":"' + name.val() + '","email" :"' + email.val() + '"}'
And also use:
context.Request.Form["op"];
why don't you start working with proper data models?
Instead of using HTTPContext, make your input parameter a model of the data that you want to receive. Then you won't have any issues.
Stringify your object before sending, like this
data: JSON.stringify({
"op": "register_to_newsletter",
"name": name.val(),
"email": email.val()
}),
So the full code should be like this
var name = $("#txtNewsletterName");
var email = $("#txtNewsletterEmail");
$.ajax({
url: "/Handlers/Handler.ashx",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: JSON.stringify({
"op": "register_to_newsletter",
"name": name.val(),
"email": email.val()
}),
async: true
});
Related
I'm posting data to an ASP.NET Core MVC 2.1.2 page using this jQuery code:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: JSON.stringify({
sCountryCode: "Test 123"
})
});
}
I am receiving the post in the controller with this method:
[HttpPost]
[ValidateAntiForgeryToken]
[Route("/OnCountryChange")]
public IActionResult OnCountryChange([FromBody] string sCountryCode)
{
logger.LogDebug($"Country code is: {sCountryCode ?? "null"}");
return Json(sCountryCode);
}
The output printed to the log is:
Country code is: null
The raw request body (viewed using Fiddler) looks like this:
{"sCountryCode":"Test 123"}
Why isn't the data being passed?
I am not familiar with C#,but in your question you have add
contentType: "application/json; charset=utf-8"
in your Ajax method which means the data parameter is json format,so you need to access as json object instead of access string directly.
Two ways to solve it:
a. Change your C# controller method to access like a json object
b. Send Ajax parameter without json,code similar to below:
function OnCountryChange() {
$.ajax({
url: "/OnCountryChange",
type: "POST",
datatype: "json",
headers: {
"RequestVerificationToken": $('input[name = __RequestVerificationToken]').val()
},
data: {sCountryCode: "Test 123"}
});
}
I have created web-api to provide service like pin-code, Bank IFSC Code and so on, from my website named as http://www.ajaxserver.com
My all api is hosted on my site and my all client access using my site.
web api code is
[Route("api/GetURLName/")]
[HttpGet]
public string GetURLName(HttpRequestMessage request)
{
return HttpContext.Current.Request.Url.AbsoluteUri ;
}
One of my client website name is http://www.clientwebsite.online
client is used jquery to retrieve info like below code.
$('#btnTestCore').click(function () {
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName/',
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
Output comes:
"http://ajaxserver.com/api/GetURLName/".
Need Output:
"http://clientwebsite.online/api/GetURLName/"
You could append the output to your AJAX request:
$('#btnTestCore').click(function () {
var urlname = encodeURI("http://clientwebsite.online/api/GetURLName/")
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName?urlname=' + urlname,
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
You will then, of course, have to read that querystring in your webAPI code
As far as the server of the ajax request knows; the "site" is itself, so http://www.ajaxserver.com. You could try to look at the referrer, but... that isn't reliable across all browsers and protocols.
So you have two choices:
have the client API tell you the calling site - note that it could trivially be spoofed by the client
do some non-trivial proxy (etc) configuration such that the ajax server's site responds on the client domain
Note that http://clientwebsite.online/api/GetURLName/ was not the actual URL and is not going to come from anywhere by itself.
I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue
Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source
i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});
Sending objects to ASP.NET from JSON works fine if you have a class built that matches the JSON object, but all I need to do is send a single integer.
var request = { "int": jQuery('select#propSelect').val() }
jQuery.ajax({
url: '/Property/getPropByID',
type: 'POST',
data: JSON.stringify(request),
dataType: 'json',
contentType: 'application/json',
success: on_request_success,
error: on_request_error
});
Does anybody know how to do this?
Once it gets to the server I try to print out what has been passed and it displays nothing.
public void getPropByID(string objects)
{
System.Diagnostics.Debug.WriteLine("JSON> "+ objects);
//return js.Serialize(db.Properties.Find(id));
}
If all you need to do is send an int, then do this:
jQuery.ajax({
url: '/Property/getPropByID',
type: 'POST',
data: {'myint':$('select#propSelect').val()},
dataType: 'json',
contentType: 'application/json',
success: on_request_success,
error: on_request_error
});
And on the web service side:
public void getPropByID(int myint)
{
}
Note: I believe the parameter name on your web service must match the parameter name on the client side.
Try this:
var request = { objects: jQuery('select#propSelect').val() }