Cannot get proper response in xhttp in javascript? - javascript

I am using following AJAX code
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 ) {
alert("Status : " + this.status);
alert("Response : " + this.responseText);
}
};
xhttp.open("GET",url,true);
xhttp.send(null);
}
The problem is that I am unable to get the response. The responseText has no value and status is 0.
I checked in fiddler, the request is properly completed. Fiddler shows the correct response. I checked it by debugging on console, the xhttp doesnot update after xhttp.send().
This code is running inside an IFrame.

Related

How to obtain the body response in the client-side?

I am new in web, I am serving an html when a button is clicked on the client side through a request, the body response of that request is the html. How can I retrieve the html or body response from the client side?
I am trying with this code but everything is empty:
var xhr = new XMLHttpRequest();
xhr.open(signedRequest.method, signedRequest.url, true);
console.log('xhr.response: ', xhr.response);
console.log('xhr.responseText: ', xhr.responseText);
console.log('xhr.responseXML: ', xhr.responseXML);
document.write('<p>xhr: ' + xhr + '</p>');
xhr.send();
Any idea on how to obtain the body response in the client-side?
Try to add a div or any input element with the id "demo" and try to run the code below.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "<strong>The response from the test URL is: </strong>" + this.responseText;
console.log(JSON.parse(this.response));
}
};
xhttp.open("GET", "https://httpbin.org/get", true);
xhttp.send();
<div id="demo"></div>

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

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

PHP/AJAX only works when something gets echoed?

I'm trying to include the Wordpress blog header in a php file to use it as an AJAX call function.
define('WP_USE_THEMES',false);
echo 'Something';
require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-blog-header.php');
Original snippet found in: Wordpress include("../../../wp-blog-header"); failing, current by Ole Sauffaus.
The code only works when there is something echoed or printed between the define and the require function. Without it the server responds with a 404-error.
This behavior occurs only when I target the php via an AJAX request as follows.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('directory_results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://localhost:8888/appsconnected/wp-content/themes/appsconnected/ajax-loop.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("platform=" + platforms + "&category=" + category + "&orderby=" + order);
What causes this behavior?
Try this:
<?php
define('WP_USE_THEMES',false);
require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-blog-header.php');
?>

XMLHttpRequest.responseText doesnt write the value when calling a URL

There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is
My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT
This is the code I referred : code
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
you have to check, if the request was successful:
if (req.readyState === 4) {
// what should be done with the result
}
finally, it has to look like this:
req.onreadystatechange = function () {
if (req.readyState === 4) {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
}

Categories