Ajax post not sending data to c# API Controller - javascript

I am trying to use $.Ajax() function to post data after a triggered event to my controller, but the data is not being sent. If I change the same function to "GET" method instead of "POST", it sends the data correctly, so I guess it has something to do with the VS2019 ASP.NET web project configuration, but I cannot find what it is.
The front code I am using is as follows:
marker.on('click', function (ev) {
let id = ev.target.features.properties.id
$.ajax({
url: "/public/pushDocuments",
method: "POST",
data: {
id: id,
objectname: "Prueba2",
bucketkey: "Prueba2"
},
contentType: "JSON",
success: function (data) {
launchViewer(data.urn);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
and in the server side:
[HttpPost]
[Route("public/pushDocuments")]
public async Task<IActionResult> postDocument(string id, string objectname, string bucketkey)
{
//Code here
}
but, as I said, the server is not getting the information. Nevertheless, if I change the method to GET in the server and front, I do get the data I am sending, but it is not the correct way to do it, as the work I want to do inside the server function is to save some data to a database. I have done it multiple times in other project and works, but I cannot figure out why it is not working on this one.

Related

Opening new page passing parameters without showing them on the URL

I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!
#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}

How can I send an object to the server on form submit without ajax?

I have an application that is written on the top of ASP.NET MVC 5 framework. For one page, I am using this awesome jQuery-QueryBuilder plugin to let the user create filters to narrow down the results of the dataset.
When the user submits the form "by clicking the submit button" I want to call a function builder.queryBuilder('getRules') provided by jQuery-QueryBuilder which returns and object that needs to be sent to the server. I don't want the request to be sent as string. Also I don't want to sent it as ajax request.
Here is what I have done. The following code is not working. When the server receives the request the rules are always null.
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$('#QueryBuilder_Rules').val(rules);
btn.closest('form').submit();
}
});
I tried to use AJAX to send the post request to the server like the code below shows. The code below worked fine. However, I don't want to use AJAX, I want to do the same thing using regular form post request
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$.ajax({
type: "POST",
url: url,
data: {Rules: rules}
});
}
});
How can I correctly send the rules object as an object not a string to the server using standard post request?
What is the problem in using Ajax?
You may consider doing the following:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({Rules: rules}),
dataType: "json",
contentType: "application/json",
success: function (json) {
}
[HTTPPost]
public void Rules(YourClass[] array){...}

Javascript send data to ActionResult that return RedirectToAction

I need to send data from javascript to my action that return RedirectToAction and some data.
My Js:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "GetAssetFilterID",
data: JSON.stringify({ 'VidLink' : clipData.src, 'InitialTime': clipData.markIn, 'EndTime': clipData.markOut }),
dataType: "json",
/*async: false,*/
});
My Action:
[HttpPost]
public ActionResult GetAssetFilterID(string VidLink, string InitialTime, string EndTime)
{
//some code
return RedirectToAction("Share", new { vid = VidLink, fil = filterName });
}
Notes
I had, on js, the url controller/action and the link that it
generated was controller/controller/action.
I don' get any error on console, nothing happens.
I don't need to use Ajax, I just want to send data from my Js to my
ActionResult. Ajax was the sample that I found.
Thanks in advance
You cannot do that. All you can do is return a url in the ajax result and use JS to redirect. Return the url in json or similar and in the ajax success or complete callbacks do your redirect.
Because the browser never posted its not expecting a response that would allow/cause a redirect.
Also duplicate of asp.net mvc4 ajax login: RedirectToAction not working

Trying to understand JQuery/Ajax Get/POST calls

Correct me if I'm wrong but it was my understanding that a POST was to be used if I was changing data, and a GET was to be used if I want to retrieve data.
Based on that assumption.
I have (MVC5) app.
My JavaScript
function MyLoadData(myValue) {
$.ajax({
method: 'POST',
url: '/Home/GetMyData',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ "MyValue": myValue}),
success: function (data) {
// Do Stuff
}
});
and my controller.
public JsonResult GetMyData(string myValue)
{ // Do Stuff }
This only works if I set the method: 'POST', if I set it to 'GET' it will still make the server call but not pass the myValue to the controller.
Also of note there is no data annotation on the GetMyData method.
In this scenario shouldn't I be using GET to get my data from the controller?
UPDATED based on comments:
function MyLoadData(myValue) {
$.ajax({
method: 'POST',
url: '/Home/GetMyData',
dataType: 'json',
data: { "MyValue": myValue},
success: function (data) {
// Do Stuff
}
});
Both POST and GET methods can pass the myValue to the controller.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
The primary difference between a GET and a POST is that the POST will also submit the form data. In your example, you can use a GET by appending ?MyValue=<myValue> to your URL and WebAPI will assign the value to the Action's parameter.
If the GET request needs to work then use this code block:
function MyLoadData(myValue) {
$.ajax({
method: 'GET',
url: '/Home/GetMyData?myValue=test',
success: function (data) {
// Do Stuff
}
});
Basically, you can use GET or POST to get the data. but in GET, the data is passed through query string. In POST it can be passed both through query string as well as body.
One real world scenario when to use POST-Suppose your method expects Customer parameter and you need to send Customer object as parameter, then you can send the json representation of Customer object through body.but its not possible through GET.
One more reason is security,if you use GET, your method can be called through browser.but if you use POST, the method can't be directly called.
These were the important difference.For more differences see this link - http://www.diffen.com/difference/GET_(HTTP)_vs_POST_(HTTP)

How to post data from DOM to nodejs via AJAX

I use POST method to send JSON data to the URL and I am utilizing from this data in order to render the page and I am rendering page via underscorejs. Is there any way to retrieve that data (in JSON format) and assigned them in another var in AJAX and send it as a data ?
I am trying to send data to the nodejs server in order to update Mongo DB. But there is no luck...
$(document).ready(function(){
$("#addContact").click(function(){
var responseArea = $('.actionArea');
$.ajax({
url: '/account/:id/added',
type: 'POST',
cache: false,
data: { contactId: this.model.get('_id') },
function onSuccess() {
$responseArea.text('Contact Added');
}, function onError() {
$responseArea.text('Could not add contact');
}
});
});
});
The error I am getting "Cannot call method 'get' of undefined"

Categories

Resources