Forgive me if I have titled this tread wrong, I don't know the correct terminology.
I have a link with values included, they are: id and environment therefore the url it formatted such ad https://foo.com?id=1234&e=s
With this url I need to take the id and the environment (Stage or production) and create a post body to set a flag as true.
So if e=s (environment = stage) I need post to
https://services-stage.foo.com/api/account//flag
Or if e = p (production)
https://services.foo.com/api/account//flag
Where = the id in the url
With POST body:
{
"type": OptionFlag,
"flag": true //Flag should be set to true
}
My problem is I don't know where to start with my limited javascript knowledge. I have created GET requests form api's in the past but never POST and never with parameters in the URL.
I now understand how to handle the post, however I am still at a loss on how I would get the Id and the environment data from the url to then pass them to the ajax url in the function.
function CustomerId(){
//Function for getting id number from URL
}
function apiEnvironment(){
//Function for getting environment from URL
}
function OptOut(CustomerId, apiEnvironment) {
jQuery.ajax({
type: 'POST',
url: apiEnvironment + '/api/v1/account/' + CustomerId + '/optOut',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data : data,
success: {
}
});
}
This Is what I have so far...
Related
I am attempting to recover a WordPress user's ID on the backend PHP after receiving an AJAX post request.
I was unable to use wp_get_current_user() within my AJAX handler function on the backend (I'm not entirely sure why this fails)
My solution was to use wp_localize_script to pass wp_get_current_user()->ID to the browser. I am concerned that the user might be able to change the user ID within their browser and pose as another user. Is this possible? If so, is there a better way to get the user's ID in an ajax POST?
The following is my current setup:
JS Ajax
var fd = new FormData();
fd.append('user_id', ajax_object.user_id);
fd.append('action', 'tb_upload');
jQuery.ajax({
type: "POST",
async: false,
url: ajax_object.ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function (resp) {
console.log("in success!");
if (resp != null) {
console.log(resp.data);
} else {
console.log("Error: Response is null!");
}
}
});
I am trying to write a script that gets COVID-19 numbers from the Ontario Database, but I keep getting the following error:
"invalid value \"_\""
Upon further investigation, the URL that is trying to be accessed contains the following parameter:
&_=1610496351832
As you can see in my code below, I never define such a variable:
var data = {
resource_id: '8a89caa9-511c-4568-af89-7f2174b4378c' // the resource id
};
$.ajax({
dataType: 'jsonp',
data: data,
url: 'https://data.ontario.ca/api/3/action/datastore_search'
});
Is there any way I can remove the _ object from the request?
The file I am trying to access is located at the following URL, where data is the resource_id.
https://data.ontario.ca/api/3/action/datastore_search?resource_id=8a89caa9-511c-4568-af89-7f2174b4378c
That is an automatic value generated by JQuery to avoid the cache.
Add the following to your script if you want to get rid of the underscore param:
var data = {
resource_id: '8a89caa9-511c-4568-af89-7f2174b4378c' // the resource id
};
$.ajax({
dataType: 'jsonp',
data: data,
type:'GET',
cache: true,
url: 'https://data.ontario.ca/api/3/action/datastore_search'
});
It only occurs in GET requests, you can play around with this setting. But remember, the automatic underscore param is included intentionally to avoid the request cashing.
I want to access some data from selected work items.
Below is my working code.
function postApiData(ApiUrl, responseBody, token) {
var res = '';
$.ajax({
type: 'POST',
async: false,
url: ApiUrl,
contentType: 'application/json',
data: JSON.stringify(responseBody),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + _token));
},
}).done(function (data) {
res = data;
});
return res;
};
var d = {
"ids": itemlist,
"fields": ["System.Id", "System.WorkItemType", "System.Title", "System.AssignedTo", "System.State", "System.Tags", "cust.PID", "cust.Product", "cust.ReleasedToProduction"]
};
var itemdata = postApiData('https://dev.azure.com/COMP/products/_apis/wit/workitemsbatch?$expand=relations&api-version=5.1', d, '');
However, $expand is not working here to get relations. query gives the result and always ignores $expand.
I have also tried to pass $expand in request body, but it is also not working. Can anyone please guide here?
That's because the expand parameter can not be used with the fields parameter if the expand value is relations.
You could execute this api with your request body in Postman. You will get the clearly message that why you can not apply it.
To use your API, if you specify the fields in the request body, then expand should not be used any more, and vice versa. This is as designed, and it has been hardcoded into our scripts. We do not allow another $expand value if it is not the None or Links.
For the 5 values of $expand(None, Relations, Fields, Links, All), only None and Links can work with fields successfully in API. This is a universal rule which apply to all APIs, including this one.
Also, please use $expand=Relations in request body instead of in URI which shown as the document described. Here if you use it in URI, it will not be used by server script since the method that this API called does not has this parameter. Another API which can use $expand in the URI (As normal, we would mention and show whether it can be used in URI in document), the corresponding scripts have parameters can access these value which passed by URI.
So, here please use $expand=Relations in request body, then you would get the result with all fields and its all relations.
I would really appreciate some advice, I'm trying to retrieve information from an open API for the first time.
The API details are here,
https://data.police.uk/docs/method/neighbourhood-locate/
I want to retrieve the 'force' and 'neighbourhood' values and save them into variables, I want to save them as variables as I'm then calling googlemaps to display the KML map. I managed to get quite far on other sections of my code, such as geocoding a user inputted address and retrieving the Long/Lat, but I am now struggling to send the long/lat to the external API and save the response.
I've hardcoded the long/lat into the below URL for this advice request, I think I'm getting a response from the API but failing to capture the values into my variables. The debugger shows the following response, {"force":"metropolitan","neighbourhood":"00BK17N"}, below is my code,
var ForceId; //returned from the API
var Neighbourhood; //returned from the API
accessURL = "https://data.police.uk/api/locate-neighbourhood?q=51.500617,-0.124629"
//Use the zip code and return all market ids in area.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: accessURL,
dataType: 'jsonp',
success: function (data) {
ForceId.push(val.force);
Neighbourhood.push(val.Neighbourhood)
console.log(ForceId);
console.log(Neighbourhood);
}})
I made a few mistakes, after seeing the responses were coming back as errors for its syntax, I adjusted some settings, I removed contenttype as 'application/JSON' and the response could be seen in the consolelog to contain the needed parameters. I'm not sure of the implications of doing this or if its bad practice as I'm extremely new at this, its my first attempt at working with API's. So other may advise better.
function GetPolice(){
$.ajax({
type: "GET",
// contentType: "application/json; charset=utf-8",
url: accessURL,
dataType: 'json',
success: function(data) {
ForceId = data.force;
Neighbourhood = data.neighbourhood;
},
})
}
If your new at this, then my suggestion is to tinker with 'success, error, complete' to see what responses are being returned to consolelog. Have a look at what your 'datatype' should be from the external API. Again, i'm not best placed to give advice but hope other new people find this helpful.
I now need to make the above a callback response, as it completes the function before the responsehas been recieved, I wish to use the response in another fucntion elsewhere, but thats a different challenge :)
I'm trying to call a web service to get some data. I need pass this URL in a GET method:
http://localhost/ecosat/ws/api.php?t=vw_motorista
But, when I look in Chrome Developer Tools, the link is:
http://localhost/ecosat/ws/api.php?t=vw_motorista&_=1397500899753
I'm not passing this parameter: &_=1397500899753
With this additional parameter, I received a 500 error. I can't change the web service to handle this.
What's going on? Is Chrome is changing my code?
This my Ajax
function get(pURL, pToken) {
var ret = null;
$.ajax({
type: "GET",
dataType: "json",
async: false,
timeout: globalTimeOut,
cache: false,
url: pURL,
headers: {"Token": pToken},
error: function(request, status, error) {
ret = null;
},
success: function(data) {
ret = data;
}
});
return ret;
}
You're probably using cache: false setting in your ajax query. It adds a _ parameter with a timestamp value, to make sure that your ajax call doesn't get cached by the browser.
Remove this setting, if you don't need it. But if you need make sure caching is disabled, you could try two things:
add your own parameter with a timestamp to your query, e.g. {ts: new Date.getTime()}, or
if possible, add headers to the web server response. See this question