Passing URL variable with & from JS to PHP result in "&" omission - javascript

It is a bit difficult to find the proper title for this question for me, so maybe this example will clarify my issue.
I am making an ajax request to pass some variables from a JS to a PHP.
One of these variables is a URL with some options, namely
https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=impianti_risalita&
The PHP code is ignoring any options after the first & symbol, considering only this part
https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs
The AJAX request to the PHP I am making at the moment looks like
https://localhost/shire/php/export_wfs.php?wfs_url=https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=impianti_risalita&format=ESRI%20Shapefile
being wfs_url and format the two parameters the PHP is supposed to process.
I think i am supposed to avoid placing the & symbols in the wfs_url parameter, but I have no idea what should i do instead. Any help would be appreciated.
EDIT
Here is the AJAX call:
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE
// url is https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=impianti_risalita&
var php_url = window.location.protocol + "//" + window.location.hostname + '/shire/php/export_wfs.php?wfs_url=' + url + 'format=' + format_list[0];
xhr.open('GET', php_url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
alert('Downloading...');
}
}
xhr.send();
return false;
});

Here's how to send it as POST request:
var php_url = '/shire/php/export_wfs.php';
var formData = new FormData();
formData.append('wfs_url', url);
formData.append('format', format_list[0]);
xhr.open('POST', php_url);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
alert('Server reply: ' + xhr.responseText);
}
}
xhr.send(formData);

try including this function (base64_encode):
var php_url = window.location.protocol + "//" + window.location.hostname + '/shire/php/export_wfs.php?wfs_url=' + base64_encode(url) + 'format=' + base64_encode(format_list[0]);
and on the server side:
$wfs_url = base64_decode($_GET['wfs_url']);
$format = base64_decode($_GET['format']);

Related

An error occurred while parsing EntityName XMLHttpRequest Request

I am trying to do http GET request for a MS flow using XMLHttpRequest in java script but getting the above error.
I know this is because of the url.Can anyone help me what is the exact issue with my url.
var finalurl = "https://prod4-30.centralindia.logic.azure.com:443/workflows/ed30ad9219a940fa8e5af317cf697e4c/triggers/manual/paths/invoke?api-version=2016-06-01&sp=/triggers/manual/run&sv=1.0&sig=ctQe3OAscgTfzDgji9gS_B43lvHEV4JP-hGdaxu46wg";
function DohttpRequest(greeting) {
alert(greeting);
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', '" + finalurl + "', false);
xmlHttp.send(null);
var jsonResponse = JSON.parse(xmlHttp.responseText);
console.log(jsonResponse);
alert(xmlHttp.responseText);
}
I am doing the GET request in sharePoint using the custom action. The definition of the custom action with CommandAction is as below
UserCustomAction SPToDBAction = collUserCustomAction.Add();
SPToDBAction.Location = "CommandUI.Ribbon.ListView";
SPToDBAction.Sequence = 10001;
SPToDBAction.Title = "SPToDBAction";
string location = "<CommandUIDefinition Location=\"Ribbon.ListItem.Actions.Controls._children\">";
SPToDBAction.CommandUIExtension = #"<CommandUIExtension><CommandUIDefinitions>"
+ location
+ "<Button Id=\"InvokeAction.Button\" TemplateAlias=\"o1\" Command=\"EditFormButtonCommand\" CommandType=\"General\" LabelText=\"Sync SP To DB\" Image32by32=\"data:image/png;base64,iVB= \" />"
+ "</CommandUIDefinition>"
+ "</CommandUIDefinitions>"
+ "<CommandUIHandlers>"
//+ "<CommandUIHandler Command =\"EditFormButtonCommand\" CommandAction = \"javascript:alert('Custom List ECB custom Action')\" />"
+ "<CommandUIHandler Command =\"EditFormButtonCommand\" CommandAction = \"javascript:DohttpRequest('Are you sure to sync the Items from Sharepoint to Database'); function DohttpRequest(greeting){ alert(greeting); var xmlHttp = new XMLHttpRequest(); xmlHttp.open( 'GET', '" + finalurl + "', true ); xmlHttp.send( null ); var jsonResponse = JSON.parse( xmlHttp.responseText); console.log(jsonResponse); alert( xmlHttp.responseText);}\" />"
+ "</CommandUIHandlers></CommandUIExtension>";
SPToDBAction.Update();
Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.
With asynchronous request you need to wait for server answer, for do that you need to work with XMLHttpRequest onreadystatechange property, so in the end your function code will look like this...
function DohttpRequest(greeting) {
alert(greeting);
let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let jsonResponse = JSON.parse(this.responseText);
console.log(jsonResponse);
alert(this.responseText);
}
};
xmlHttp.open('GET', '" + finalurl + "', true);
xmlHttp.send();
}
Hope it helps...

Javascript serialized POST

