Cannot pass URL from JavaScript to PHP in Laravel - javascript

I'm trying to get three values from a front-end form in JavaScript and then passing those values to the Laravel controller.
I can get two values (Key and Id) but I cannot get the third value because it is a URL. If I comment the URL variable then I'm getting the rest of the two values (Key and Id) but if I'm passing the URL along other two values then I'm not getting anything in my controller.
I have tried these two JavaScript methods encodeURIComponent() and encodeURI() to encode the https URL given but still no luck.
This is my code in JavaScript:
let get_url = $("#get-url").val();
let get_key = $("#get-key").val();
let get_id = $("#get-area").data('getId');
toastr.remove();
if (get_key) {
var req = new Image();
req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
console.log(req.src);
toastr.success(MEASURE.UTILITIES.translate("success_request_successfully_sent"));
$("#btn-send-data-request").hide();
$("#block_get_url").hide();
$("#block_get_key").hide();
$("#csv_get_request_message").show();
} else {
toastr.error(MEASURE.UTILITIES.translate("error_enter_valid_data"));
}

Your get_url contains a url, which i believe has https:// or http://
This is a problem when you are adding to the API URL you are constructing as adding more / changes the ROUTE.
For example your API URL expects req.src = api_url + 'senddata/' + get_id + '/' + get_key + '/' + get_url;
which is something like http://www.laravel.com/api/senddata/123/123/urlhere but you are making is something like http://www.laravel.com/api/senddata/123/123/http://urlhere which means you are altering the ROUTE.
To solve that you can URL Encode the URL before passing it.
Change your code to this should work : let get_url = encodeURIComponent($("#get-url").val());
Reference: https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp

Related

MWS Post Request with Google Scripts

