Reputation: 1070
I have verified by using the browser debugger / network monitor that I am sending in a variable in an AJAX call called "search" and in the monitor it shows in the header as "search=test". I am trying to access this variable in the code behind but can't seem to find it? Here is my code for front and back-end, am I missing something?
Code Behind :
public class AJAXSearchLog : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string searchTerm = Convert.ToString(HttpContext.Current.Request.Form["search"]);
if(!string.IsNullOrEmpty(searchTerm)){
AspDotNetStorefrontCore.DB.ExecuteSQL("insert into TribSearch(SearchTerm,CustomerID,LocaleSetting) values(" + DB.SQuote(CommonLogic.Ellipses(searchTerm, 97, true)) + "," + '0' + "," + DB.SQuote("en-us") + ")");
}
context.Response.Clear();
context.Response.Write(searchTerm);
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
Front-End
window.onbeforeunload = function(e) {
if ($("#searchBox_text").val().length >= 2) {
var _search = $("#searchBox_text").val();
var url = "/AJAXSearchLog.ashx";
$.ajax({
async: false,
type: 'POST',
url: url,
data: {'search': _search},
contentType: 'application/json;',
dataType: 'json',
success: function(result) {
alert(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log('error');
}
});
}
};
Upvotes: 2
Views: 7895
Reputation: 1070
I have found that the data wasn't getting passed through when the contentType
was set to 'application/json'. Also, to read the POST variable, Request.Params[]
was needed. Here are the 2 lines of code that I changed :
in the front-end -
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
in the back-end -
string searchTerm = Convert.ToString(context.Request.Params["search"]);
Upvotes: 4