jQuery POST and GET methods: Construct URL or use data param? - jquery-plugins

I am using the post and get methods for Ajax calls, and have a general question. There are two methods I've seen people use on the web:
Construct the URL and parameters by
hand
Use the data parameter
Both approaches work. I've included them below:
// Construct the POST URL by hand
queryStringDelimiter = "?";
settings.queryParam = "q";
$.post(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType);
// Use the data param
$.post(settings.url, {q:query}, callback, settings.contentType);
Are there any situations where you would construct the URL and parameters by hand instead of using the built-in data parameter? Any advantages of one method over the other?

I'd say the data approach is better since it formalizes the process and reduces the chances of producing errors while string building. Besides, the JQuery library will do the string building for you so its basically the same amount of work.

No reason I can think of why one would construct them by hand unless they didn't know of the data parameter if there's more than 1 or 2 parameters, it's also cleaner to keep them separated so if you have to loop through the data object and possibly modify some values you'd just iterate over the object instead of parsing a string manually.

If you let jQuery concatenating the data in to the appropriately formatted string you...
avoid having to duplicate that code...
avoid worrying about escaping the data for transport...
can easily switch between GET and POST requests in the future...
Really, the only argument AGAINST using the data parameter is if you already have the data in a concatenated format.

If I am using a GET I tend to just construct the URL, but when using POST I use the data parameter.
I do it because it is closer to how I was doing ajax calls before jQuery, when I wrote everything myself.

Related

Unable to send object value in next request json body

I am trying to send object value based on condition to the previous request.
From above,pricecheck i will get formtype value based on form type validation i have to send guests info in request..
here i am able to validate but not able to pass the object value if i try any string i can able to do,please help me.
You need to put a string value in vars, surrounded with quotes " and escape inner quotes\",as
vars.put("guests", "{ \"title\":\"Mr\", .... }");
You're violating 2 major best practices:
You're referring JMeter Variables like ${form} in the JSR223 Test Elements while you should be using vars.get('form') construction instead
You're using JavaScript language which is a performance anti-pattern, since JMeter 3.1 you should be using Groovy language for scripting
Check out Parsing and producing JSON article to learn more about reading and generating JSON in Groovy.
Also posting code in form of screenshots is not something you should be doing otherwise the chance of getting a comprehensive answer will be much less

How can I use a list function in CouchDB to generate a valid (/normal) ViewResults object?