I am trying to make a post request through google scripts to amazon to collect information.
We are trying to get our orders to MWS and transfer them to sheets automatically.
I got to the last step which is signing the request.
A few things I wasnt sure about:
They say we use the secret key for hashing,I only see a client secret
and an access key id, which do I use?
Do I add the URL as part of whats getting signed? On the MWS Scratch pad they add this as shown:
POST
mws.amazonservices.com
/Orders/2013-09-01
Does it have to be on separate lines does it need post and the rest of the stuff. Its a little unclear.?
I read online that the sha256 byte code gets base64 encoded, not the string literal, is that true?
I tried to hash the string that amazon gave to me with an online tool and compare it to the hash they provided and the base64 encode, thing matched. I tried decoding as well, nothing matched
Can someone please send me an example that works, so I can understand what happens and how it works?
Thank you!
Below is what I have so far:
function POSTRequest() {
var url = 'https:mws.amazonservices.com/Orders/2013-09-01?';
var today = new Date();
var todayTime = ISODateString(today);
var yesterday = new Date();
yesterday.setDate(today.getDate() - 1);
yesterday.setHours(0,0,0,0);
var yesterdayTime = ISODateString(yesterday);
var dayBeforeYesterday = new Date();
dayBeforeYesterday.setDate(today.getDate() - 2);
dayBeforeYesterday.setHours(0,0,0,0);
var dayBeforeYesterdayTime = ISODateString(dayBeforeYesterday);
var unsignedURL =
'POST\r\nhttps:mws.amazonservices.com\r\n/Orders/2013-09-01\r\n'+
'AWSAccessKeyId=xxxxxxxxxxx' +
'&Action=ListOrders'+
'&CreatedAfter=' + dayBeforeYesterdayTime +
'&CreatedBefore' + yesterdayTime +
'&FulfillmentChannel.Channel.1=AFN' +
'&MWSAuthToken=xxxxxxxxxxxx'+
'&MarketplaceId.Id.1=ATVPDKIKX0DER' +
'&SellerId=xxxxxxxxxxx'+
'&SignatureMethod=HmacSHA256'+
'&SignatureVersion=2'+
'&Timestamp='+ ISODateString(new Date) +
'&Version=2013-09-0';
var formData = {
'AWSAccessKeyId' : 'xxxxxxxxx',
'Action' : "ListOrders",
'CreatedAfter' : dayBeforeYesterdayTime,
'CreatedBefore' : yesterdayTime,
'FulfillmentChannel.Channel.1' : 'AFN',
'MWSAuthToken' : 'xxxxxxxxxxxx',
'MarketplaceId.Id.1' : 'ATVPDKIKX0DER',
'SellerId' : 'xxxxxxxxxx',
'SignatureMethod' : 'HmacSHA256',
'SignatureVersion' : '2',
'Timestamp' : ISODateString(new Date),
'Version' : '2013-09-01',
'Signature' : calculatedSignature(unsignedURL)
};
var options = {
"method" : "post",
"muteHttpExceptions" : true,
"payload" : formData
};
var result = UrlFetchApp.fetch(url, options);
writeDataToXML(result);
Logger.log(result);
if (result.getResponseCode() == 200) {
writeDataToXML(result);
}
}
function calculatedSignature(url) {
var urlToSign = url;
var secret = "xxxxxxxxxxxxxxxxxxx";
var accesskeyid = 'xxxxxxxxxxxxxxx';
var byteSignature = Utilities.computeHmacSha256Signature(urlToSign, secret);
// convert byte array to hex string
var signature = byteSignature.reduce(function(str,chr){
chr = (chr < 0 ? chr + 256 : chr).toString(16);
return str + (chr.length==1?'0':'') + chr;
},'');
Logger.log("URL to sign: " + urlToSign);
Logger.log("");
Logger.log("byte " + byteSignature);
Logger.log("");
Logger.log("reg " + signature);
var byte64 = Utilities.base64Encode(byteSignature)
Logger.log("base64 byte " + Utilities.base64Encode(byteSignature));
Logger.log("");
Logger.log("base64 reg " + Utilities.base64Encode(signature));
return byte64;
}
Step 1, creating the string to be signed
The string_to_sign is the combination of the following:
The string POST followed by a NEWLINE character
The name of the host, mws.amazonservices.com, followed by a NEWLINE
The API URL, often just /, or somthing like /Orders/2013-09-01, followed by a NEWLINE
An alphabetical list of all parameters except Signature in URL encoding, like a=1&b=2, not followed by anything
The minimum parameters seem to be the following:
AWSAccessKeyId is a 20-character code provided by Amazon
Action is the name of your API call, like GetReport
SellerId is your 14-character seller ID
SignatureMethod is HmacSHA256
SignatureVersion is 2
Timestamp is a date like 20181231T23:59:59Z for one second before new year UTC
Version is the API version like 2013-09-01
additional parameters may be needed for your call, depending on the value of Action
Please note:
The NEWLINE character is just "\n", not "\r\n"
The name of the host should not include "https://" or "http://"
The Signature parameter is necessary for the actual call later (see step 3), but is not part of the string_to_sign.
Your string_to_sign should now look somewhat like this:
POST
mws.amazonservices.com
/Orders/2013-09-01
AWSAccessKeyId=12345678901234567890&Action=ListOrders&CreatedAfter .... &Version=2013-09-01
Step 2, signing that string
Calculate a SHA256 hash of above string using the 40-character Secret Key
Encode this hash using Base64
In Pseudocode: signature = Base64encode( SHA256( string_to_sign, secret_key ))
Step 3, send the call
Send a HTTPS POST request, using the full alphabetical list of parameters, now including above signature as Signature somewhere in the middle, because you need to keep ascending alphabetical order.
https://mws.amazonservices.com/Orders/2013-09-01?AWSAccessKeyId....Version=2013-09-01
Step 4, processing the result
You should be getting two things back: a response header and a XML document. Be sure to evaluate the HTTP status in the header as well as all contents of the XML document. Some error messages are hidden deeply in XML while HTTP returns "200 OK".
Step 5, Advanced Stuff
If you use calls that require you to send a document, like SendFeed, you need to do the following additional steps:
Calculate the MD5 hash of your document
Encode this hash using Base64
In Pseudocode: contentmd5= Base64encode( MD5( document ))
Add Content-Type: text/xml (or whatever fits your document) as HTTP header
Add Content-MD5: plus the base64 encoded hash as HTTP header
This code was a great help for building a similar application. I corrected some small issues to bring it up to work:
before signing the ISODate need to be worked out to replace the ":" chars
var todayTime = ISODateString(today);
var todayISO = todayTime;
var todayTime_ = todayTime.replace(":", "%3A");
todayTime = todayTime_.replace(":","%3A");
The same for the calculated signature (quick & dirty solution, replace only 3 appearences and need to updated for more chars)
Logger.log(unsignedURL);
var tmpsignature = calculatedSignature(unsignedURL);
var orsignature = tmpsignature;
// encode special chars
tmpsignature = encodeURIComponent(orsignature);
}
I added a header and dropped the form, put all parameters in the url
var header = {
"x-amazon-user-agent": "GoogleSheets/1.0 (Language=Javascript)",
"Content-Type": "application/x-www-form-urlencoded"
// "Content-Type": "text/xml"
};
var options = {
"method" : "post",
"muteHttpExceptions" : true,
// "payload" : formData,
"header":header
};
And changed the call to url encoded (Form was not working, do not know why)
var url = 'https:mws-eu.amazonservices.com/Orders/2013-09-01?'+
'AWSAccessKeyId=<your stuff>'+
'&Action=GetOrder'+
'&SellerId=<your stuff>+
'&MWSAuthToken=<your token>'+
'&SignatureVersion=2'+
'&Timestamp='+todayTime'+ // remember to replace the ":" thru hex
'&Version=2013-09-01'+
'&Signature='+ tmpsignature+
'&SignatureMethod=HmacSHA256'+
'&AmazonOrderId.Id.1='+<your order;
parsed the response:
var result = UrlFetchApp.fetch(url, options);
//writeDataToXML(result);
Logger.log(result);
var xml = result.getContentText();
var document = XmlService.parse(xml);
This worked! :-)
I checked the signature also with
https://mws-eu.amazonservices.com/scratchpad/index.html

