jQuery .ajax() - add query parameters to POST request? - javascript

To add query parameters to a url using jQuery AJAX, you do this:
$.ajax({
url: 'www.some.url',
method: 'GET',
data: {
param1: 'val1'
}
)}
Which results in a url like www.some.url?param1=val1
How do I do the same when the method is POST? When that is the case, data no longer gets appended as query parameters - it instead makes up the body of the request.
I know that I could manually append the params to the url manually before the ajax request, but I just have this nagging feeling that I'm missing some obvious way to do this that is shorter than the ~5 lines I'll need to execute before the ajax call.

jQuery.param() allows you to serialize the properties of an object as a query string, which you could append to the URL yourself:
$.ajax({
url: 'http://www.example.com?' + $.param({ paramInQuery: 1 }),
method: 'POST',
data: {
paramInBody: 2
}
});

Thank you #Ates Goral for the jQuery.ajaxPrefilter() tip. My problem was I could not change the url because it was bound to kendoGrid and the backend web API didn't support kendoGrid's server paging options (i.e. page, pageSize, skip and take). Furthermore, the backend paging options had to be query parameters of a different name. So had to put a property in data to trigger the prefiltering.
var grid = $('#grid').kendoGrid({
// options here...
dataSource: {
transport: {
read: {
url: url,
contentType: 'application/json',
dataType: 'json',
type: httpRequestType,
beforeSend: authentication.beforeSend,
data: function(data) {
// added preFilterMe property
if (httpRequestType === 'POST') {
return {
preFilterMe: true,
parameters: parameters,
page: data.page,
itemsPerPage: data.pageSize,
};
}
return {
page: data.page,
itemsPerPage: data.pageSize,
};
},
},
},
},
});
As you can see, the transport.read options are the same options for jQuery.ajax(). And in the prefiltering bit:
$.ajaxPrefilter(function(options, originalOptions, xhr) {
// only mess with POST request as GET requests automatically
// put the data as query parameters
if (originalOptions.type === 'POST' && originalOptions.data.preFilterMe) {
options.url = options.url + '?page=' + originalOptions.data.page
+ '&itemsPerPage=' + originalOptions.data.itemsPerPage;
if (originalOptions.data.parameters.length > 0) {
options.data = JSON.stringify(originalOptions.data.parameters);
}
}
});

Related

Data passing error from javascript to controller

