Trying to understand JQuery/Ajax Get/POST calls - javascript

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)

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 use jquery Ajax data action

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 *
}
});

Angular & ASP.NET MVC - Parameter is null when I pass a parameter to my backend Controller

If you look at the parameter of my ASP.NET MVC Controller clientId, it's always null.
the only way i can get it to not be null and actually pass the data through successfully is to create a class... but that gets tedious and I can't create a class for every backend function i make just to get this to work.
Is there a way to pass data successfully without creating a class?
Thank you for any help
Angular Factory
PlaylistsFactory.getUsersForClient = function (clientId) {
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: JSON.stringify(clientId)
});
};
Angular Controller
PlaylistsFactory.getUsersForClient(clientId)
.success(function (userList) {
console.log('success!');
});
ASP.NET MVC Controller
public JsonResult GetUsersForClient(string clientId) //clientId is always null unless i create an object
{
...
}
Try making your JSON parameter match the name of your C# parameter as well as encasing that in the data payload as JSON:
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: {clientId: JSON.stringify(clientId)}
});
};
i would recommend that you follow the rules of a RESTful API.
This means you should use the HTTP verbs like GET (getting data), POST (updating data), PUT (creating data), DELETE (deleting data). See http://www.tutorialsteacher.com/mvc/actionverbs-in-mvc
Then you could also add the parameter you want to pass into the route of your API: /Show/GetUsersForClient/{clientId}. See http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
In this case you disengage the problem of sending data in the body without having a ViewModel on the MVC-Controller side.
When you want to proceed with your solution, then try creating the Object before sending it:
PlaylistsFactory.getUsersForClient = function (clientId) {
var payload = { clientId: clientId }
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: payload
});
};
MVC / WebAPI also sometime choke when the content-type in the request header is text/plain or application/json. For example: a json-object will not be recognized properly by .Net when sent in text/plain.

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

Issue posting a large amount of data when using json in a query string

I'm posting four JSON objects to the server using a jQuery ajax request. Each object can be up to 30k characters. When all of the parameters are large the last parameter or even the last two parameters do not show up on the server. Everything works fine when the parameters are smaller though.
In chrome's network tab I see all of the parameters in their entirety. In fiddler I see the parameters in their entirety but the parameters that don't show up on the server will not have a name.
Fiddler
The structure of my request is as follows:
var formData = "json0=" + JSON.stringify(json0) + "json1=" + JSON.stringify(json1); //etc
$.ajax({
type: 'POST',
url: url,
data: formData,
success: function (result) {},
error: function() {}
});
I wouldn't think there would be a limit on a POST but it's acting like the data is being truncated for some reason. Server side I'm in Java using ParameterAware to retrieve the data but I think the issue is before it gets there since fiddler doesn't have the parameters' names.
Query strings are not made for large amounts of data, you should pass your data to your Ajax call in an object:
$.ajax({
type: 'POST',
url: url,
dataType: "JSON",
data: {
json0: json0,
json1: json1
// etc
},
success: function (result) {},
error: function() {}
});
Have a look at this article discussing the maximum length of query strings.
jQuery AJAX documentation: http://api.jquery.com/jQuery.ajax/

Categories

Resources