replace segment of a URL with regex

I have a button that takes a value from a checkbox and inserts it dynamically into a URL parameter. the URL looks like this:
example.com/search?q=searchterm&site=site1&page=1
&site=site1 is what is being updated dynamically by the value of a checkbox. My code for that looked like below at first:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = '&site=' + filterSelection + '&page=1';
console.log(filterUrl + " - " + filterSite);
window.location.replace(filterUrl);
});
The problem with the first approach is when you click the button multiple times, it just adds the new parameters to the URL, so it ends up looking like:
example.com/search?q=searchterm&site=site1&page=1&site=site2&page=1&site=site3&page=1
When I only need to change &site=site3&page=1 - I tried using a regex to select that part of the URL and replace it with the new one. My attempt at that is below:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
console.log(filterUrl + " - " + filterSite);
window.location.replace(url, filterUrl);
});
What this block does is remove the search query and just returns
example.com/site=site1&page=1 which gives a 404.
I need to somehow update a segment of a URL, and not the entire thing. I believe I need to do some sort of regex to target it and change it. What are the next steps? How can I update a certain section of a URL?
EDIT: This is where it stands now:
// apply filter, go to page
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
// console.log(filterUrl + " - " + filterSite);
if (window.location.href.indexOf("&site=") > -1) {
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
window.location.replace(filterSite);
console.log(filterSite);
} else {
window.location.replace(filterUrl);
}
});
but the .replace() method doesn't seem to be working.
Correct me if I got it wrong:
You have something like this: example.com/search?q=searchterm&site=site1&page=1 and you need to update ONLY THIS PART: &site=site1.
One way:
filterSite.replace(/&site=site\d+/,'&site=site' + filterSelection);
This works only if the updatable part of the url is ALWAYS going to be of the form &site=site<number>, ie: filterSelection is always a number
anyhow, let me know
REGARDING YOUR EDIT:
Assuming what you mean by The .replace() method won't change the parameter, is that the URL won't change, you are right: when you do this:
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
what you are modifying is the variable filterSite, the page won't automatically reload to the new url, which I think is what you intend after seeing this other line:
window.location.replace(filterSite);
replace it with:
window.open(filterSite);
to make the page go to the new url
More about window.open and its arguments
One last thing, I noticed you are using /&site=\d+/,'&site=' + filterSelection as args for replace which will not match example.com/search?q=searchterm&site=site1&page=1. So, unless you changed the structure of the url, you might want to look on that too.
let me know
URL Constructor
EXAMPLE: 1
;
var uri = new URL( "http://example.com/search?q=searchterm&site=site1&page=1" );
uri.searchParams.has("q");
>> true
uri.searchParams.set( "site", "site2" );
uri.searchParams.set( "page", "2" );
uri.href;
>> "http://example.com/search?q=searchterm&site=site2&page=2"
;
Browser Suport: ( ? )[ Chrome 49, Firefox 44, Opera 36, IE12 ]
I suggest you to use A POST request method and Jquery has already a method to construct that params to send based in the form
https://api.jquery.com/serialize/

Using URL encoded parameters in Angular

