Jquery say that I try to make a cross domain call - javascript

Becouse I have many dinamicly created data (in popover window) I need to create ann function like this:
function addOffer() {
var token = document.getElementsByName('_token')[0].value;
var s1 = $('.hstart').val();
var p1 = $('.spin').val();
$.ajax({
url: '/offers',
type: 'POST',
data: {
price: p1,
start: s1,
_token: token
},
});
};
Now I call this function with:
$('.addBid').click(function() {
addOffer();
});
and request is send to backend but then I get:
k.cors.a.crossDomain.send # jquery.js:8630
UPDATE:
In Laravel backend I have only:
public function store(Requests\OfferRequest $request)
{
$offer = new Offer($request->all());
Auth::user()->offer()->save($offer);
Alert::success('Offer is succesfully added!', 'Good job!')->persistent("Close");
return Redirect::back();
}

Related

Calling an ASP.NET MVC-view via ajax does not work

I am trying to call a view with an ajax-Call, passing an Id to the Controller-method. The Id is passed, everything is fine until I call the view in the return-Statement. Nothing happens.
$("#btnCreatePackage").click(function () {
var workflowId = $("#workflowId")[0].value;
$.ajax({
url: '#Url.Action("Create", "package")',
type: 'get',
data: { id: workflowId },
success: function (data) {
return data;
},
timeout: 500
});
});
public ActionResult Create(int id) {
IList < Workflow > workflows = WorkflowService.GetWorkflowList();
ModifyPackageViewModel vm = new ModifyPackageViewModel
{
Package = null,
Workflow = workflows.SingleOrDefault(x => x.Id == id),
Workflows = workflows,
Hosts = ScalingService.GetHostList(),
SelectedHostNames = new List<string>(),
Factor = 1
};
if (!vm.SelectedHostNames.Any()) {
if (vm.Hosts.Any()) {
vm.SelectedHostNames.Add(vm.Hosts.First().Name);
}
}
return View(vm);
}
The curious thing is, if i#m calling the view via #Url.Action without passing the Id with the following code, it works.
<a href="#Url.Action("Create")">
<div class="submenu-item add">
neues paket anlegen
</div>
</a>
public ActionResult Create() {
IList<Workflow> workflows = WorkflowService.GetWorkflowList();
ModifyPackageViewModel vm = new ModifyPackageViewModel
{
Package = null,
Workflow = workflows.FirstOrDefault(),
Workflows = workflows,
Hosts = ScalingService.GetHostList(),
SelectedHostNames = new List<string>(),
Factor = 1
};
if (!vm.SelectedHostNames.Any()) {
if (vm.Hosts.Any())
{
vm.SelectedHostNames.Add(vm.Hosts.First().Name);
}
}
return View(vm);
}
In both cases the Controller-method is called, goes through to the end without errors, in the first case nothing happens, in the second case everything is fine.
Anyone any ideas??????
Thanks, daniel
You can't return the data from an ajax call. You can store it in a variable declared outside, or do something inside your success handler.
This works just as well with your success handler (success: function(data) ...). The main thing to remember is the scope of the data that is returned from your controller.
EX:
var outsideVariable; // You can store the data in here for later if you need to
$.ajax({
url: '#Url.Action("Create", "Package")',
type: 'GET',
data: { id: workflowId }
}).fail(function (data) {
// Fail handler
}).done(function (data) {
// Success, Do Something
YourFunctionThatProcessesData(data);
// Or store the data into a variable that has outside scope
outsideVariable = data;
}).always(function () {
//Do this no matter what
});
function YourFunctionThatProcessesData(data)
{
// do stuff with the data
}
At least I fixed it, I did not need an ajax-Call, instead I just used this:
$("#btnCreatePackage").click(function() {
var workflowId = $("#workflowId")[0].value;
window.location.href = '#Url.Action("Create", "package")/' + workflowId;
});
It can be that simple........

ASP.NET Core Antiforgery Token without the form

