I'm trying to post the entire asp.net form to a certain url.
I have tried:
$.post("http://www.someaddress.com", $("form").serialize());
I have also tried:
$.ajax({
type:"POST",
url:"http://www.someaddress.com",
data: $('form').serialize(),
success: function(){
alert('yay');
}
});
In both cases the submit is fine but no data is passed along with it.
When i test the form.serialize() in firebug console, this shows my form serialized just fine. When i view the submit in fiddler, i can see that the data part is not set. Maybe im not understanding the data part, but every single tutorial shows this as the way to go -> serialize the form and set that as data. What must i do to get my serialized form as the data in my request?
What am i missing? Also - why does the NET tab in firebug show all these requests as method OPTIONS?
is this
url:"http://www.someaddress.com"
just an example or do you try to access a foreign domain? (which would explain the problem).
Based on your comment, the ajax same origin policy does not allow to access a foreign domain.
You cannot do a Ajax request to a foreign domain. As this is not allowed (against security) in javascript to access a foreign page ( not on your domain )
Related
Im using Visual Studio 2012 and creating a web page using "ASP.NET Web Site (Razor v2)"
Im using Java to generate a random link;
<script>
var random = new Array();
random[0] = "example1.com";
random[1] = "pattern1.com";
random[2] = "specimen1.com";
</script>
<script>
function randomlink() {
window.location = random[Math.floor(Math.random() * random.length)];
}
</script>
A Random URL
When I click the A Random URL link it opens a random page from the list in the script above. I'ts all good, but because its a verry big list I need a way to do the same without having it in HTML because its slowing the loading of the page since its in the _SiteLayout.cshtml. Thanks.
Among your choices are the following options:
Send all the URLs to the client and have the client pick a random choice.
Have the server pre-pick the random URL and send only that one to the client (it can just be put directly into the <a> link. No need for javascript at all.
Make an ajax call to the server to request a random link and when that is returned, go to it.
Make a get request to the server and have the server return a redirect to a randomly chosen URL.
It sounds like you don't want to implement the first option if you have a zillion URLs.
The second option is probably the easiest as it requires only slightly modifying the generation of the page and requires no new server APIs. You just have to figure out how to select a random URL in your server-side environment.
The third and fourth options are the least efficient as they require a call to the server, a response from the server with the new URL and then a client redirect to the actual URL.
I would pass the random url with the page when it renders from the server. You can generate the url on the server using c#'s Random class.
A Random URL
Just pass a model that you reference in your view.
I need to implement single page applications using ASP Web Forms. I faced with a navigation problem. I need to use a navigation pattern like this:
http:// web site url / ... / page.aspx? {query string} # {ListId} / {ItemId}
When a user request a data from the server, the request on the server doesn't contain hash # (because this is a client-side feature). And it looks like this:
http:// web site url / ... / page.aspx? {query string}
So, actually I need two requests:
to get a page without hash and load javascript;
to handle hash data using javascript and async call required data from the server.
Is it possible to implement this logic with only one request?
Are there any best practices?
You can append ListId/ItemId to query string before sending request and read it regularly on a server.
var url = 'http://example.com?param1=10¶m2=20#1000';
var beforeHash = url.split('#')[0];
var itemId= url.split('#')[1];
var processedUrl = beforeHash + '&itemId=' + itemId;
If your request is not already fired from JavaScript, you will have to hook into link's click event...
Or maybe you can get rid of # entirely and scroll content via JavaScript (my guess is that you use # because of local anchors to jump to different places in document)?
BTW There is window.location.hash property.
Update:
Based on your comment the flow is like this:
User types URL with #ItemId
Server returns the page
JavaScript reads #ItemId from window.location, puts it into QueryString and makes a request
Server returns the page based on modified QueryString
In this situation the two-requests pattern seems to be the only viable option. By design server does not get #Item part (called fragment). So there is no way to guess ItemId upon initial request. If after second (ajax) request, you refresh #ItemId dependant parts of the page through JavaScirpt, user experience will not be hindered much.
I'm generally a fan of RESTful API design, but I'm unsure of how to apply REST principles for a validation API.
Suppose we have an API for querying and updating a user's profile info (name, email, username, password). We've deemed that a useful piece of functionality to expose would be validation, e.g. query whether a given username is valid and available.
What are the resource(s) in this case? What HTTP status codes and/or headers should be used?
As a start, I have GET /profile/validate which takes query string params and returns 204 or 400 if valid or invalid. But validate is clearly a verb and not a noun.
The type of thing you've described is certainly more RPC-style in its' semantics, but that doesn't mean you can't reach your goals in a RESTful manner.
There's no VALIDATE HTTP verb, so how much value can you get from structuring an entire API around that? Your story centers around providing users with the ability to determine whether a given user name is available - that sounds to me like a simple resource retrieval check - GET: /profile/username/... - if the result is a 404, the name is available.
What this highlights is that that client-side validation is just that - client side. It's a UI concern to ensure that data is validated on the client before being sent to the server. A RESTful service doesn't give a whit whether or not a client has performed validation; it will simply accept or reject a request based on its' own validation logic.
REST isn't an all-encompassing paradigm, it only describes a way of structuring client-server communications.
We have also encountered the same problem. Our reasoning for having the client defer to the server for validation was to prevent having mismatched rules. The server is required to validate everything prior to acting on the resources. It didn't make sense to code these rules twice and have this potential for them to get out of sync. Therefore, we have come up with a strategy that seems to keep with the idea of REST and at the same time allows us to ask the server to perform the validation.
Our first step was to implement a metadata object that can be requested from a metadata service (GET /metadata/user). This metadata object is then used to tell the client how to do basic client side validations (requiredness, type, length, etc). We generate most of these from our database.
The second part consist of adding a new resource called an analysis. So for instance, if we have a service:
GET /users/100
We will create a new resource called:
POST /users/100/analysis
The analysis resource contains not only any validation errors that occurred, but also statistical information that might be relevant if needed. One of the issues we have debated was which verb to use for the analysis resource. We have concluded that it should be a POST as the analysis is being created at the time of the request. However, there have been strong arguments for GET as well.
I hope this is helpful to others trying to solve this same issue. Any feedback on this design is appreciated.
You are confusing REST with resource orientation, there's nothing in REST that says you cannot use verbs in URLs. When it comes to URL design I usually choose whatever is most self-descriptive, wheather is noun or verb.
About your service, what I would do is use the same resource you use to update, but with a test querystring parameter, so when test=1 the operation is not done, but you can use it to return validation errors.
PATCH /profile?test=1
Content-Type: application/x-www-form-urlencoded
dob=foo
... and the response:
HTTP/1.1 400 Bad Request
Content-Type: text/html
<ul class="errors">
<li data-name="dob">foo is not a valid date.</li>
</ul>
A very common scenario is having a user or profile signup form with a username and email that should be unique. An error message would be displayed usually on blur of the textbox to let the user know that the username already exists or the email they entered is already associated with another account. There's a lot of options mentioned in other answers, but I don't like the idea of needing to look for 404s meaning the username doesn't exist, therefore it's valid, waiting for submit to validate the entire object, and returning metadata for validation doesn't help with checking for uniqueness.
Imo, there should be a GET route that returns true or false per field that needs validated.
/users/validation/username/{username}
and
/users/validation/email/{email}
You can add any other routes with this pattern for any other fields that need server side validation. Of course, you would still want to validate the whole object in your POST.
This pattern also allows for validation when updating a user. If the user focused on the email textbox, then clicked out for the blur validation to fire, slightly different validation would be necessary as it's ok if the email already exists as long as it's associated with the current user. You can utilize these GET routes that also return true or false.
/users/{userId:guid}/validation/username/{username}
and
/users/{userId:guid}/validation/email/{email}
Again, the entire object would need validated in your PUT.
It is great to have the validation in the REST API. You need a validation anyway and wy not to use it on the client side. In my case I just have a convention in the API that a special error_id is representing validation errors and in error_details there is an array of error messages for each field that has errors in this PUT or POST call. For example:
{
"error": true,
"error_id": 20301,
"error_message": "Validation failed!",
"error_details": {
"number": [
"Number must not be empty"
],
"ean": [
"Ean must not be empty",
"Ean is not a valid EAN"
]
}
}
If you use the same REST API for web and mobile application you will like the ability to change validation in both only by updating the API. Especialy mobile updates would take more than 24h to get published on the stores.
And this is how it looks like in the Mobile application:
The response of the PUT or POST is used to display the error messages for each field. This is the same call from a web application using React:
This way all REST API response codes like 200 , 404 have their meaning like they should. A PUT call responses with 200 even if the validation fails. If the call passes validation the response would look like this:
{
"error": false,
"item": {
"id": 1,
"created_at": "2016-08-03 13:58:11",
"updated_at": "2016-11-30 08:55:58",
"deleted_at": null,
"name": "Artikel 1",
"number": "1273673813",
"ean": "12345678912222"
}
}
There are possible modifications you could make. Maby use it without an error_id. If there are error_details just loop them and if you find a key that has the same name as a field put his value as error text to the same field.
I have a page that's sending some POST data in plaintext to an aspx page I wrote:
firstname: John
lastname: Doe
accountid: 123
I need to take this POST data and run it through an encrypting algorithm so the data ends up like so:
firstname: AKFJULKHI
lastname: IDKLNZUI
accountid: RIQLKKNIC
After encoding it, I then need to POST it to another aspx page that's expecting this encoded data. I cannot modify this page. Essentially, I'm writing an in-between page whose purpose is to take some plaintext data, encode it using a proprietary algorithm, and pass it to another page that expects this encrypted data. I realize it's a useless security feature because the user knows what the data is before the encryption, but I cannot modify the other pages and have to stick to the API.
My question is, what is the easiest way of doing this? Response.Redirect will convert it to a GET request, and Server.Transfer will not change the URL on the client side. I could do a manual POST request and then do a Response.Write, but that seems like a really roundabout way of doing it.
I think you may want to approach this with a module instead. The HttpModule intercepts the request, can change the request and then the request continues on to the target and the target page is unaware that the request was modified.,
ref: http://www.codeproject.com/Articles/30907/The-Two-Interceptors-HttpModule-and-HttpHandlers#HttpModuletheeventbasedpreprocessor
HTTP does not support POST redirects.
Instead, you can render a simple page with an HTML form containing hidden inputs with your modified data and pointing to the new URL, then automatically submit the form using Javascript.
I read some values from text boxes and send them via jQuerys post method to an server. If the user enters text containing something like "bla bla", the call fails. The data looks like this in that case:
var data = { myKey: 'bla <script> bla' };
And I send it to the server like this:
$.post(targetUrl, data, function(x) {...});
On the server side (an Asp.Net web form) it looks like the call never reaches the server. Any hint how to solve that? If there's a convenient function which cleans data from bad tags, that would be fine too.
Have you desactivate the validate request of your aspx page?
add this in your page declaration: validateRequest="false"
To strip tags using a jQuery function:
jQuery.fn.stripTags = function() {
return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};
Do you receive a page_load in ASP.NET? If yes, isn't there anything in Request.Params?
I would suggest escaping your values client side using the javascript escape function as shown below
var data = { myKey: escape('bla <script> bla') };
Once you have done that, you can retrieve the correct value on the server side using the following (.Net Code)
HttpUtility.UrlDecode(param_value_to_decode)
I tested this and the correct value is being passed correctly to the server via the post request.
Hope this helps.
Additional Info : I forgot to mention the cause of the error. When inspecting the request using firebug, it returns a "500 Internal Server Error - A potentially dangerous Request.Form value was detected from...". This is a built in protection mechanism from asp.net to protect against script injection. The following page directive ValidateRequest="false" did not solve the problem as expected (Works in traditional WebForms). It might be something specific to the Mvc platform, not to sure. The above solution does work, so just use that.
Regards
G