I am passing an encoded URL to an AngularJS app, what I want to do is decode the value and then take the parameters to use them to fill some html elements. So I have the following encoded URL:
http://www.otherurl.com/ROOT/?Transaction=%257b%2522TransactionID%2522%253a%2522-1%2522%252c%2522CashierID%2522%253a506069%252c%2522ErrorDescription%2522%253a%2522%2522%252c%2522ErrorCode%2522%253a%2522%2522%252c%2522status%2522%253a500130%252c%2522statusName%2522%253a%2522Approved%2522%252c%2522TraceID%2522%253a%2522%2522%252c%2522externalID%2522%253a%2522%2522%252c%2522Amount%2522%253a45.00%252c%2522CurrencyCode%2522%253a%2522USD%2522%252c%2522RejectReason%2522%253a%2522%2522%252c%2522Notes%2522%253a%2522%2522%252c%2522CSID%2522%253a-1%252c%2522ProcessorName%2522%253a%2522%2522%252c%2522Descriptor%2522%253a%2522%2522%257d#/return
I have the following code on js:
var uri_dec = decodeURIComponent(decodeURIComponent($location));
var nuevo = uri_dec.search()['Transaction'];
console.log('return controller > dec: ' + uri_dec);
console.log('return controller > nuevo: ' + nuevo);
$scope.transactionID = nuevo.search()['CashierID'];
console.log('return controller > transactionID: ' + $scope.transactionID);
Issue here is that Im not being able to use "nuevo" as it says undefined. Would you please help me solving this?

How to get real value of parameters in url

I have problem but I tried many solutions but it does not work .
Here is my code:
var params = '?DepartmentId=' + DepartmentId + '&DepartmentName=' + DepartmentName;
When I send params 'DepartmentName' with value 'R&D ABC' It only send 'R' to controller .
I tried to encode this params but it does not work like this:
params = encodeURI(params);
but it still get 'R' instead of all value.
Please help me, thanks
In javascript, you should use encodeURIComponent to encode parameter in url :
var params = '?DepartmentId=' + DepartmentId + '&DepartmentName=' + encodeURIComponent(DepartmentName);

Javascript URL Query String Logic

I have an events listing page which can be filtered by type and also by date using query string variables.
I am trying to achieve the following logic using javascript/jQuery.
I have a calendar which fires a function when updated. When fired I need to implement the following logic:
If the current URL contains ?filter= then add &dateStart= to the end of the URL.
If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
If the current URL contains ONLY ?dateStart= then replace it with the new one.
I have tried various methods to achieve this but I keep hitting the problem of appending information to the end of the URL rather than replacing parts of it.
Any help would be appreciated.
Thanks.
You can try something like this:
NOTE: not tested.
var newDateValue;
var myPath = window.location.pathname
//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;
if(containsFilter && !containsAppendedDateStart){
// If the current URL contains ?filter= then add &dateStart= to the end of the URL.
window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){
//If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
newDateValue = 10; // add your new value here
var splittedPathArray = myPath.split("&dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
window.location.replace(newUrl);
}else if(containsDateStart){
// If the current URL contains ONLY ?dateStart= then replace it with the new one.
newDateValue = 15;// add your new value here
var splittedPathArray = myPath.split("?dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}
You can achieve this more easy with native Web API or vanilla javascript than with jQuery. As far as jQuery don't provide any specific function to work with query strings.
The new URLSearchParams object provide a few methods to work more easily with URL query strings. In your case for example you'll need to do something like this:
function updateQueryString(queryString, dateStart) {
var queryString = new URLSearchParams(queryString);
queryString.has('dateStart')
? queryString.set('dateStart', dateStart)
: queryString.append('dateStart', dateStart);
return queryString.toString();
}
for this solution you'll need a polyfill
Sadly this is not yet implemented by the majority of web browsers and you'll need to "polyfill" the URLSearchParams object for this solution to work properly. You'll have to add this line to the <head> section in your html:
<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.14/polyfill.min.js"></script>
You can find more information about the URLSearchParams in the Mozilla Developers Network Documentation, the WHATWG specification for the URL Standard or the specification by the W3C
solution without polyfill
​
If you don't like to use edge features you still can do it without any extra polyfill. It would look like this:
function updateQueryString(queryString, dateStart) {
var qsObject = {};
queryString
.substring(1) // ignore '?'
.split('&').forEach(function (param) {
param = param.split('=');
qsObject[param[0]] = param[1];
});
qsObject['dateStart'] = dateStart;
return '&' + Object.keys(qsObject)
.map(function (key) {
return key + '=' + qsObject[key];
})
.join('?');
}
Call whatever version of the updateQueryString function you rather like this:
updateQueryString(windonw.location.search, dateStart)

Categories

Resources