I have a simple problem I need to solve, and list functions are my current attempt to do so. I have a view that generates almost what I need, but in certain cases there are duplicate entries that make it through when I send in edge-case parameters.
Therefore, I am looking to filter these extra results out. I have found examples of filtering, which I am using (see this SO post). However, rather than generate HTML or XML or what-have-you, I just want a regular ol' view result. That is, the same kind of object that I would get if I queried CouchDB without a list function. It should have JSON data as normal and be the same in every way, except that it is missing duplicate results.
Any help on this would be appreciated! I have tried to send() data in quite a few different ways, but I usually get that "No JSON object could be decoded", or that indices need to be integers and not strings. I even tried to use the list to store every row until the end and send the entire list object back at once.
Example code (this is using an example from this page to send data:
function(head, req) {
var row; var dupes = [];
while(row=getRow()) {
if (dupes.indexOf(row.key) == -1) {
dupes.push(row.key);
send(row.value);
}
};
}
Lastly, I'm using Flask with Flask-CouchDB, and I'm seeing the aforementioned errors in the flask development server that I'm running.
Thanks! I can try to supply more details if need be.
Don't you need to prepend a [, send a , after each row value except the last, and end with ]? To actually mimic a view result, you'd actually need to wrap that in a JSON structure:
{"total_rows":0,"offset":0,"rows":[<your stuff here>]}

Passing multiple values as query string is good or bad practice in MVC

In my page I ve to pass multiple values to controller.
My URL looks something like :
http://blah/Search/Page/?type=new&keywords=blahblah&sortType=Date
Is Passing multiple values as query string good practice in MVC ? or We can have slash separated URL, by using introducing custom routing?
NB: Lets consider all the values in my query string, are not secure / sensitive data.
I wouldn't consider it a bad practice, as long as it's not senstive data. It just depends if you want to write a custom route in your global.asax to handle it or not. The custom routes provide a cleaner url forsure. Also, for more savy users if they understand the concept on your site, it's more intuitive.
So consider this:
http://baseballcards/topps/1980 // search for baseball cards made by topps in the 1980s
http://recipes/deserts/pies // search for a desert recipe that are pies
http://code/csharpe/linq // search for csharp code that has linq examples
In these examples we can almost read the url like a sentence, making it more intuitive, giving a user the ability to plug and play. It clearly denotes the query almost like a breadcrumb, indicating exactly what the context will be. I personally like this. But either way is a good approach.
To extend with more parameters:
routes.MapRoute(
"SearchRecipes",
"Search/Recipes/{category}/{type}",
new { controller = "Search", action = "Recipes", category = "all" , type = ""}
);
Some examples:
Search/Recipes/Deserts/Pie
Search/Recipes/Dinner/Beef
Search/Recipes/Lunch/Salads
Select later (query string in route values) in case,
If you are concerned about header length.( By default get parameters are part of headers, and web server accept 1024 byte header length by default in IIS7).
Hide logical implementation of your code.
Url looks good and easier to remember.
Otherwise Both the approaches work equally.
I think passing search parameters in the query string is the way you should go, especially if all your parameters are optional. It also enables you to use normal method="get" forms without hassle.
I don't think "security/personal data" has anything to do with this since the query string is a part of the URL just like the path is.
IMO I think this is absolutely fine. I think it is actually preferable to use querystrings in MVC when the path represents the function and the querystring parameters represent the filters, e.g. as in a search.
However, I wouldn't use querystring parameters for data that represent information about the content retrieved. So I would include the year and month of an article in the path but not the page number if returning more than one page of articles for the year and month.

Should a JSON-P callback function accept a string?

I'm calling a REST API somebody else created. It supports JSONP to facilitate cross domain access.
The response I get back from the service looks like:
mycallback('{"token": "123456789"}');
Notice the single quotes wrapping the JSON data; Passing it as a string rather than a raw object. JQuery can handle this, but other libraries seem to expect a raw object instead.
mycallback({"token": "123456789"});
The raw object parameter makes more sense to me since it avoids the need to parse the JSON data, but I want to know for sure before asking the maintainer of the API to make the adjustment:
Which is most correct?
Passing a javascript literal (second) as shown here is more correct as it avoids deserializing the string back to a javascript object.
Passing a string is obviously a bad thing - you have two choices (#1 is preferred):
Ask the developer of the JSONP service to send proper JSONp instead of a string
Make your callback function smart so it uses something like payload = JSON.parse(payload); in case payload is a string.

GET vs POST in AJAX?

Why are there GET and POST requests in AJAX as it does not affect page URL anyway? What difference does it make by passing sensitive data over GET in AJAX as the data is not getting reflected to page URL?
You should use the proper HTTP verb according to what you require from your web service.
When dealing with a Collection URI like: http://example.com/resources/
GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.
PUT: Meaning defined as "replace the entire collection with another collection".
POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.
DELETE: Meaning defined as "delete the entire collection".
When dealing with a Member URI like: http://example.com/resources/7HOU57Y
GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.
PUT: Update the addressed member of the collection or create it with the specified ID.
POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.
DELETE: Delete the addressed member of the collection.
Source: Wikipedia
Well, as for GET, you still have the url length limitation. Other than that, it is quite conceivable that the server treats POST and GET requests differently; thus the need to be able to specify what request you're doing.
Another difference between GET and POST is the way caching is handled in browsers. POST response is never cached. GET may or may not be cached based on the caching rules specified in your response headers.
Two primary reasons for having them:
GET requests have some pretty restrictive limitations on size; POST are typically capable of containing much more information.
The backend may be expecting GET or POST, depending on how it's designed. We need the flexibility of doing a GET if the backend expects one, or a POST if that's what it's expecting.
It's simply down to respecting the rules of the http protocol.
Get - calls must be idempotent. This means that if you call it multiple times you will get the same result. It is not intended to change the underlying data. You might use this for a search box etc.
Post - calls are NOT idempotent. It is allowed to make a change to the underlying data, so might be used in a create method. If you call it multiple times you will create multiple entries.
You normally send parameters to the AJAX script, it returns data based on these parameters. It works just like a form that has method="get" or method="post". When using the GET method, the parameters are passed in the query string. When using POST method, the parameters are sent in the post body.
Generally, if your parameters have very few characters and do not contain sensitive information then you send them via GET method. Sensitive data (e.g. password) or long text (e.g. an 8000 character long bio of a person) are better sent via POST method.
Thanks..
I mainly use the GET method with Ajax and I haven't got any problems until now except the following:
Internet Explorer (unlike Firefox and Google Chrome) cache GET calling if using the same GET values.
So, using some interval with Ajax GET can show the same results unless you change URL with irrelevant random number usage for each Ajax GET.
Others have covered the main points (context/idempotency, and size), but i'll add another: encryption. If you are using SSL and want to encrypt your input args, you need to use POST.
When we use the GET method in Ajax, only the content of the value of the field is sent, not the format in which the content is. For example, content in the text area is just added in the URL in case of the GET method (without a new line character). That is not the case in the POST method.

Resources