Get QueryStrings in browser url in jquery get request - asp.net-mvc

I would like to send a get request with jquery but the get function does not put the query strings in the address bar.I tried setting async to false but it still does not work.
$("#searchForm").submit(function (event) {
var x = $("#category").serialize();
$.get("Home/test", x, function (data) {
alert(data);
});
event.preventDefault();
});
The code above does not put the query strings in the address bar like a normal get request would.
hence i should have in the browser address bar something like Home/Text/?category=laptop
for example
any other solutions to specify what querystrings i can put in the address bar are welcome.
form id="searchForm" action="#Url.Action("Index")" method="get">
<input type="text" name="search" id="search />
<div id="price">
<input type="text" id="PriceMin" name="PriceMin" />
<input type="text" id="PriceMax" name="PriceMax" />
</div>
<input type="submit" value="submit"/>
</form>
as an example i dont want in the url querystrings of
?search=volvo&PriceMin=&PriceMax=
In other words, the input fields that are null should not be placed in url on a get request.
thx.
Found something and its working why i didnt think of this before is beyond me
$("#searchForm").submit(function (event) {
if ($("#PriceMin").val() == "") { $("#PriceMin").prop("disabled", true); alert("isnull");}
});
i disable the input field if it is "" just before the form is sent.Thus the query string of "priceMin" is not sent because the element is disabled.

The reason why the address bar doesn't change is because when you make an AJAX request with javascript, this request is made in the background. The whole point of AJAX is to make requests without navigating away form the current page. If you change the url in the address bar that would trigger the entire page to be reloaded. So what you are trying to achieve is impossible. You could use the fragment portion of the url (the part that follows the #). You could modify this part of the url without causing the browser to navigate away. Take a look at the following article: http://ajax.rswebanalytics.com/seo-for-ajax/#!ajax-crawlable-urls
Thus you could have the following url:
http://example.com/Home/Text/#category=laptop
In order to manipulate the fragment portion of the url in javascript you could use the window.location.hash property. Bear in mind though that this part of the url is never sent to the server. It is only intended to be used on the client.
As far as your second question about the empty strings is concerned, there's no way to achieve that in pure HTML. You will have to write javascript. Basically here you will have to subscribe to the .submit event of the form and manually build the target url that you will redirect to and exclude parameters that have empty values. Then manually redirect to this url using the window.location.href property. Also don't forget to cancel the default action of the submit by returning false.

Related

Change url from Action zf2

I am implementing a search an sending a search form to an action. Everything is working as expected but the url after the submit isn't very friendly and contain undesirable information. It is showing the whole request query array as a query string. I have a form with a fieldset element named 'album-search'.
Here is the url I am getting right now:
http://hostname/music_organizer/public/albums/page/1?album-search[term]=art&csrf=12b6065ab7ea428f02ad36a9cc363752-d96a14c1c7f1f2961112014a1e200e03&search=Search
Here is the url i am want to get:
http://hostname/music_organizer/public/albums/page/1?term=art
I have tried to set the query string in the action like this:
public function searchAction(){
//code
$this->getRequest()->getQuery()->set('term', $term);
//code
return $viewModel;
}
but no luck,
Thanks in advance
I thought your current rendering form should be like this
<form method="get" action="...">
<input name="term">
<input type="hidden" name="csrf" value="...">
<input type="submit" name="" value="Search">
<form>
Remove Submit Button:
Don't specify the submit button name while creating it
Remove CSRF element
If you don't required csrf element in querystring then remove it from your view page. but this csrf tag is very useful to avoid cross-site request forgery attacks.
--SJ

How rewrite URL?

I'm making a single web app.
I have a form with a POST method and an action value equal to "/login".
<form action="/login" method="POST">
<label for="mail">Email</label><input name="log" id="mail" type="text">
<label for="pass">Pass</label><input name="pass" id="pass" type="text">
<input type="submit">
When the submit button is press, server get the form, then return to the index page.
But, in the address bar, I have "local:5050/login" and would have "local:5050".
Can I remove the "login" mention ?
Since you are making a SPA, you will not want to have the POST method of the form actually complete. Generally this is done in dart by attaching a listener on the form element, within that listener you would then do a couple of things:
1) Cancel the default action (Also see: How do I prevent an on.submit event from changing/reloading the page?)
2) Get the values you're interested in from the form (or potentially take the entire form itself)
3) Send the values via an AJAX request to the server and listen for the response from the server to verify it was valid etc.
See the Dart tutorials on forms for more information on accomplishing the other steps.

Refactoring HTML Markup from POST to GET

