How to send text like "<>" in parameter with $.ajax to server? - javascript

On client side i have form wich is send to server using $.ajax:
function showSearchResults(searchText, fromSuggestions) {
$.ajax({
url: "/Home/Search",
data: { searchText: searchText, fromSuggestions: fromSuggestions },
success: function (response) {
//processing response
},
beforeSend: function () {
showLoadingPane(); //function to show loading image
}
});
}
On server I have following code:
[HttpGet]
[AsyncAuthorize]
public ActionResult Search(string searchText, bool fromSuggestions = false)
{
//handling request
}
When I type in form text "<>", while debugging i see "<>" in js, but on server I am getting just empty string ""
I tried to use encodeURIComponent(searchText) which gives me string "%3C%3E", but on server i get "3C3E"

Question closed. We had custom model binder that was filtering some symbols.

Related

Sending Ajax to controller

I am trying to get live validation on a register form that tells the user if the username they are trying has already been taken or not. I am using jQuery to detect change in the input and want to send the username they type as an AJAX to a Spring controller I have set up. Eventually it will plug it into a query and return if that username has already been registered. I am having trouble with the AJAX. Any ideas on how to accurately send the request?
My AJAX:
$(document).ready(() => {
function checkPassword() {
let usernameGiven = $("#username").val();
$.post( "/check",
{username: usernameGiven} ,
function(data) {
console.log(data)
})
}
$('#username').on('input', () => {
checkPassword()
});
});
My Controller:
#PostMapping("/check")
public String checkUsername(#RequestParam(name = "username") String username){
}
I haven't used jQuery in a long time but I don't think you can pass data with your post using that syntax. Try:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
dataType is the type of data you expect back from the server (xml, json, script, text, html).
While you're testing this, make sure you're actually returning some data back from your controller too, even if it's just mock data for now.
Maybe can work if you use:
<input id="username" onBlur="checkIfUserExist()">
Make a javascript function:
function checkIfUserExist() {
$.ajax({
url: "/check",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
console.log(data); //content user availability status
},
error:function (){}
});
}
}
Think I found what I was looking for. This is working for me. Let me know if you think there is a more efficient way of doing this.
#RestController
public class TestController {
#GetMapping("/getString")
public String getString(#RequestParam(name = "username") String username) {
return JSONObject.quote(username);
}
}

Submitting Json to Spring MVC Controller returning jsp as ajax response string

I am creating Spring mvc app. I am submitting JSON string to controller through AJAX. What I want is to redirect the page to different JSP page.
Right now I am returning the view from controller but instead of redirecting it is returning response to previous AJAX request.
Spring Controller
#RequestMapping("/hello")
public String hello() {
return "powerseries";
}
Javascript/Ajax
$(document).ready(function(){
$('#getData').click(function(){
var aa=JSON.stringify(answer);
$.ajax({
type: "POST",
url: "hello",
contentType: "application/json",
dataType:'json',
data:aa,
cache: false,
processData:false,
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
}
});
});
});
console.dir(answer);
Browser Console
When you are using AJAX, your MVC should return a special JSON response.
eg:
#RequestMapping("/hello")
#ResponseBody
public Map hello() {
m.put('my_redirect', 'the new url');
return m;
}
then handle this response in your AJAX's handler. Use javascript's window.location.href = resp.my_redirect; to go to the new url.
If you want to redirect to other jsp page , use redirect inside controller method.
#RequestMapping("/hello")
public String hello() {
// return "powerseries";
return "redirect:powerseries";
}
// Add method to controller .
#RequestMapping("/powerseries")
public String returnPowerseries() {
return "powerseries";
}
or just use $("html").html(response); if you want to entirely change your document html.

Json.stringify allows HTML elements

I am trying to post values from MVC view to controller.
Request validation feature is enabled for application.
But when i tried to pass values with HTML tags to controller, I am not getting any exception.
here is my ajax post:
Group.Name = model.Name();
Group.Id = model.ID();
$.ajax({
type: 'POST',
url: /IndexController/SaveGroup',
async: true,
cache: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Group: group }),
success: function (data /*, textStatus, request*/) {
try {
}
catch (error) {
showExceptionWindow('Jquery Error:' + error);
}
},
error: function (request /*, status, error*/) {
handleException(request.responseText);
}
});
}
Controller Code:
[HttpPost]
public async Task<ActionResult> SaveGroup(Group group)
{
when i tried to insert html tags,the values are passing to controller action method and getting saved.
When request validation feature is enabled,html elements should not be passed to controller.
How to make sure it is getting blocked at controller.
MVC validation dosent work since you've changed the submit button to prevent default mvc use the jquery plugin Validate.js just go through i,this code should work
var form = $("#YourFormID");
form.validate();
form.submit(function (e) {
e.preventDefault();
if (form.valid()) {
//Your ajax call
}
})
Seems you have a typo as there group does not seem to be a valid object it is undefined:
data: JSON.stringify({ group: Group }), // <-----It should have to be this Group here
And at your backend:
[HttpPost]
public async Task<ActionResult> SaveGroup(Group group) // group is {}
{
Or as Group is already an object then you can stringify it directly:
data: JSON.stringify(Group), // <-----It should have to be this Group here
[HttpPost]
public async Task<ActionResult> SaveGroup(Group Group) // group is {}
{
Why not using an HTML parser to detect HTML elements injection? This can be a clean JS solution
var containsHTML = /<[a-z][\s\S]*>/i.test("<p>HTML text to be parsed</p>")
if(containsHTML==true){
//There are HTML tags inside the string
}
else{
//You're good to go
}

Why Viewbag not show in asp.net mvc view page?

I'm beginner in asp.net mvc,write this java script code for fetch any data from controller:
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: {
'id': 29
},
success: function(color) {
//alert(color);
},
error: function() {
alert('Error occured');
}
});
and write this action in controller:
[HttpGet]
public ActionResult CallService(string id)
{
var idNum = Convert.ToInt32(id);
string color = idNum.ToString();
ViewBag.Myfamily = "razzaqi";
return Json(color, JsonRequestBehavior.AllowGet);
}
in view page write this code:
<h1> Hello Dear #ViewBag.Myfamily</h1>
when i run the project <h1> Hello Dear #ViewBag.Myfamily</h1> not show me ,but i think show me this output:
Hello Dear razzaqi
You are returning JSON not ViewBag. You need to send the "razzaqi" to as part of JSON object. Set up HTML as
<h1> Hello Dear <span id='familyname'></span></h1>
Modify You controller to return myfamily as part of JSON object.
[HttpGet]
public ActionResult CallService(int id)
{
string color = id.ToString();
return Json(new {
color = color
myfamily = "razzaqi"
}, JsonRequestBehavior.AllowGet);
}
Consume the result like
$.ajax({
url: '#Url.Action("CallService", "MyScore")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': 29 },
success: function (data) {
$('#familyname').text(data.myfamily)
},
error: function () {
alert('Error occured');
}
});
The Viewbag object is filled into the view, server side when making the view. Your ajax call contacts the server asking about Json data after the view is already made.
So you are too late passing objects to your viewbag if you do it this way...
There are however some workarounds/solutions for this problem:
Let the Controller return the variable in the Json it's returning.
Simple, efficient way to get the data you need
Html helpers etc. Won't work however and sometimes you just need that horrible viewbag...
Reload a partialview when doing the ajax call.
Takes more time to implement, You'll have to create a new action and partialview.
Good when you want more content to change on the call and want to use html helpers etc.

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

Categories

Resources