Direct ajax() or post() request of an URL - ajax

I have an url with query args:
var url = 'http://example.com/ajax.php?action=update_count&product=1234'
So, all query args I need to send for ajax request is already in URL, I tried this:
$.post( url, '', callback, 'json');
But, it won't send POST data.
So, I want to ask shall I do ajax/post request without data object/string, as query args are already in url.
Thanks.

If you put a parameter in the URL, it's treated like a GET parameter, not a POST parameter. You need to use whatever server-side mechanism is normally used for getting URL parameters. For instance, in PHP it would be $_GET['action'] and$_GET['product']`.
If you want to be able to send a parameter in either GET or POST, you can use PHP's $_REQUEST variable. It merges both sets of parameters.

Related

Send object with axios get request [duplicate]

This question already has answers here:
Axios get in url works but with second parameter as object it doesn't
(4 answers)
Closed 5 years ago.
I want to send a get request with an object. The object data will be used on the server to update session data. But the object doesn't seem to be sent correctly, because if I try to send it back to print it out, I just get:
" N; "
I can do it with jQuery like this and it works:
$.get('/mysite/public/api/updatecart', { 'product': this.product }, data => {
console.log(data);
});
The object is sent back from server with laravel like this:
public function updateCart(Request $request){
return serialize($request->product);
The same thing doesn't work with axios:
axios.get('/api/updatecart', { 'product': this.product })
.then(response => {
console.log(response.data);
});
I set a default baseURL with axios so the url is different. It reaches the api endpoint correctly and the function returns what was sent in, which was apparently not the object. I only get "N; " as result.
Axios API is a bit different from the jQuery AJAX one. If you have to pass some params along with GET request, you need to use params property of config object (the second param of .get() method):
axios.get('/api/updatecart', {
params: {
product: this.product
}
}).then(...)
You can pass either a plain object or a URLSearchParams object as params value.
Note that here we're talking about params appended to URL (query params), which is explicitly mentioned in the documentation.
If you want to send something within request body with GET requests, params won't work - and neither will data, as it's only taken into account for PUT, POST, DELETE, and PATCH requests. There're several lengthy discussions about this feature, and here's the telling quote:
Unfortunately, this doesn't seem to be an axios problem. The problem
seems to lie on the http client implementation in the browser
javascript engine.
According to the documentation and the spec XMLHttpRequest ignores the
body of the request in case the method is GET. If you perform a
request in Chrome/Electron with XMLHttpRequest and you try to put a
json body in the send method this just gets ignored.
Using fetch which is the modern replacement for XMLHtppRequest also
seems to fail in Chrome/Electron.
Until it's fixed, the only option one has within a browser is to use POST/PUT requests when data just doesn't fit into that query string. Apparently, that option is only available if corresponding API can be modified.
However, the most prominent case of GET-with-body - ElasticSearch _search API - actually does support both GET and POST; the latter seems to be far less known fact than it should be. Here's the related SO discussion.

Angular $http.delete request with body

So I looked at this post:
is an entity body allowed for an http delete request
Which seems to indicate that while it is 'ok' to do on some conceptual level, in practice it may not be doable because browsers just ignore it.
I have some express.js authentication middleware I need to get through, and I don't want to attach my user details to url params. All my other requests that need to authenticate attach these details to the body of the request.
Is there some way to force this? I saw some other posts where some people seemed to have success in passing a body with their delete request.
I am running a node/sails back-end. It always logs the body as undefined for a delete request. Is there any way to modify
The sails API pulls the id of the object to delete from the params, so we have to append the id to the url.
But if I want to pass some authentication details in a body for server-side verification before processing the delete request, I can't just stick them in an object as the second parameter of the delete request, like you can with $http.post.
Angular's post method automatically assigns whatever we insert as a second parameter to the body of the request, but the delete method does not.
Angular's $http.delete method does allow us to supply a config object as the second parameter, through which we can get access to the 'data' property. This is the same way post does it through it's second parameter.
So if we need to attach a body to a delete request we can use the following:
$http.delete('/api/' + objectToDelete.id, {data: {id: currentUser().id, level: currentUser().level}});
This will pass the object to delete's id in the url parameter, and my user credentials in the body as an object.
Honestly, everytime a trouble sounds like a "restriction of as REST", a rethink of the strategy and the philosophy might be a good idea.
I have some authentication middleware I need to get through
I don't want to attach my user details to url params
I'm not directly answering the question, but you should know that among the commons
URL parameters (or query, but URL anyway)
Body
there is a third option for "passing values to the server" :
request Headers
I'd just suggest to consider that third option to provide your credentials: request header.
Edit : following appendix would just apply to any "external" middleware, like a proxy server or whatever, not a true express middleware inside sails.js
In addition, that would be a good idea that your middleware stripped those headers before redirecting to the real action.

accessing request parameters Parse

I've got an issue when I try to access the request parameters.
As I've read, we have to use request.params.someParam to access the data we're sending via post or get. I'm following these steps, but I obtain an "undefined" response.
The code I use is the following one:
app.post('/hello', function(request, response) {
var query = new Parse.Query(Parse.Installation);
query.equalTo('UserName', request.params.userName); //trying to filter by UserName parameter
response.set('Content-Type', 'text/plain');
});
Does anyone know why do I obtain an undefined response and how to fix it?
Thanks
May I ask how do you specify your request params?
Because I found that when I tried to arrange a background job with request.params in Parse WebGUI, it requires to put a double quote (") for each key. Ex. {"userName":"John"}.
But when the request.params got passed into the background job, the double quote was escaped. Ex. {\"userName\": "John"}. So I can't get the param by request.params.userName
If I send the request via CURL then it all works fine.

JSON or Form Data? What's the preferred way to send data back to the server

I'm messing around with Django and AngularJS, attempting to send data back to my server using the $http resource. It looks like I could do this by either posting the data back as a form by setting the content-type as follows:
$http({
url: url,
data: form_encoded_data,
method: 'POST',
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
});
Or post back JSON in the request body with something like this:
$http.post(url, json_data)
.success(function(data, status, headers, config) {
...
}
In the first method, I can get access to the form data in my Django view via request.POST, and in the second, I can get access to the JSON via request.body. They both seem to work, but what's considered best practice?
I'm not sure what the convention for JSON data is. What I am sure of is that there is a convention for getting form data. In the absence of a compelling reason to use JSON, I would tend to think it's better to stick with the request.POST
I would go with using a form, it just makes sense intuitively and it is what I have used every time.
I prefer to use the $http service that accepts an object literal for configuration:
$http({method:'POST',url:'api/customers/add', data: customer})
.success(function(data) {
...
});
The result is promise object where you can immediately call .success. Its cleaner and easier to read IMO.
Note: customer is typically a data-bound object literal in JSON notation, but it does not have to be.

Values in the url is get or post?

I just wanted to know the values which I pass in URL are of Get type or Post type.
Neither or both. They are just part of the query string. Since they are part of the URI, they can appear in any kind of HTTP request.
(Some confusion might occur because PHP will populate the $_GET superglobal with them no matter what verb (GET, POST, PUT, etc) was used to make the request. Some other environments are more sensible, Perl tends to call them Query Params, ASP.NET uses Request.QueryString)
The browser sends any request that contains query parameters, those query parameters populate $_GET. As #Quentin says, they need not necessarily be from a GET request.
On the other hand,
A POST is made most commonly during form submission. $_POST variables are not a part of the URL, and are sent as POSTDATA.

Resources