Vanilla JS Ajax and base64img issue - javascript

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.

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

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

String replace not working with value returned from a XMLHttpRequest request

I have a (Laravel) PHP code that returns a long string in this way:
echo json_encode([
'created' => $count,
'total' => $num_stores,
'progressValue' => round((100 / $num_stores) * $count, 2),
'token' => str_repeat('|',1024*64)
]);
I need to get this string in javascript and clean it, removing all "|" character. But it seems not working.
This is my javascript code:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
try {
if (xhr.readyState == 4) {
alert('[XHR] Done');
} else if (xhr.readyState > 2) {
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var cleanedResponse = new_response.replace(/[|]/g, '');
console.log('CLEANED RESPONSE: ' + cleanedResponse);
var result = JSON.parse( cleanedResponse );
console.log('AFTER THE PARSE');
xhr.previous_text = xhr.responseText;
}
} catch (e) {
console.log(xhr.responseText);
alert("[XHR STATECHANGE] Exception: " + e);
}
};
xhr.open("POST", "...", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRF-TOKEN", jQuery('meta[name="csrf-token"]').attr('content'));
xhr.send(params);
I always get the exception when I try to parse JSON, and in the console I still see the "|" characters in the "cleanedResponse" variable.
How is it possible if I replace them?
When xhr.readyState == 3, then xhr.responseText holds only partial data - 3 means that the response has not yet been fully downloaded. You probably try to parse only partial JSON string that is not complete and therefore not valid and parsable. Wait for downloading complete response (xhr.readyState == 4) and then try to clean and parse JSON.
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState for further explanation of XHR states.

javascript how to parse numbers?

Hello so i'm trying to parse numbers that i get once i request page using http web request.But it seems that it fails me every time :/
Code that i use to make web request and parse:
var xhr = new XMLHttpRequest();
xhr.open('GET', "website url", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.);
}
}
I don't know what i need to write after dot i tried many options :(
Example of response that i get: {"status":1,"request":"1663758118"}
and i need to get only numbers
Html:
<pre>{"status":1,"request":"1663758118"}</pre>
So if somebody could help that would be great :)
If I understand your question correctly, and your code does correctly parse JSON string into JSON object, then you can do the following to retrieve data from JSON object
response.status // '1' as int
response.request // "1663758118" as string
Hope this answer can help you :)
After dot you need to put the property name in order to get the value.
If you need to convert a string to number you can add a + sign immediately before the string:
var response = JSON.parse('{"status":1,"request":"1663758118"}');
var stat = +response["status"];
var req = +response["request"];
console.log('status is: ' + stat + ' typeof is: ' + typeof stat);
console.log('request is: ' + req + ' typeof is: ' + typeof req);
If you need numbers from your response {"status":1,"request":"1663758118"}, you can use do this
const response = {"status":1,"request":"1663758118"}
const values = Object.keys(response).map(key => parseInt(response[key], 10))
console.log(values) // => [1, 1663758118]

How to pass all the params as a single object while making ajax call

I have the below js code:
xmlhttp = GetXmlHttpObject();
if (xmlhttp != null) {
var url = "/support/residential/outage/serviceOutage?cbrnum=" + cbrnum + "&btn=" + btn + "&outagetkt=" + outagetkt;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("thankyoucontent").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(null);
}
This calls a servlet by passing certain params in query string. Now my question is , can we bind all the params into a single object , send that object alone in query string and use the object in the servlet to retrieve the param values? Is it possible?
Yes, you can send the data as JSON to the server:
var data = {cbrnum: cbrnum, btn: btn};
var url = "...?data=" + encodeURIComponent(JSON.stringify(data));
Then on the server side, retrieve the value of data and parse the JSON into native data types (Converting JSON to Java).
Note though that browsers often impose a length limit on the URL. If you have a lot of data, do a POST request instead.

Categories

Resources