XMLHttpRequest appending payload to the uri - javascript

I'm making a simple POST XMLHttpRequest, it is successfully posting the data but also the paylod getting appended to the URL. Is there anyway the data doesnt appended to the URL
var payLoad= JSON.stringify(ItemJSON);
var xmlhttp = new XMLHttpRequest();
xmlhttp.addEventListener("readystatechange", function () {
if (xmlhttp.readyState < 4){
}
else if (xmlhttp.readyState === 4) {
if (xmlhttp.status == 200 && xmlhttp.status < 300){
console.log("Success",xmlhttp.responseText);
}
}else{
alert("Error!! \\n There was an error while saving. Please retry again later.");
}
});
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(payLoad);
}
Response :
https://sample.com/api/apipipelines?apiName=asdasdaaaaaa&orgUnit=ASA&apiProductName=asdasd&leadDeveloperName=Sandeep&leadDeveloperEmail=sa11as1%40sandsssy.com&baseUrl=%2Fapplication%2Foip%2Fv1%2Fcase-management%2F&projectOwnerName=alisa&projectOwnerEmail=sa%40sasssssndy.com

It is because the header that you used while posting the content:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Change it to
xmlhttp.setRequestHeader("Content-Type", "application/json");
Reference for you: What is the difference between form-data, x-www-form-urlencoded and raw in the Postman Chrome application?

Related

POST value from JavaScript to PHP via AJAX without jQuery

I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4 and status == 200 yet PHP keeps echoing back an empty array/value.
I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.
JS (from index.html) :
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send(valueToSend); //this line is probably not sending the value the way I expect it to
}
}
PHP (from test.php) :
echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
My last try was to change request.send(valueToSend); with .send(encodeURI('name=' + valueToSend)); but it just made the ajax call redirect the page location to a non-existing one.
What am I doing wrong ?
There are few things wrong in your code, such as:
Even through you defined send_ajax() function, you didn't call it anywhere in the code.
With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:
request.send("name="+valueToSend);
So the complete JavaScript code would be like this:
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("name="+valueToSend);
}
}
send_ajax();

How can I get the substatus code of the exception with java script? like 500.1

I would like to read the substatus code of the exception like 500.1 on the client side. How to achieve this?
here is my code on the server side:
if(string.IsNullOrEmpty(userEmail)) {
Response.StatusCode = 500;
Response.SubStatusCode = 1;
Response.StatusDescription = "Email fehlt";
return;
}
Client side:
if (xhr.status == 500 && thrownError.indexOf("Email") > -1) {
alert('Email is missing...');
}
else {
alert('Error...');
}
On client side you can use the getAllResponseHeaders() method of XMLHttpRequest.
If a correct http header is really sent, it will read it.
Example:
var request = new XMLHttpRequest();
request.open("GET", "ajax.php", true);
request.send();
request.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(this.getAllResponseHeaders());
}
}
Output is separated by "\r\n".
If somehow the substatus cannot go through, maybe you can use another http header field for your goal, even if it is not according to the standards...

xmlHTTP request error: "failed"

var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET','http://example.com/',true);
xmlHTTP.send();
I just keep getting XHR failed loading: GET, can anyone help???
Thanks
If the server your contacting doesn't have CORS set in the header (e.g. access-control-allow-origin: *), you will not be able to make the request. If you don't have access to the server to set a CORS header, you'll need to contact the server from a server you do control and then pass that to the browser (either with a CORS header or not if it's served from the same domain)
But your code works fine. The problem is with your http://example.com/ not returning
http://jsbin.com/zuhobidako/edit?html,js,console,output
var xmlHTTP = new XMLHttpRequest();
xmlHTTP.open('GET','https://jsonplaceholder.typicode.com',true);
xmlHTTP.send();
xmlHTTP.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.body.innerHTML =
this.responseText;
}
};
For server status errors, add this to onreadystatechange
if( this.status > 299 && this.readyState == 4) {
console.log('Server Error: ' + xmlHTTP.statusText);
}
For xmlHTTP code errors...
xmlHTTP.onerror = function() {
console.log('xmlHTTP Error', xmlHTTP.responseText)
}

How can I pass data from client to server use raw AJAX?

Hello I have already search but they often use jquery ajax to pass data from js to PHP(server-side). but for my project it has a bunch of pure js code so I should use raw AJAX to pass data.
For example, if I want to send a variable "Imgname" that value = 13 and want to echo in php page.
this is my try
<script>
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert('send to server successfully');
}
};
xmlhttp.open("POST", "test2.php", true);
xmlhttp.send("Imgname=13");
}
</script>
in test2.php
<?php
$temp = $_POST['Imgname'];
echo $temp; /////output should be 13
?>
but error Undefined index: Imgname in C:\xampp\htdocs\test2.php on line 2
You need to make sure that you're sending the correct content-type:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Try sending the header:
var http = new XMLHttpRequest();
var url = "test2.php";
var params = "Imgname=13";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);

Failing to get results using XMLHttpRequest

I'm trying to retrieve a file using XMLHttpRequest with Javascript. I'm having some problems getting the data of the sample file.
Here is the simple code:
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
alert(xmlHttp.responseText);
}
xmlHttp.open("GET", "http://humanstxt.org/humans.txt", true);
xmlHttp.send(null);
</script>
With the above code I don't get any alerts. If I remove && xmlHttp.status == 200 then I get an empty alert, (I don't know why the server isn't giving the 200 status code). I tried different URLs but they all give out the same results.
Any thoughts on this?

Categories