I have the following mark up in an ASP.NET MVC view (this is a Twitter Bootstrap search box):
<form action="#Url.Action("Results", "Search")" method="post">
<input type="text" class="search-query" id="SearchTerm" name="SearchTerm" />
</form>
This code works as expected, but using a post here is causing problems.
How can I change this markup to pass the search query as a URL argument instead? I'm not really sure how to even approach this short of keeping the existing markup and then redirecting from the controller. I'm thinking there must be a more efficient way than that.
You should be able to change method="post" to method="get" and get the desired result. The form, with a get method setting, pushes the fields in the form to the querystring by its default behavior.
As a workaround, if the default behavior doesn't suit you, you could catch the submit event of the form, and do:
window.location = form.action + "?SearchTerm=" + document.getElementById("SearchTerm").value
Something like that, where form is a reference to the form element. You can build the link and redirect using javascript, which is a get request.

Submit a form as JSON (no AJAX)

Is it possible to submit form data as JSON, without using AJAX?
I've tried changing the enctype:
<form enctype="application/json"></form>
But that's not a valid value according on w3schools
The reason I would like this behaviour is that the requested URL will return a file, which I obviously can't do anything with if I use AJAX. I would like to send JSON data marked as Content-Type: application/json so that ASP.NET MVC will use its JSON binding.
Yes, you can serialize form like an object with plugin. I write a sample for you;
//Head
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.serialize-object.js"></script>
You can download plugin from here
//Form
<form id="frm">
<input type="text" name="Model[Firstname]">
<input type="text" name="Model[Lastname]">
<input type="text" name="ModelDetail[PhoneNumber]">
...
<button type="button" onclick="sendForm()">Send</button>
</form>
//JS
function sendForm(){
model_data = $("#frm").serializeObject();
$.ajax({
url: 'YOUR_SERVICE_URL',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(model_data),
dataType: 'json',
success:function(e){
// I know, you do not want Ajax, if you callback to page, you can refresh page here
}
});
Good luck!
Could you use JSON.stringify() to serialize your client side object and then stuff that into a hidden input and submit your form...and then in the controller side pull it back out of the Request.Form and deserialize it into your object?
[Edit]
Just saw in the comment section underneath of the original question that this was essentially a duplicate post and that this stackoverflow worked as a solution.
you can try;
// html
<form type="POST" action="/Home/Test">
<input id="foo" value="hede">
</form>
// dto
public class TestInDto{
public string foo {get;set;}
}
// home controller
[HttpPost]
void Test(TestInDto inDto){
var foo = inDto.foo;
}
As per W3C standards you can't pass the data like JSON using
<form enctype="application/json"></form>
Description
User agents that implement this specification will transmit JSON data from their forms whenever the form's enctype attribute is set to application/json. During the transition period, user agents that do not support this encoding will fall back to using application/x-www-form-urlencoded. This can be detected on the server side, and the conversion algorithm described in this specification can be used to convert such data to JSON.
The path format used in input names is straightforward. To begin with, when no structuring information is present, the information will simply be captured as keys in a JSON object
Reference DOC
You can now set form enctype='application/json' according to the new W3C standards published on 29 May 2014.
You can check it : http://www.w3.org/TR/html-json-forms/
You can use Form2js.It is designed by google and it is easy to use library.
https://github.com/maxatwork/form2js
Also , It can be modified according to user requirement .You can check their license .You can Find the basic examples of this javascript file using the link below:
http://form2js.googlecode.com/hg/example/test.html
Try this simple store your POST array in variable and then encode it as json obj.
like this-->
$postarray=($_POST);
$jsondata=json_encode($postarray);
Sorry its for PHP

MVC Ajax action relative to current controller

I'm trying to get an Ajax call from a link in a master page.
So I want to specify only the action relative to the current page/controller.
i.e.
$.ajax({
url: '/Save',
type: "GET",
// .. etc
});
I want to call the "Save" action of whatever controller served the page. I thought this would work straight off, but it doesn't appear to. Is there an elegant solution?
If you got this straight into your view, you could do
$.ajax({
url: '#Url.Action("Save")',
type: "GET",
// .. etc
});
If not, and javascript is in external file, you could attach url generated with Url.Action to element as data-? html5 attribute. And then dynamically read that attribute value before doing ajax call.
<input type="text" data-save-action-url="#Url.Action("Save")" />
You should never hardcode url's in asp.net mvc. Always use Url.Action. It inspects your routing configuration when generating urls, and will always return correct value according to it. If you hardcode urls, your application may become unusable when you change routing configuration. And you will have to change every single url in you application manually.

Resources