An error occurred while parsing EntityName XMLHttpRequest Request - javascript

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...

Related

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

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']);

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)

Does anyone one know how to translate this jQuery into normal js?

So i have an email sending function on my cordova app and it uses jQuery to do it. When debugging my app the ajax function works fine when testing in my browser, but when i build the app and test it on my phone it does not work. I had another problem like this that was only fixed once i used normal js instead of jQuery. Here is the function:
var message = localStorage.getItem("Message");
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // <<KEY
var message_name = "defender_send_message"; // <<MESSAGE NAME
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({ // <<SEND
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
Does anyone know how to translate it into normal js? Thank you
You need to use XMLHttpRequest object to make a ajax call using vanilla JS.
var message = localStorage.getItem("Message");
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var data = {};
data.value1 = message;
data.value2 = localStorage.getItem("AdminsEmail");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'jsonp';
xmlhttp.send(data);

Problems getting response

I'm having some troubles trying to execute an ajax call. It is stored in chat.js (added in the html head) and it does a call to getChatHistory.php
chat.js:
function getChatHistory(user1, user2){
var response = 'fail';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
response = response + xmlhttp.responseText;
} else {
response = "Error:" + hmlhttp.status;
}
xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
xmlhttp.send();
}
return response;}
getChatHistory.php:
<?php
echo "the php talks";
?>
index.html:
<script>
(function(){
alert(getChatHistory('user1', 'user2');
})()
I checked with alert() and the onreadystatechange event doesn't work.
You're not sending the request due to the fact that your .open and .send functions are inside of your callback, try this instead:
function getChatHistory(user1, user2){
var response = 'fail';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
response = response + xmlhttp.responseText;
} else {
response = "Error:" + hmlhttp.status;
}
}
xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
xmlhttp.send();
return response;
}
Note, that you are also going to run into issues getting the response to return due to the fact that it's an async request. The response will return undefined unless you either a) make it a synchronous request (generally a bad idea) or b) set your action requiring the response to fire after the ready state has completed. Here is a basic example of how you could do so:
function getChatHistory(user1, user2, onComplete){
var response = 'fail';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
response = response + xmlhttp.responseText;
} else {
response = "Error:" + hmlhttp.status;
}
onComplete(response);
}
xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
xmlhttp.send();
}
index.html
<script>
(function(){
getChatHistory('user1','user2', function(resp){
alert(resp);
});
})();
</script>

IE8 is breaking my AJAX... FF is fine

Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.

Categories

Resources