Passing an argument into a URL - javascript

I have a function, which takes a number as an argument. I was wondering how I could use this number to pass into a url which will then be used in a GET request.
Below is some of my code, the {{}} brackets below didn't work, I also tried template literals which for some reason also didn't work 'https://www.mywebsite.com/api/v2/${urlID}/fonts.json'
function getID (ID) {
var urlID = this.ID;
var request = require("request");
var options = {
method: 'GET',
url: 'https://www.mywebsite.com/api/v2/{{urlID}}/fonts.json',
};

For your template to work, you'll need backticks.
`string ${someVariable} another string`
Since you're putting data in a URL, you should also take care to use encodeURIComponent() so that any data is escaped properly for the URL.
Putting it all together:
url: `https://example.com/api/v2/${encodeURIComponent(ID)}/fonts.json`

Related

Macy product API jQuery

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,
// ...
}

passing parameters to rails back end from an ajax call

I am trying to pass an API route to rails for the server to perform the call instead of the client. I get a 404 not found when I try to do this. From the console it works find when I am passing this route to the method. However not from the ajax call. Here is my controller method:
def identification
#link = params[:link]
#response = MotorClient.new.response_from_path(#link)
render json: #response
end
Here is my route:
get '/identification/:link', to: 'vehicles#identification', on: :collection
Here is my ajax:
handleRoute: function (e) {
this.handleChange(e);
e.preventDefault();
var options = e.target.options;
var route = "";
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
route = (options[i].dataset.route);
console.log(route)
$.ajax({
type: 'get',
url: '/vehicles/identification/',
dataType: 'json',
data: {"link":encodeURIComponent(route)},
success: function (data) {
this.props.getMakes(data);
}.bind(this),
})
}
}
},
When I console.log the route I get the correct string like this "/v1/Information/YMME/Years/2012/Makes/56/Models" and Like I said from the rails console it works but I can't get the parameter correctly this is what I get on the javascript console when I do thru the ajax call:
GET http://localhost:3000/vehicles/identification/?link=%252Fv1%252FInformation%252FYMME%252FYears%252F2012%252FMakes 404 (Not Found)
What am I doing wrong?
Looks like your route is expecting the link to be a segment in the URL path instead of a query string variable: /identification/:link -- Try dropping the /:link or appending the encoded link at the end of your URL when making an AJAX call back to the server.
The key here is encodeURIComponent which escapes the link string. It is better to escape data in such way, so I'm thinking you better to handle escaped string format at API side.
There is another way: using 'post' instead of 'get' ajax type. Thus, you could drop escaping part and pass a pure string as 'link' property.

Convert C# model to plain json-string

Is there any simple way to convert an C#-object into a plain string that is escaped and can be used by javascript?
I try to pass the string into a jQuery-function which will replace some parts of this string with real values to pass them as request-object via $.ajax.
Whatever I tried (found in the internet) doesn't work.
Currently I have:
var jsVariable = "#Html.Raw(Json.Encode(new MyClass()))"
but this throws an Uncaught SyntaxError: Unexpected identifier as of the " are not escaped correctly.
Update 1
At the end I would like to have the JSON-string like
"{"Prop1": "{0}", "Prop2":"{1}"}"
on which I can (in javascript) call
var request = string.Format(jsVariable, value1, value2);
to enable
$.ajax({
type: "POST",
url: "someUrl",
data: $.parseJson(request),
success: function(data) {
console.log("success");
},
dataType: "JSON"
})
Just get rid of the double quotes.
Make sure this is added in the script tag of your view.
var jsVariable = #Html.Raw(Json.Encode(new MyClass()))
you'd then get a javascript object with its properties - provided MyClass is defined, and is accessible in your CSHTML.
jsVariable.myProp, jsVariable.myOtherProp . . etc

how to decode serialize url from javascript in php

please consider following snippet
i have submited a form which contains a background image url , i have serialize the form data . in php the URL is not decoding , how to get orignal url
$("#slider_settings_form").submit(function(e) {
var postData = $(this).serialize();
submited form
$.ajax({
url: ajaxurl,
data: {
"params": postData,
"action": "saveFormSettings"
},
method: "POST",
success: function(response) {
alert(response);
},
});
Use string urldecode( string $str ) function to decode your encoded URL data
for more follow this link
A successful parsing could be done by adding urldecode like this:
parse_str(urldecode($_REQUEST['params']), $params);
urldecode is important because it converts url encoded string into parsable string.
If you want to achieve it from javascript you can use these methods:
var uri = "http://stackoverflow.com/questions/30587877/how-to-decode-serialize-url-from-javascipt-in-php"
var uri_enc = encodeURIComponent(uri); //for encoding
var uri_dec = decodeURIComponent(uri_enc); //for decoding
Here is the link for more details:
Url decode and encode
Have a look at this related question.
We need to see how you're decoding the data in PHP to help you, but in addition to the answer ahead of mine (suggesting the use of urldecode), you should also make sure postData actually has data in it.
Only "successful controls" are serialized to the string [...] - second answer
It's entirely possible postData is nil. You should test it by alerting it and go from there. The question I linked to has a more thorough answer with code examples.
var postData = $(this).serialize(); -- this would create a query string like 'a=1&b=2', where a and b are form fields. You might want to fetch the value of a or b -- the following code will help you:
parse_str($_GET['params'], $params);
// then you can use $params['a'] to fetch form field 'a'
print_r($params);
// =>
//Array
//(
// [a] => 1
// [b] => 2
//)
For more about parse_str, see http://php.net/manual/en/function.parse-str.php

Pass parameter containing `&` with AJAX

I am passing my string to PHP through AJAX using $.Ajax.
I'm trying to pass this string:
action=abc&parameter=C&W
The AJAX splits the C&W on the basis of &, so the request comes in this format:
$action = "abc";
$parameter = "C";
How can I pass it as C&W, without it being split into a different parameter?
You should let jQuery do the encoding for you :
$.ajax({
url: someUrl, // <- no parameter here
data: {action:'abc', parameter:'C&W'},
...
Using bog-standard JavaScript (no jQuery), you can use encodeURIComponent:
var url = "action=" + encodeURIComponent(action) + "&parameter=" + encodeURIComponent(param);

Categories