Is it possible to have antiforgery tokens without forms? I have an ajax post call that I would like to make that needs an antiforgery token. However, most examples I have seen are asking for forms. This is what I have so far:
<script>
$(document).ready(function () {
var SessionId = document.getElementById("Id").value;
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
if (output[i].Mine == true) {
p.setAttribute("class", "Sender Me");
q.setAttribute("class", "Message");
} else {
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
}
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
return false;
});
</script>
This just gets its input from a textbox and a button that is not attached to a form.
Ajax request could send the anti-forgery token in request header to the server.Refer to solution in Handle Ajax Requests in ASP.NET Core Razor Pages.
<script type="text/javascript">
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
</script>
<script>
$(document).ready(function () {
var SessionId = document.getElementById("Id").value;
var form_data = {
"SessionId": SessionId
};
var headers = {};
headers['XSRF-TOKEN'] = gettoken();//header name could be changed
$.ajax({
url: "/Home/testPost",
method: "POST",
data: JSON.stringify(form_data),
headers:headers,
contentType: "application/json",
success: function (result) {
console.log(result);
//...
},
error: function (error) {
console.log(error);
}
});
//...
});
Then you need to configure the antiforgery service to look for the XSRF-TOKEN header you have defined:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
Of course,you need to use correct model binding and [ValidateAntiForgeryToken] attribute for your action.
The AntiforgeryToken is there to prevent cross site request forgery. So you should really use it. The easiest way to get one in jQuery is to render a dummy, hidden form on the page. Then the you can use your javaScript to copy the token from the dummy form and include it in your ajax post.
You need to add it manually. Try this:
var token = $("[name='__RequestVerificationToken']").val();
And then post it with your data:
data: {
__RequestVerificationToken: token,
JSON.stringify(form_data)
}
EDIT:
As #AndresAbel mentioned, you can copy the token from the form and send it in ajax post:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
}
Then in in your script:
var token = $('input[name="__RequestVerificationToken"]', $('#__AjaxAntiForgeryForm')).val();
Then send it in ajax:
data: {
__RequestVerificationToken: token,
JSON.stringify(form_data)
}
Don't forget to add the annotation [ValidateAntiForgeryToken] for your method in the controller.

ASP.NET MVC call Controller Action with parameter from javascript function

I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.

Ajax GET call to webAPI

In my javascript file i am trying to make a GET Request to my webAPI, the entire request is ignored. the two alerts before and after the request are outputted but nothing within my request.
This is my GET request made in my javascript file:
alert("before Get");
$.ajax({
url: '/api/Map/',
type: 'GET',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function () {
alert("error in request");
}
});
alert("after Get");
My WebAPI file and the method im trying to get:
// GET: api/Map
public IEnumerable<string> Get()
{
SetContext();
List<ICoordinate> BoundingBox = CreateBoundingBox(_LoadedConfiguration.StartPosition);
List<string> LayerNames = _LoadedConfiguration.GetAllLayerNames();
Map LoadedMap = new Map(BoundingBox, LayerNames, _persistenceFactory, _LoadedConfiguration);
GeoJson.IGeoJsonGeometry MapFeatureCollections = (IGeoJsonGeometry)LoadedMap.GetAsGeoJsonObject();
return new string[] { MapFeatureCollections.ToString()};
}
I am trying to return the string of "MapFeatureCollections"

How to print receipt without print dialog box in client side

I want print receipt in client side without print dialog box, i am using mvc this is my solution to achieve my problem.
EPSON printer was installed in my system.This solution is working when host in my local iis but its not work when host in server and accessing from my local system getting "An error occurred while processing your request" error. In server no printer is installed.
$.ajax({
type: "POST",
url: '../Service/print',
cache: false,
data: { iprintData: printData, iprinterName: sPrinterName },
success: function (data) {
// alert('print Send Successfully');
},
error: function (ex) {
alert(ex.responseText);
// alert('error while Seding print');
}
});
this is my code in controller
public JsonResult print(string iprintData, string iprinterName)
{
Boolean bflag = false;
System.Web.HttpContext.Current.Session["_printData"] = iprintData;
PrintDocument printDocument = new PrintDocument();
printDocument.PrintController = new StandardPrintController();
printDocument.PrintPage += PrintDocumentOnPrintPage;
printDocument.PrinterSettings.PrinterName = iprinterName;
//printFont = new System.Drawing.Font("Arial", 10);
printDocument.Print();
bflag = true;
return Json(bflag, JsonRequestBehavior.AllowGet);
}
public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_height, new_width);
Graphics g = Graphics.FromImage((Image)new_image);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
private void PrintDocumentOnPrintPage(object sender, PrintPageEventArgs e)
{
string printstring = System.Web.HttpContext.Current.Session["_printData"].ToString();
string path = HttpContext.Server.MapPath("~/content/Images/logo.png");
System.Drawing.Image img = Image.FromFile(path);
//img = resizeImage(img, 80, 60);
e.Graphics.DrawImage(img, 6, 100);
e.Graphics.DrawString(printstring, new System.Drawing.Font("ronnia", 9), Brushes.Black, 10, 150);
}
can any one help me from this ?
first you have to write windows service that contain HttpListener.
write your printing code inside the service
Install the service in client machine
call that service using ajax like below.
function PrintReceipt() {
var PrintData = JSON.parse($("#receiptData").html())
if (PrintData.length > 0) {
$.ajax({
type: "POST",
url: "http://localhost:41963/printOrder",
data: JSON.stringify({ "PrintData": PrintData }), //reciept data
crossDomain: true,
success: function (response) {
},
error: function () {
}
});
}
}
set System.Drawing.dll property
Copy Local=true

Categories

Resources