I am trying to achieve that when I call the JS function, a post request is send. In my browser I would send:
http://myuser:password#hc2:80/api/callAction?deviceID=185&name=turnOn
This works. Yet in my code it doesn't.
Important to note:
- Chrome does raise an Error: Request doesn't pass access control. If I disable this in Chrome, I doesn't display this error (yet no response from the server either).
<script type="text/javascript">
function changestate() {
var http = new XMLHttpRequest();
http.withCredentials = true;
var user = "bassie"
var pass = "password"
var url = "http://hc2/api/callAction";
var params = "deviceID=185&name=turnOff";
http.open("POST", url, true);
http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(http.responseText);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
</script>
The equivalent to putting the URL in the browser's location is a GET request, not POST.
Since you're sending a cross-domain request, you won't be able to read the response (unless you relay through a proxy on your origin server). So you can't read http.responseText, and can simply omit the onreadystatechange function; you'll just have to assume it
function changestate() {
var http = new XMLHttpRequest();
http.withCredentials = true;
var user = "bassie"
var pass = "password"
var url = "http://hc2/api/callAction";
var params = "deviceID=185&name=turnOff";
http.open("GET", url + "?" + params, true);
http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
http.send();
}
Eventually ended up creating a sort of like proxy. This was the main component. Not in the example (My script gets the HTTP requested) and gets the output. Below the gist of it:
req = urllib.request.Request('http://hc2:80/api/callAction?param1=1&param2=2')
credentials = ('%s:%s' % ('user', 'password'))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' %
encoded_credentials.decode("ascii"))
response = urllib.request.urlopen(req)

JavaScript: How to get http response as a result of click

I'm trying to get response of GET request, that starts after document.getElementById('btnPdf').click();
I'm using Selenium Webdriver as JavaScriptExecutor.
My question is similar to this How do I capture response of form.submit but I don't know exact url and would prefer to use pure JS without AJAX (if it's possible).
function get
Response() {
var send1='senddata'; // this is a var to send
var send2='senddata2'; // this is another var to send
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myGetPageName',true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.onload = function() {
if (xhr.status === 200) {
var myResponse = xhr.responseText;
alert(myResponse);
}
};
xhr.send('myvar1=' + send1 + '&myvar2=' + send2)
}

Vanilla JS Ajax and base64img issue

I am encoding an image using a function that uses a canvas element to encode an image to base64.
Then I try to post the Base64 string through AJAX to my php ajax_controller:
function submitParticipation(name,email,phone,city) {
encodeImage(uploadedImg, function(encodedImage) {
uploadedImg = encodedImage;
});
var ajax = new XMLHttpRequest();
var params = 'uid='+ facebookUserId + '&name=' + name + '&email=' + email +
'&phone=' + phone + '&city=' + city + '&img_string=' + base64Img +
'&facebook_name=' + facebookUserFullName + '&facebook_pic=' +
facebookProfilePic + '&facebook_email=' + facebookUserEmail;
ajax.open("POST", "main_ajax_controller.php?m=store_participation", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(params);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var response = ajax.responseText;
} //If an error occur during the ajax call.
if (ajax.readyState == 4 && ajax.status == 404) {
}
}
}
The base64Img though does not go through the AJAX call - it goes through empty.
Any idea why?
The base64Img variable is defined just fine - I can see this because I log it in the console right before defining it in the params variable of the Ajax call.
Your params string is invalid because you don't encode each of the values. All of them, including the base64 value should be wrapped in encodeURIComponent().
For example:
base64Img = encodeURIComponent(base64Img);
Base64 values include an = character, which is breaking the key pair string.

XHR get request URL in onreadystatechange

Is there any way to get the URL of request in the "onreadystatechange" method?
I want to run multiple XHR requests and know which of them comes back:
xhr.open("GET", "https://" + url[i], true);
xhr.onreadystatechange = function(url) {
console.log("Recieved data from " + url);
};
xhr.send();
There are 3 simple ways of doing this.
1: use closures as already described
2: set an attribute on the xhr object that you can reference later like so:
xhr._url = url[i];
xhr.onreadystatechange = function(readystateEvent) {
//'this' is the xhr object
console.log("Recieved data from " + this._url);
};
xhr.open("GET", "https://" + url[i], true);
3: Curry the data you need into your callbacks (my preferred solution)
Function.prototype.curry = function curry() {
var fn = this, args = Array.prototype.slice.call(arguments);
return function curryed() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
function onReadystateChange(url, readystateEvent) {
console.log("Recieved data from " + url);
};
xhr.onreadystatechange = onReadystateChange.curry(url[i]);
xhr.open("GET", "https://" + url[i], true);
Use closures.
function doRequest(url) {
// create the request here
var requestUrl = "https://" + url;
xhr.open("GET", requestUrl, true);
xhr.onreadystatechange = function() {
// the callback still has access to requestUrl
console.log("Recieved data from " + requestUrl);
};
xhr.send();
}

Categories

Resources