Macy product API jQuery - javascript

I am a beginner programmer trying to form a URL to GET macy product information based on my keyword, here:http://developer.macys.com/docs/read/catalog_and_store_services/catalog/search#requesturl
They have 3 mandatory parameters, 2 of which is in the HTTP header, Accept and x-macys-webservice-client-id with another being in the query parameter, searchphrase.
According to the document, I have formed a jQuery function to GET products information:
function ajaxsearch(){
var terms = "reddress";
var macyurl = "https://api.macys.com/v4/catalog/search?searchphrase="+ terms;
alert(macyurl);
var apikey = "6zjre5gv8822t323e6wxj85a";
$.ajax({
url: macyurl,
headers:{
Accept: application/json,
x-macys-webservice-client-id: apikey
}
success: function(data){
alert("successful call!")
}
});
}
Question: Are the syntax of my function correct? I have checked this with the console and they are having problems with one of the headers, x-macys-webservice-client-id. Is this the correctly way to set up HTTP header parameters in my case?

Keys of an object should follow the same rules of naming a variable. If not, they should be quoted like this:
headers:{
Accept: "application/json", // you can quote the key here too, but the value has to be quoted.
"x-macys-webservice-client-id": apikey // the key must be quoted since - aren't allowed in key names. if apikey is not a variable, then it should be quoted too.
}, // Plus, you forgot to put a comma here to separate the entries
NOTE: If you don't know what do keys and values mean here is what I'm talking about:
{
key: value,
anotherKey: anotherValue,
// ...
}

Related

How can I create a fetch url with optional input fields within a web application

I am making an API call by using fetch method(GET) of Jquery. My question is, how can include empty input fields (totally optional, user may fill those areas, maybe not) into my fetch url. When I tried to send them as empty string, server is responding with a status code(400)- bad request.
These are the optional input fields to fill
MY JAVASCRIPT CODE
var fetchUrl = "https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode="
+iataOrigin+"&destinationLocationCode="
+iataDestination+"&departureDate="
+getFlightDepartureDate()+"&adults="
+getFlightAdults()+"&max="+getmaxTicket()
console.log(fetchUrl)
const settings = {
"url": fetchUrl,
"method": "GET",
"headers": {
"Authorization" : "Bearer myTokenInHere"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
For instance, I want to declare a URL such as 'adult number input field value' is not initialized, it's an empty string. Like this :
"&adults="
After trying this, server is not responding with a status code 200. I would be very thankful for your help.

How to pass an array of id's to delete using an endpoint rather than just one Id

I am trying to remove an array of id's that has to be removed in the backend. I am going to use an endpoint that will take this and execute the delete request with redux. It will be at the endpoint:
DELETE /api/v1/algo/configs?configIds=1,2,3
The 1, 2 , and 3 just represents dummy id's. Which are passed as query parameter and the response would look something like this:
{
"configIds": ["1","2","3"]
}
These above is what should be returned(the deleted array)
Here is what I have so far on the frontend, which is a handler that should asyncronously remove the array one by one so that rate limit is not going crazy.
async function deleteAll() {
for (const id in filteredStoppedConfigs) {
await actions.clearAllConfigs(filteredStoppedConfigs[id]);
}
}
filteredStoppedConfigs is an array of id numbers to remove
And here is an endpoint I have already implemented to delete one id. It works and does the job. But not sure how to implement it at the new endpoint which deletes a whole array. Essentially clearing the whole array
async function deleteConfig(configId) {
const options = {
method: 'DELETE',
headers: {
'content-type': 'application/json'
},
url: `${ALGOS_API_ROOT}/configs/${configId}`
};
return axios(options);
}
Been trying to research online but no one really asked a similar question. Any help is appreciated. Thanks!
OPTION 1
You will need to parameterize your array elements, creating a string that looks like DELETE /api/v1/algo/configs?configIds[]=1&configIds[]=2&configIds[]=3
OPTION 2
Use a POST or PATCH ROUTE and pass the JSON string of the array in the body of the request. POST|PATCH /api/v1/algo/configs
{
headers: ....,
....
body: {
ids: stringifiedArray
},
....
}
OPTION 3 NOT SUPER ENCOURAGED
A simple endpoint like so is fine: DELETE /api/v1/algo/configs.
Next, you can probably stringify your array JSON.stringify(arrayHere) and pass that stringified array as part of the body of the request like so:
body: {
ids: stringifiedArray
}
You will then receive this body parameter on your backend(whitelisting it), parse it and then used it for your desired operation
You can update deleteConfig as below to handle a request to delete for one config id as well as multiple config ids
async function deleteConfig(configId) {
const options = {
method: 'DELETE',
headers: {
'content-type': 'application/json'
},
url: configId.includes(",") ? `${ALGOS_API_ROOT}/configs?configIds=${configId}` : `${ALGOS_API_ROOT}/configs/${configId}`
};
return axios(options);
}
To handle a request to delete for one config id
deleteConfig(single_config_id);
To handle a request to delete for multiple config ids
deleteConfig(array_of_config_ids.join());

Using ajax to pass pass values to controller from view in MVC

I have the following in my Razor view file:
<button onClick="getFavouriteBooks()">Display Favourites</button>
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '#Url.Action("Favourites", "Home")',
data: ids,
dataType: "javascript"
});
}
</script>
And in my Home Controller, this action:
public async Task<ViewResult> Favourites(string[] ids)
{
// var bookList = code that retrieves list of all books
var favouriteBooks = bookList.Any(book => ids.Contains(book.Id));
return View("Index", favouriteBooks);
}
When user clicks 'Display Favourites' I get a 500 error for localhost/Home/Favourites. Can anyone help me see where I've gone wrong here?
Update: bookIds is an array of string Ids.
Update data with added contentType in ajax call as below and check again
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '#Url.Action("Favourites", "Home")',
// jQuery refers below mentioned contentType to serialize data in JSON format
// Without this, serialization will be url encoded string
contentType: "application/json; charset=utf-8",
// Assuming ids as a array of strings
// data to be an object that holds Action methods parameters as it's properties
// Stringify object before assigning to data
data: JSON.stringify({
ids: ids
}),
dataType: "javascript"
});
}
So I think there is a couple of things going on here.
I am assuming it’s a “get” request not a “post” request. Since you want to display the books. If you want to “get” all that match an id the easiest way would be to get the total response and loop through it. If it is just for a small project if it’s serious you want to want to change your SQL to find where ID.
But assuming you just want assistance with the JavaScript.
First of all if you put your javascript in line like that you need to also handle the response in line which isn't going to be syntactically very friendly. After all we are not writing php.
The second point about async functions is that you need a response which will happen asynchronously so need to await. Also need to handle the promise
I have simplified what I think is the solution here to use fetch instead of ajax to avoid all the jquery and Ajax setup with code pen but the logic should be there for you to follow up.
https://codepen.io/sijbc/pen/qBRrgBG?editors=1111
fetch('https://api.github.com/users')
.then(res => res.json())//response type
.then(data => console.log(data))
Also found this article which would be worth checking out
https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7

