How to use jquery Ajax data action - javascript

I am trying to figure out what and how to use the data parameter in a $.Ajax call. The problem is that I am unsure as to what the 'action' part in the data call is supposed to do. Is it an action in a controller? If yes, how do I reference it correctly?
var data = {
action: 'get-all-users',
data: JSON.parse($('form.post-list input').val())
};
$.ajax({
url: '/Users/index',
type: 'POST',
data: data,
success: function (response) {
* code *
}
});
What should 'get-all-users' result to? A Get function in a controller or what?
I am using ASP.NET MVC Core 2.0.

The property 'action' of the object 'data' is not related to controller (and it is not an action of controller).
The data parameter in $.ajax call contains data to be passed to server. So here you are gonna send the next object to the server:
var data = {
action: 'get-all-users',
data: JSON.parse($('form.post-list input').val())
};
And in order to receive and parse this object on the server side you should have appropriate C# class to provide ModelBinder with a correct data.
One more. In your example Index is an action in Users controller call will be made to. You can see it in 'url' parameter of $.ajax.
$.ajax({
url: '/Users/Index',
type: 'POST',
data: data,
success: function (response) {
* code *
}
});

Related

Ajax post not sending data to c# API Controller

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.

How to pass dates as parameters in Ajax url get call?

I have an Ajax call that tries to populate a highchart by calling an api. I am trying to access date values from ViewBag and passing them to the AJAX url, I end up getting an error
jQuery.Deferred exception: Jun is not defined ReferenceError: Jun is
not defined
the value from the ViewBag looks like June-2022. The ajax implementation looks like
$.ajax({
url: 'api/getProvinceData/'+ #ViewBag.reportinPeriod,
type: 'GET',
success: function (data) { }
});
so the complete api with the values filled up should look like when it gets the value in the ViewBag
url: 'api/getProvinceData/Jun-2022'
Why am I getting Jun is undefined in Ajax, while I am just accessing the value directly from the ViewBag? Any help is appreciated.
Because you are calling a view it will render it as 'api/getProvinceData/'+ Jun-2020, so the best way to access it is to just have it inside the quotes and not concatenate it so it will be
$.ajax({
url: 'api/getProvinceData/#ViewBag.reportinPeriod',
type: 'GET',
success: function (data) { }
});
and it will make the api correctly as
'api/getProvinceData/June-2022

How to pass array from js to controller

I have an array in my javascript file app/assets/javascript/pages/books_page.js :
var booksPage = Backbone.Model.extend({
defaults: {
authors: []
}
...
How can I pass that to my controller as a param. The path of my controller is app/controllers/books_controller.rb ?
I think I might need an ajax request and tried the following but it is not working:
$.ajax({
type: "post",
url: "/books_controller",
data: { list_authors: this.get('authors') },
});
Specifically, I am not sure what the url needs to be. Your help here will be greatly appreciated. Thanks.
Backbone (and jQuery) should do all the heavy lifting for you. Set the urlRoot in the model:
var booksPage = Backbone.Model.extend({
urlRoot: '/books',
...
});
and then call save on the instance to send the data to the server:
// Get or create `books` as a `booksPage` instance as usual...
// Then make some changes to `books` using `books.set(...)`...
books.save();
You can use JSON.stringify, and parse it from Controller JSON.parse(params).
$.ajax({
type: "post",
url: "/books_controller",
data: { list_authors: JSON.stringify(this.get('authors')) }
});
type: 'POST',
url: `/books/${this.id}`, // or '/books/' + this.id,
data: {
_method: 'put'
}
This will route you to the BooksController#update. You also need to merge the _method entry into your data object.
"NOTE: Because submitting forms with HTTP methods other than GET and POST isn't widely supported across browsers, all other HTTP methods are actually sent over POST with the intended method indicated in the _method parameter. Rails automatically detects and compensates for this." - Working with JavaScript in Rails

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)

jquery sending form data and a json object in an ajax call

I'm making a call to another ajax page, the call posts a json object.
I also need to send data from a form
(not using submit - I have the ajax call attached to a button which uses e.preventDeault()).
The call is as folows:
var myUrl = 'sendswatch-data.php';
$.ajax({
url: myUrl,
data: {'swatchid[]':swatchArray}, 'formdata':$('#orderData').serialize()},
type: "POST",
error: function(xhr, statusText, errorThrown){
// Work out what the error was and display the appropriate message
},
success: function(myData){
$('#tabsampleorder').html(myData);
$('.tabber').hide();
$('#tabsampleorder').show();
}
});
I have a form on the page id of formdata.
How do I send this as well as the json object? I've tried
data: {'swatchid[]':swatchArray}, 'formdata':$('#orderData').serialize()},
but that's generating an error.
You have an extra } after watchArray. Try removing that.
data: {'swatchid[]':swatchArray, 'formdata':$('#orderData').serialize()},
You can send data from the form as follows:
data : { swatchid: swatchArray, formdata: $('#orderData').serialize() }
You will need a parameter in the controller for every field that your add.

Categories

Resources