I am trying to call web service in html5 javascript. But XMLHttpRequest status value getting ZERO insted of 200 and responseText is empty. help me to solve the issue, My code below
<script type="text/javascript">
var xhr;
function Getdet()
{
try {
xhr = new XMLHttpRequest();
xhr.open('POST', "URL", true); // URL-->Webservice link
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.responseType = 'json';
}
catch(err)
{
alert(err.message);
}
}
function processRequest(e) {
try{
var prn=JSON.stringify(e);
alert("xhr.readyState-->"+xhr.readyState);
alert("xhr.status-->"+xhr.status);
alert("xhr response-->"+ xhr.response);
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.ip);
}
}
catch(err)
{
alert(err.message);
}
}
}
</script>
Related
I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}
I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload
I am trying to do a simple GET request to flipkart search api.
baseurl= 'https://affiliate-api.flipkart.net/affiliate/search/json?';
params={
query:name,
resultCount:5
};
var xhr=new XMLHttpRequest();
xhr.open('GET',baseurl+$.param(params),false);
xhr.setRequestHeader("Fk-Affiliate-Id","myidhere");
xhr.setRequestHeader("Fk-Affiliate-Token","mytokenhere");
xhr.send();
After using asynchronous XMLHttpRequest(),I get following error:
var xhr = new XMLHttpRequest();
xhr.open("GET", baseurl+$.param(params), true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("gowofee",xhr.responseText);
} else {
console.error("gowofee",xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error("gowofee",xhr.statusText);
};
xhr.setRequestHeader("Fk-Affiliate-Id","myid");
xhr.setRequestHeader("Fk-Affiliate-Token","mytoken");
xhr.send(null);
Now I am getting this error:
I tried to download a file from Dropbox using Core Api with javascript.
Here is the method I have written.
function downloadFile(path) {
var url = "https://api-content.dropbox.com/1/files/auto/"+path;
var result;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.send(path);
}
But I am always getting the status as 400. Don't know whats wrong. I got this below HTML as response.
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx</center>
</body>
</html>
Edit 1 :
var url = "https://api-content.dropbox.com/1/files/auto/" + path;
var result;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.setRequestHeader("access_token",token);
xhr.send();