POST JsonArray using Ajax

I have a JSON Array that I am trying to post to SENDGRID using Ajax. Using Postman I am able to post with no issues however when I post the data in my .js file I keep getting an error (bad request = missing parameters).
Any help is appreciated.
Note: The values are in fact valid. I have removed the identifying information for safety.
CHROME PAYLOAD:
AJAX Call:
var mailUrl = "https://api.sendgrid.com/v3/mail/send";
var postdata = '{"personalizations": [{"to":[{"to email"}],"from": {"email":"from email"},"subject":"Hello, World!" , "content" : [{ "type":"text/plain" , "value":"TestMessage!" }]}]}'
$.ajax({
type: 'POST',
headers: {Authorization: "Bearer APIKEY"},
url: mailUrl,
contentType: "application/json",
data: JSON.stringify(postdata),
success: function (res) {
alert('ok');
},
error: function (res) {
alert('problems');
}
});
The problem seems to be with this part of json [{"to":[{"to email"}].You can use jsonlint to validate the json. Also JSON.stringify() method converts a JavaScript value to a JSON string.
But in your case postdata is already a string .
The string stored in the variable is a valid JSON. Calling JSON.stringify() on a JSON will escape all the special characters like " and that escaped string will not be deserialized to the object you intended.
While a string is still a valid JSON according to some specifications, The specifications for application/json stated in RFC4627
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members).
make the returned string invalid for post.
Sending the string itself without serializing it again will likely work.

how to get correct JSON object from flickr API

I used flickr photo search method to retrieve public photos.
when I run it with jquery, it works fine, I get the json object in correct form.
{
"photos": {
"photo": [
{
.........
}
]
},
"stat": "ok"
}
But when I use it with AngularJs, I got the same object with a prefix jsonFlickrApi
jsonFlickrApi({
"photos": {
"photo": [
{
......
}
]
},
"stat": "ok"
})
what I used in AngularJs is:
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.flickrPhotoSearch = function() {
return $http({
method: 'GET',
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3f807259749363aaa29c2fa93945&tags=india&format=json&callback=?',
dataType: 'json'
});
}
});
Please tell me how can I convert the second JSON to the first one.
Is there anything I can do in $http call or have to alter JSON object.
There was problem in the url.
This Url works for me.
https://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=3f807259749363aaa29c712fa93945&user_id=61495424#N00&format=json&nojsoncallback=?
You have to add nojsoncallback=1 to the url, like this
https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=XXX&format=json&nojsoncallback=1
And that remove the jsonFlickrApi function on response.
The above answer which says to add nojsoncallback=1 is correct, but I'd like to provide more context and reasoning behind it.
If you take a look at the documentation (which is poorly formatted in my opinion): https://www.flickr.com/services/api/response.json.html and scroll all the way to the bottom you will find, tucked away:
Callback Function
If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request.
To define your own callback function name, add the parameter jsoncallback with your desired name as the value.
nojsoncallback=1 -> {...}
jsoncallback=wooYay -> wooYay({...});
The key part being: If you just want the raw JSON, with no function wrapper, add the parameter nojsoncallback with a value of 1 to your request
Therefore, add this to your request and it will remove jsonFlickrAPI wrapper that you are seeing in your response: nojsoncallback=1
You are getting a JSONP response (notice the P) which is basically a function call with an argument that is the response you are expecting.
Easy solution for you: Create a function named jsonFlickrApi with a parameter response and you can do your handing in there.
At this point, I am not sure if you can define your function inside your service but try it. If not, you can define it outside.
Alternatively, try using $http.get function instead. Were you specifying the return accepted by the client in your jQuery original code?
EDIT
Try this setting the data type of the request using $http or $http.get without forgetting to specify the data property in the settings object.
$http({
url: 'http://localhost:8080/example/teste',
dataType: 'json',
method: 'POST',
data: '',
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});

Categories