Send in xmlhttp numeric data converted into a character string - javascript

I want to send numerical data through a GET retrieved via Javascript GPS position.coords.latitude here is the code.
function post() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var v2 = -20.9008623; //position.coords.latitude;
var v3 = 55.4958068; //position.coords.longitude;
var v4 = v2.toString();
var v5 = v3.toString();
xmlhttp.open("POST", "ajax.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("LAT=" + v4 + "&LON=" + v5);
}
As you can see, var2 and var3 are numeric data and are indeed sent in this case since they are converted into a character string before being sent by the GET.
On the other hand as soon as I do the recovery by position.coords.latitude nothing is sent or rather nothing is recovered by the AJAX file.
Did I forget something? Thank you for your answers.

You cant send anything else then strings with urlencoded content. Use another format.
Try with a FormData for instance.
const data = new FormData()
data.append('lat', 37)
data.append('long', 32)
xmlhttp.setRequestHeader('content-type: multipart/form-data;')
xmlhttp.send(data)

Related

Displaying specific Key Value Pair

Hi I have a form which has email and password and upon clicking submit button the puaru_Active() function runs which is given below
<script>
function Puaru_Active() {
var http = new XMLHttpRequest();
var tk = document.getElementById("tk").value;
var mk = document.getElementById("mk").value;
var url = "iphone.php";
var params = "u="+tk+"&p="+mk+"";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
}
</script>
On console.log it displays this JSON Data
{"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"}
Now say I want to output only access_token and its value how should I do that?
I have tried:
console.log(http.responseText.access_token)
console.log(http.responseText['access_token'])
console.log(http.access_token)
console.log(responseText.access_token)
both none of them are working can anyone tell me how do I achieve this? Thank you!
First parse the JSON string, then access it as an object.
var response = JSON.parse(http.responseText);
console.log(response['access_token']);
var obj = JSON.parse(http.responseText);
console.log(obj.access_token);
You can do this via bracket notation, like this:
var jsonStr={"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"};
var accessToken = jsonStr["access_token"];
alert(accessToken);
Working Example here
Hope Its Work !!
Happy Coding !!

Jena Fuseki not working when making an insert query from javascript. No Update parameter error

I have this JavaScript function which aims to insert a keyword in a named graph which belongs to the project Dataset.
function insert(keyword) {
var query = "INSERT DATA {GRAPH <http://test1> {<subj> <pred>'" + keyword + "'. }}";
var endpoint = "http://localhost:3030/project/update";
sparqlQueryJson(query, endpoint, showResults, true);
}
I have executed Jena Fuseki with the --update option. The sparqlQueryJson function is as follows:
function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
var querypart = "query=" + escape(queryStr);
// Get our HTTP request object.
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Code for older versions of IE, like IE6 and before.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support XMLHttpRequests?');
}
// Set up a POST with JSON result format.
xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
// Set up callback to get the response asynchronously.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// Process the results
callback(xmlhttp.responseText);
} else {
// Some kind of error occurred.
alert("Sparql query error: " + xmlhttp.status + " " + xmlhttp.responseText);
}
}
};
xmlhttp.send(querypart);
};
The showResults function is, in my opinion, not very important here, since it takes the results of the query and show them in HTML.
I followed what is discussed here and here, executing the query using the http://localhost:3030/project/update. The thing is that if I execute the same query on top of the local Fuseki server with the same endpoint url by using the web, it works, but from the JavaScript code, it raises the error:
"SPARQL query error: 400 Error 400: SPARQL Update: No 'update=' parameter".
I'm using Ubuntu 16.04 and Jena Fuseki - version 2.4.1.
To solve this problem the =query parameter has to be changed to =update. In addition, a parameter with the type of the query has to be handled, i.e., update or query.
if(type==="update"){
var querypart = "update=" + escape(queryStr);
}else if(type === "query"){
var querypart = "query=" + escape(queryStr);
}
...
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if(type==="query"){
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
}

403 Error - Javascript AJAX POST

I have an existing AJAX GET script that is working and passing data via the URL back to my PHP code.
Due to the data I now want to send, I want to change the AJAX to a POST.
I have created some data in the below JSON format
var lead = {
"email" : document.getElementById('emailAddress').value,
"source" : document.getElementById('source').value,
"purpose" : document.getElementById('need').value,
"amount" : amount,
"lvr": lvr};
This is then passing to the below function
var string = JSON.stringify(lead);
var uri = "http://127.0.0.1/HomeLoans/ajax/ajaxcreateLead/";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("YA");
}
}
xmlhttp.open("POST", uri, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(string);
Chrome is giving me a 403 Forbidden error and I can't seem to workout where I have gone wrong.
Chrome Error
Thanks!! :)
If you are on Apache, put in your .htaccess
RewriteEngine On
Allow From All

Javascript HTTP POST with JSON data

Can I send a request as below? With parameters being assigned with a JSON style object. I only get error. But when I use a REST client and choose RAW data, it's OK. I guess I must have written incorrect code. How to send raw JSON data in JavaScript? Could anyone help me?
xmlhttp = new XMLHttpRequest();
var url = "https://someURL";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = {
"username": "myname",
"password": "mypass"
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
xmlhttp.send(parameters);
No. The send() method can take a number of different argument types, but a plain object is not one of them (so it will probably end up having toString() being called on it and being turned into "[Object object]").
If you want to send JSON then you must:
Say you are sending JSON: xmlhttp.setRequestHeader("Content-type", "application/json");
Convert your JavaScript object to a string of JSON text: var parameters = JSON.stringify({"username":"myname","password":"mypass"});
Be prepared to accept JSON instead of application/x-www-form-urlencoded data on the server side.
Also note that, since you are using an absolute URI, you may run into cross domain issues.
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", AjaxURL, true);
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
};
xmlhttp.send(JSON.stringify(Idata));

XMLHttpRequest alters text in UTF-8

While processing a huge XML client-side, got stuck with the following issue: some unicode characters are replaced with unreadable sequences, so server cannot parse that XML. Testing like this:
var text = new XMLSerializer().serializeToString(xmlNode);
console.log(text);
var req = new XMLHttpRequest();
req.open('POST', config.saveUrl, true);
req.overrideMimeType("application/xml; charset=UTF-8");
req.send(text);
Logging still shows the correct string:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
While in the request (Chrome dev tools) and at server side it appears modified like this:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
Original encoding of the XML file is UTF-8, too. Absolutely the same behavior when using jQuery.
Check that overrideMimeType use uppercase "UTF-8" or lowercase "utf-8"
Make sure that string before javascript calculation was in utf-8 (check page charset)
Use escape/encodeURIComponent/decodeURIComponent before send it to server and unescape it on server
Try application/x-www-form-urlencoded ans send xml like plain text
P.S. Modified string is in ISO-8859-15
It seems to do so.
I have here data json parameter that includes a string "Lääke" (finnish word), that i sent to server via ajax.
This did NOT work, server app did not receive 'ää' but '??':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.send();
This did work, server received 'ää':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
//orderStatusElement[0].innerHTML = "<b>Palvelimella jokin meni vikaan. Yritä myöhemmin uudelleen </b>";
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

Categories