Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource asp.net - ajax

I am facing problem with Cross Domain Ajax call. When I call a asp.net WebMethod through Ajax Call I got warning : Reason: CORS preflight channel did not succeed
Here is complete code
Server Code :
using System;
using Customers.BLL;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public partial class API_Default : System.Web.UI.Page
{
static string ApplicationPath = "";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ValidateUser(string UserName)
{
string strJson = "";
var User = Members.GetCustMaster(UserName);
if (User != null)
{
User.BankName = ApplicationPath + (User.BankName.ToString() != "" ? "Images/Photos/" + User.BankName : "images/avatar.png");
strJson = JsonConvert.SerializeObject(User);
}
else
{
JavaScriptSerializer json = new JavaScriptSerializer();
Failure failure = new Failure();
strJson = json.Serialize(failure);
}
return strJson;
}
}
[Serializable]
public class Failure
{
public bool Status { get { return false; } }
public string Result { get { return "Record Not found"; } }
}
I have added Headers in Web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Token" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
Thisis how I am trying to call this webmethod
<head>
<title></title>
<script src="jquery-1.11.1.min.js"></script>
<script >function GetJSon() {
var obj = {};
obj.UserName = $("#txt").val();
$.ajax({
type: "POST",
url: "http://someurl.net/webservices/default.aspx/ValidateUser",
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
data: JSON.stringify(obj),
success: function (msg) {
console.log();
alert(msg.d)
$("#test").html(msg.d)
},
error: function () {
console.log();
}
});
}</script>
</head>
<body>
<input type="text" value="demo" id="txt" />
<input type="button" onclick="GetJSon()" value="jSon" />
Response : <div id="test">
</div>
</body>
</html>
Response for preflight has invalid HTTP status code 404

Related

Model validation in Asp.Net Core before making an Ajax call from java script

Below is the sample code, i am calling this code on button click event. My question is, can i validate my viewmodel object before making ajax call? i can see model errors in java script, not sure how to check.
My viewmodel class properties has Data Annotation Validator Attributes. I don't want make ajax call if the viewmodel is not valid, want to check (ModelState.IsValid) in java script code, before making ajax call.
Any help, would be greatly appreciated.
$(function () {
$("#btnGet").click(function () {
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: viewModelobject,
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
}
ModelState.IsValid is server side code.Browser has no idea about what it is,so you could not validate ModelState in client side. You can use Jquery Validation at client side.
Here is a working demo:
1.Model:
public class UserModel
{
[Required(ErrorMessage = "The Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
2.View(Index.cshtml):
#model UserModel
<form id="frmContact">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnGet">Click</button>
</div>
</form>
#section Scripts
{
#*you could also add this partial view*#
#*#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnGet').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(viewModelobject),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
})
</script>
}
3.Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod([FromBody]UserModel user)
{
//do your stuff...
return Json(user);
}
}
Result:
Please use jQuery form validation as shown below inside the button click callback:
var form = $('form[name="' + formName + '"]');
form.validate();
if (form.valid()) {
//Do something if the form is valid
}
else {
//Show validation error messages if the form is in-valid
}

How to delete multiple rows of database using ajax and spring mvc

I want to delete multiples rows using ajax and spring mvc but it always delete just one row.
//code controller
#RequestMapping(value = "/rmvclientserviceajax", method = RequestMethod.POST)
#ResponseBody
public void rmvclintServiceajax (HttpServletRequest request, Model model)
{
for(String serviceID: request.getParameterValues("idService"))
{ Long clientID = (long) Integer.parseInt(request.getParameter("idClient"));
metiersr.deleteClientToService(clientID,(long) Integer.parseInt(serviceID));}
}
//code js
function AjaxPostdelete() {
if ($('#idService').prop('checked')) {
var idService = $('#idService').val();
var idClient = $('#idClient').val();
$.ajax({
type : "POST",
url : "/cp/client/rmvclientserviceajax",
data : "idClient=" + idClient + "&idService=" + idService,
success : function(response) {
{
{
}
}
// code html
<form>
<ul class="liste_servch">
<input type="hidden" id="idClient" value="${client.idPersonne}" />
<c:forEach items="${listservclt}" var="servclt">
<li>
<input id="idService" type="checkbox" value="${servclt.idService}" />
<c:out value="${servclt.nomService}" />
</li>
</c:forEach>
</ul>
<input type="button" value="supp" onclick="AjaxPostdelete() ">
</form>
Try following;)
function AjaxPostdelete() {
var idServiceObjs = $('input[id=idService]');
var idServices = [];
for (var i = 0; i < idServiceObjs.length; i++) {
if(idServiceObjs[i].prop('checked')) {
idServices.push(idServiceObjs[i].value);
}
}
var idClient = $('#idClient').val();
$.ajax({
type : "POST",
url : "/cp/client/rmvclientserviceajax",
data : {idClient:idClient,idService:idServices},
success : function(response) {
}
}
}

SOAP webservice call to a method using jquery ajax that sends 2 parameters, how to catch the responses in a loop

I have a SOAP webservice created in c# (hosted on localhost) called soapService.aspx . It has a method called displayClass(String id, String theDate)
it returns. This returns following json
[{"lesson_id":2,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":"11:22","end_time":"14:22 ","notes":"test test","payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":3,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":4,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3}]
I found this using web service invoke method given on the web service description page.
I want to catch the response using ajax.
So far I wrote this
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data:instructorInput,
contentType:"application/json; charset:utf-8",
success:function(msg){
//process the msg
}
});
}
});
1) How do I invoke the web service method by passing parameters
2) How do i display all these json data in a table? Please help
Edit : Tried to post
data: "{'id': '" + instructorInputID + "','theDate': '" + instructorInputDate + "'}",
THis is the response I get from console
XMLHttpRequest cannot load http://localhost:18324/soapService.asmx/displayClasses. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:17182' is therefore not allowed access.
EDIT Two :
complete code : Still Error.. msg not defined
<pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#findClassBtn").click(function () {
displayClass();
});
function onSuccess(msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "soapService.asmx/displayClasses",
type: "POST",
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: onSuccess(msg)
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="Label1" runat="server" Text="Add Your Id"></asp:Label>
<p>
<asp:TextBox ID="instructorIdText" runat="server"></asp:TextBox>
</p>
<asp:Label ID="Label2" runat="server" Text="Add date (dd/mm/yyyy)"></asp:Label>
<p>
<asp:TextBox ID="instructordateText" runat="server"></asp:TextBox>
</p>
<asp:Button ID="findClassBtn" runat="server" OnClick="findClassBtn_Click" Text="Find Classes" />
<p>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</p>
</form>
<table id="table">
</table>
<pre>
Error: msg is not defined.
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: function (msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>

Ajax each function response is blank

I am doing search a product example using spring and ajax.I try to display the result using each function in a table. But getting blank response with headings being displayed. On firebug response field shows [].
Controller
#RequestMapping(value="searchproduct", method=RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody List<Product> searchProduct(#RequestBody #RequestParam(required=false, defaultValue="productName") String productName,
Map model) {
List<Product> productResults = productService.searchProductByName(productName);
return productResults;
}
DAOImpl
public List<Product> searchProductByName(String productName) {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Product.class);
criteria.add(Restrictions.ilike("productName", "%"+productName+"%"));
return criteria.list();
}
ServiceImpl
#Transactional
public List<Product> searchProductByName(String productName) {
return productDAO.searchProductByName(productName);
}
JSP
<script type="text/javascript">
$(document).ready(function() {
$('#searchForm').submit(function(event) {
var productName = $('#productName').val();
var json = { "productName" : productName };
$.ajax({
url: $("#searchForm").attr( "action"),
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(productResults) {
$('#searchTable').
append("<thead><tr><th>Product Name</th><th>Price</th></tr></thead>");
$('#searchTable').append("<tbody>");
var tableContent = "";
$(productResults).each(function(index, product){
tableContent +=
'<tr><td> ' +
product.productName+' </td><td> ' +
product.price+' </td></tr>';
});
$('#searchTable').append(tableContent);
$('#searchTable').append("</tbody>");
}
});
event.preventDefault();
});
});
</script>
<form id="searchForm" action="searchproduct.json" >
Product Name: <input type="text" name="productName" value="${product.productName}"
id="productName" />
<input type="submit" value="Search" />
</form>
<div id="formResponse">
<table id="searchTable">
</table>
</div>

