I have a folder on the server named uploads where uploaded files are stored (images) on requests made to the server to get a file I want to verify if the user has purchased it.
Ids of purchased products by the user are stored on a user object in MongoDB.
So I think that I should somehow attach the product id to the request or URL to then check if it exists in the user object, but where to attach it and how or maybe there is a better solution how would you tackle that?
As you already using MongoDB (even though I would suggest a relational DB for this case), I believe one approach would be to create a "middle" table called "purchased_images", linking the user_id with the image_id.
In the frontend you can write an ajax to pass the userid and itemid .You must session to do this.
when the user click verifyItembutton you can call a function by something like this
<button onclick="checkItem(userid,productId)">verifyItem</button>
Then in your script file you can call ajax
function checkItem(userid,proId) {
let data = {
userid,
proId,
}
$.ajax({
type: "post",
url: "/foo",
data: data,
success: function (response) {
console.log(response);
}
});
}
Now in your route file you can add a route /foo and you can perform mongo queries to find whether the user own it and return a boolean value the value will be sent to client side ajax and you can do whatever you need based on the state in success function of ajax
hope it helped you feel free to ask any doubts !
Related
The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}
I send a post to the server to create a new table entry in my database. Once the table entry is created I have the server respond with the id of the table entry. In the chrome developer tools I can see the response as just a singular number (i.e. if its the fifth entry in the table the server response is just 5). How do I store this information using javascript/YUI to be used later? Do I have to do something with the Y.io on: success function?
EDIT:
Y.io('/sessionsimulator/sessioncreate/', {
method: 'POST',
data: jdtoldstring,
headers: {
'Content-Type': 'application/json'
},
on: {
success: buildtable()
}
});
this is the code that posts the date/time and creates a session id. I can view the sqlite table afterwards and see that the session is created exactly how I wanted. the success function buildtable is the code that is called to generate the simulated data. within buildtable() i have a global variable that I am trying to set called sess_is
sess_id = Y.JSON.parse.responseText;
that statement lies within buildtable(), but when the table is created, the column that is filled with sess_id the variable is "undefined."
I can see in the developer tools the response to the url call /createsession is a number, I am just trying to pick that number and store it in sess_id variable.
If the response is just a number, you can access it from response.responseText in your IO success callback. It's a string, so you need to parse it as a number:
Y.io(url, {
//...
on: {
success: function (requestId, response) {
var id = parseInt(response.responseText, 10);
// do something with the id
}
}
});
It's usually a good idea to send JSON from the server and parse it in JavaScript when you want to send more information than just a number. You can read more about this in the IO User Guide, starting from the Response Object section.
In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!
$.getJSON(twitter_url, function(data){
loadtwit(data);
});
I am querying the twitter url via $.getJSON, for instance:
http://twitter.com/statuses/friends/stevejobs.json?callback=?
Sometimes the browser response is UnAuthorized if the tweets are protected. How can I handle that response to avoid triggering a login form.
success: loadtwit(data);
else: die silently
You can use $.ajax and provide an error handler.
$.ajax({
url: twitter_url,
dataType: 'json',
success: function(data) {
loadtwit(data);
},
error: function(xhr, testStatus, error) {
// handle error
}
});
I think I found something close to a workaround, if not an answer finally.
In my case I wanted to show a user's location, name, photo and some tweets based on their username which I knew, so I was trying to use this:
http://api.twitter.com/1/statuses/user_timeline.json?&screen_name=stevejobs&count=20&callback=?
Which trigger the popup that looks like a phishing scam when querying users with protected tweets.
So you can query a search for tweets based on a user like this:
http://search.twitter.com/search.json?q=from:stevejobs&callback=?
And you can also query a user like this:
http://api.twitter.com/1/users/show/stevejobs.json?&callback=?
The first query will get back tweets and won't ask for passwords because the protected users do not appear in search. Works, but doesn't return location and meta data for the user.
The 2nd query doesn't return tweets, but does return a boolean value for protected.
So if you put it together, you can get a complete search.
I hope someone finds this useful. I've been googling and reading the API all day. After I write the function, I'll come back here and post it.
I currently have a city that someone will enter into the system and I want to go from my javascript action to a rails action so i can get the city.id from the database. For example
my javascript
function get_city(city){
//city comes in like "Washington DC"
}
my rails action
def return_city_id
#city = City.find_by_name(params["name"])
return #city.id
end
Try ajax. You can setup path in routes.rb like find_city_id_by_name?name=Washington DC. Then you can use jquery to send request.
$.ajax({
url: 'find_city_id_by_name',
data: {'name' : city},
dataType: 'text',
success: function(id) {
alert(id);
}
});
In controller, you'll need to write single id as request response:
render :text => id
More information:
http://api.jquery.com/jQuery.ajax/
Although what you ask is definitely doable, querying back-end each time you need to fetch city id by its name sounds like a bad idea to me. If the name itself come from back-end (for example, you have list of cities for user to choose from), it's better to provide ids together with names (not visible to user, but somewhere in html).
You have to use AJAX to call any methods on the server-side.
function get_city(city){
$.getJSON("/ajax/city_id", { "city" : city }, function(data)
{
//Do something with data
});
}
/ajax/city_id is some action in some controller that returns JSON when you call it.