I'm working on ASP.NET MVC project , I want to get location dropdown selected value and according to that i need to load values to City dropdown , i implemented following code and location dropdown onselect event call the javascript function and javascript function call the controller method but when executing controller method locationId is null ,and i debug javascript and locationID is there till the this line data: JSON.stringify({ locationId: +locationId }), after that javascript returns error.but controller method get hit but locationId null
code for dropddowns
<div class="row">
<div class="col-sm-4">
#Localizer["Locations"]
<select id="locationDropDown" class="selectpicker form-control" asp-for="selectedLocation" onchange="getCityList()">
<option value="0"><None></option>
#foreach (var item in Model.LocationList)
{
<option value="#item.Id">#item.Name</option>
}
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Localizer["KioskGroup"]
<select id="cityDropDown" class="selectpicker form-control">
<option>---Select City---</option>
</select>
</div>
</div>
Javascript code
function getCityList()
{
debugger;
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ locationId: +locationId }),
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
controller method
public ActionResult GetZoneListBYlocationID(string locationID)
{
List<Zone> lstZone = new List<Zone>();
long locationId = long.Parse(locationID);
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(JsonConvert.SerializeObject(zones));
}
Your current code is sending the json string {"locationId":101} in the request body because you specified the contentType as application/json. This is useful when you want to send an object with multiple properties and your action method parameter is a DTO/POCO class type. Model binder will be reading from the request body and map it to the parameter.
In your case, all you are sending is a single value. So do not send the JSON string. simply create a js object and use that as the data attribute value. Also remove the contentType: application/json as we are not sending a complex js object as json string.
Also application/json is not a valid option for the dataType property. You may use json. But jQuery is smart enough to guess the value needed here from the response headers coming back from server. So you may remove it.
function getCityList() {
var locationId = $("#locationDropDown").val();
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
data: { locationID: locationId },
success: function (result) {
console.log(result);
// populate dropdown
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Now this data will be send in Form Data as locationID=101 with Content-Type header value as application/x-www-form-urlencoded and will be properly mapped to your action method parameter.
You should use the correct types. In your action method, you are using string as your parameter and later trying to convert it to long. Why not use long as the parameter type ? Also if zones variable is a list of Zone object, you can pass that directly to the Json method. No need to create a string version in between.
public ActionResult GetZoneListBYlocationID(long locationId)
{
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(zones);
}
Why you are stringify the data.Below one should work without stringify
data: { locationId: +locationId },
I was facing the same problem. and after that, I have tried below solution.
Hope it will help you.
ajax call is as follows:
$.ajax({
type: 'POST',
url: "/Account/GetCities",
dataType: 'json',
data: { id: $("#StateID").val() },
success: function (states) {
$.each(states, function (i, state) {
$("#CityID").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
The controller code is as follows:
public List<CityModel> GetCities(int id)
{
//your code
}
You can do in your application like this:
function getCityList()
{
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
dataType: 'json',
data: { locationId: locationId },
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
}
And your controller will be same as you have done.

jQuery API call to Entity Framework API Put method

I am using jquery to make an API call to an Entity Framework API Controller and I am trying to call the Put Method:
[ResponseType(typeof(void))]
public IHttpActionResult PutProfileIDClass(int id, ProfileIDClass profileIDClass)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != profileIDClass.id)
{
return BadRequest();
}
db.Entry(profileIDClass).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProfileIDClassExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
But when I make the API call via jQuery I get this error: 405 (Method Not Allowed)
What Am I doing wrong?
Here is my API call
var data = {
id: result.data[0].id,
profileID: result.data[0].profileID,
taken: 'true'
};
var json = JSON.stringify(data);
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
If you want to do a PUT request you should use the method: 'PUT' as part of your $.ajax call:
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
method: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
Do you have it installed on IIS? In that case, you have to configure it to handle your "PUT" request.
Right click on your website in the sidebar and go to properties.
Go to the "Home Directory" Tab
In the "applications settings", click on the "configuration" button
In the "Applications configuration" Window, there should be a Mappings Tab
Simply choose which file extensions you want to have mapped (in my case i wanted ASP to map GET, PUT, POST & DELETE), comma delimited. And thats it, not even a restart required.
Hope this helps

How can I get post parameters on ajax request in Symfony 3

I have an ajax request working fine. My problem is I do not really know how to use correctly my controller to get the datas in the format I would like.
I would like to use this kind of method:
$request->request->get('pseudo'); // will return "bob"
Here is my controller code:
public function mainPlayAction(Request $request)
{
if ($request->isXmlHttpRequest())
{
$allContent = $request->getContent(); // will return a string with this format "selectedBalls=34&selectedStars=11"
$selectedBalls = $request->request->get('selectedBalls'); // will return null
$selectedstars= $request->request->get('selectedStars'); // will return null
$all = $request->request->all(); // will return Array[0]
$response = [
'allContent' => $allContent,
'selectedballs' => $selectedBalls,
'selectedStars' => $selectedStars,
'all' => $all,
'success' => true,
"status" => 100
];
return $this->json($response);
}
}
Here is my ajax code
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: {
'selectedballs': selectedBalls,
'selectedStars': selectedStars,
'countGames': countGames
},
success: function (response) {
window.console.log(response);
},
})
You simply need to call ->get() on Request object to get the data passwed along with AJAX Request.
Like this,
$selectedballs=$request->get('selectedballs');
$selectedStars=$request->get('selectedStars');
$countGames=$request->get('countGames');
I found a good answer.
I deleted this line of code from my ajax request
contentType: "application/json; charset=utf-8"
And now I can retrieve my datas using
$request->get('selectedBalls');

Jquery ajax POST inconsistent with Hapijs server inject

Here is what my Ajax post looks like:
$.ajax({
type: "POST",
url: "/create",
data: {
"question": $('#question').val(),
"options": options
},
success: function() { window.location.href="/view"; }
});
Fairly simple. options is an array of string charachters. The problem is, when I receive on the server end with Hapijs, the request payload shows this object received:
{
question: "..etc..",
"options[]": [..etc...]
}
Why does it add a [] to the options variable name? Normally this wouldn't be a problem for me, but when I do the same thing and simulate a server request in my lab test like this:
var test = [..etc..]
// Simulate POST request
var serverOptions = {
method: 'POST',
url: '/create',
payload: {
question: 'Question',
options: test
}
};
It shows that the variable name received is just "options", not "options[]". How can I get jquery to stop adding the [] to the variable name when POSTing? Thanks

Pass object from javascript to Perl dancer framework

I have following ajax code to pass values to dancer framework.
BookSave: function(data) {
### data is an object that contain more than one key value pair
var book = Book.code;
$.ajax ({
type: "GET",
url : 'textbook/save/' + book + '/' + data,
success: function(data) {
if(data.status == 1) {
alert("success");
} else {
alert("fail");
}
},
});
},
In dancer:
any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
set serializer => 'JSON';
my $book = params->{book};
my $data = params->{data}; ## This I am getting as object object instead of hash
};
Is there any way to pass object from js and getting as hash in dancer?
First and foremost, consider using the http PUT or POST verbs, and not GET. Not only is doing so more semantically correct, it allows you to include more complex objects in the http body, such as your 'data' hash (serialized, per my comments below).
I've had limited success with Dancer's native AJAXy methods, plus there is a bug that causes problems in some versions of Firefox. So instead, I serialize and then deserialize the JSON object.
Suggested changes (note I suggested changes to your routes as well):
$.ajax ({
type: "PUT",
url : '/textbook/' + book,
data: {
myhash : JSON.stringify(data)
},
dataType: 'json',
contentType: 'application/json',
success: function (response) {
if (response.status == 1) {
alert("success")
} else {
alert("fail")
}
}
})
and your Perl Dancer code changes as follows:
any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
set serializer => 'JSON';
my $book = param('book');
my $data = from_json(param('myhash'));
};
I did not go as far as testing this code, but it should at least give you a good starting point to finish solving this problem.
Good luck with your project!

Categories

Resources