partial tiles loading on ajax success in Spring tiles

I have a base tiles definition as:
<definition name="base_layout" template="/jsp/tools_tiles_layout.jsp">
<put-attribute name="body1" value="" />
<put-attribute name="body2" value="" />
</definition>
One page is defined as:
<definition name="tool_Home" extends="base_layout">
<put-attribute name="body1" value="/jsp/default/tool_body/list1.jsp" />
<put-attribute name="body2" value="/jsp/default/tool_body/list2.jsp" />
</definition>
Now one of my controller method load this page like:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String getListsById(Model model, String Id) {
List<String> list1 = null;
List<String> list2 = null;
try {
list1 = getList1FromDB();
list2 = getList2FromDB();
}
model.addAttribute("list1", list1);
model.addAttribute("list2", list2);
} catch (PersistenceException e) {
logger.error("error in ",e);
}
return "tool_Home";
}
Now i want to load only list2.jsp after a ajax call
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("Accept", "text/html;type=ajax");
},
type : 'POST',
url : "./add?fragments=body2",
data : formData,
cache: false,
contentType: false,
processData: false,
datatype : "json",
beforeSend: function(req) {
req.setRequestHeader("Accept", "text/html;type=ajax");
},
complete : function(jqXHR)
{
$("#body2").html(jqXHR.responseText);
}
});
And my controller method for this Ajax Call is
______________________________________________
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Model model, HttpServletRequest request) {
try {
List<String> list2 = getList2FromDB();
} catch (PersistenceException e) {
logger.error(e.getMessage(), e);
}
model.addAttribute("list2", list2);
return "tool_Home";
}
Here is my bean definition
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions" ref="TilesList"/>
</bean>
<bean id="TilesList" parent="parentTilesList">
<property name="sourceList">
<list merge="true">
<value>/WEB-INF/tiles.xml</value>
<value>/WEB-INF/tool-tiles.xml</value>
</list>
</property>
</bean>
But the partial loading is not working? what i am doing wrong?

Resources