Javascript HTTP POST with JSON data - javascript

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

Related

How to call REST service using JavaScript?

Using the code I found from one of the StackOverflow postings, I'm trying to call a REST service GET method. However, when the code runs it is not putting the GET format correctly in the URL.
Here's the code:
<!DOCTYPE html>
<script>
function UserAction(json)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
};
xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(json);
}
</script>
<form>
<button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
<label for="json">JSON:</label>
<input type="text" id="json" name="json"><br><br>
</form>
</html>
The expected format of this GET REST service would be:
http://localhost:8080/isJsonValid/json
(where json in the line above is the actual JSON sent as a parameter.)
Yet, what is shown in the URL line includes the project, directory and the URL has the ?name=value syntax.
Since the GET doesn't match the simple http://localhost:8080/isJsonValid/json format, I get a 404 error.
I realize there's something obvious I'm missing.
Thanks to all for suggestions.
If you need to send data you need to either send it as a query param or as the body. If you want to send it as a body need to use POST type. Below is the example of POST type.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach(movie => {
console.log(movie.title)
})
} else {
console.log('error')
}
}
// Send request
request.send()
For post Request. As I don't have any API with me I have used get API URL.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText)
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
Thanks all for the great input and help!
The best solution for me was to just use, as suggested, a POST. The GET was always putting the "?" in the URL even if I concatenated it, That "?" isn't how the REST service interprets the GET parameters so it wouldn't work that way. In the REST framework I'm using, GET parameters are just concatenated with one or more "/" as separators in the URL.
Appreciate all the terrific help here on SO. :)

Send data on ajax

Is this the correct way to send data to server on ajax request?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(response);
}
};
xhttp.open("GET", "https://myurl/", true);
xhttp.send(JSON.stringify("{ action: 'search', mode: question}"));
Because I get this error 405 (Method Not Allowed - Action not found)
No, there are several issues with that:
alert(response); will fail because there's no response variable; you'd probably want alert(xhttp.responseText).
You're doing a GET, but then trying to send a POST body. You can't do that. GET information is in the URL, not the body.
You're sending JSON (well, trying to), but not identifying it as JSON.
You're passing a string into JSON.stringify, where normally you'd pass an object, not a string, as its job is to convert things to JSON strings.
Assuming you mean to do a POST, and you really do want to send JSON (e.g., that the server is set up to accept JSON from the client), then minimal changes would be:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xhttp.responseText); // 1
}
};
xhttp.open("POST", "https://myurl/", true); // 2
xhttp.setRequestHeader("Content-Type", "application/json"); // 3
xhttp.send(JSON.stringify({ action: 'search', mode: question})); // 4
Note that I'm assuming question is an in-scope variable in that.

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

Sending data from javascript to php file

I have this function that gets text from a php file on the server and plonks it into an HTML page.
What changes do I need to make to it to SEND data (just a couple of javascript variables) to the php file rather than read from it ? Hoping not many !!
function process() {
if (xmlHttp) // the object is not void
{
try {
xmlHttp.open("GET", "testAJAX.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
}
}
Take a look at what all headers you can make use of. In your case, you would want to use POST instead of GET
xmlHttp.open("POST", "testAJAX.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(data);
You are probably better of using POST to send data it has less limitations. e.g:
var data = {
user: 'Joe',
age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
if (httpReq.readyState != 4 || httpReq.status != 200) return;
console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));
And read it:
$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);
If it's just a couple of variables, you can pop them into the query string - although you'll want to make sure their values won't break your PHP script or open a security hole (for example, don't interpret user input as a SQL string). For more complicated data structures, use POST as others have suggested.
function process(var1value, var2value) {
if(xmlHttp) {
try {
xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
}
}

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