Ajax request response null - javascript

Ajax request is successful but response is null but I can see the result response in firebug as:
<?xml version="1.0" encoding="UTF-8" ?><response><likes>13</likes></response>
And in the console there is error as :
TypeError : response is null
var XMLHttpObject = createXMLHttpRequest();
$Id = null;
function process(id) { //makeAsynchornusRequest
if(XMLHttpObject.readyState == 0 || XMLHttpObject.readyState == 4) {
XMLHttpObject.onreadystatechange = responseHandler;
$Id = id;
XMLHttpObject.open("GET","like/" + id);
XMLHttpObject.send(null);
}
}
function responseHandler() {
if(XMLHttpObject.readyState == 4) {
if(XMLHttpObject.status == 200) { // 200 implies `ok` like 400 implies `page not found`
response = XMLHttpObject.responseXML;
xmlDocumentElement = response.documentElement;
output = document.getElementById("num_likes" + $Id);
output.innerHTML = xmlDocumentElement ;
}
}
}

You have tagged JQuery - try using JQuery for your Ajax call:
$.ajax({
url: '/Likes',
data: { id: id },
success: function (response) {
if (response) {
console.log(response);
}
},
error: function (xhr, s, sa) {
console.log(s, sa);
},
complete: function () {
console.log('complete event');
}
});

Can you try switching this to an onLoad event handler.
From mozilla docs:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log(xhr.responseXML);
}
}
};
xhr.send(null);
With your code (note you may need to tweak the responseHandler() body slightly:
XMLHttpObject.open("GET","like/" + id);
xhr.onload = responseHandler;
XMLHttpObject.send(null);

Related

How to send AJAX post request and receive back JSON data in Vanilla JS?

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

Firefox onClick event does not work

I'm trying to debug a third party script.
It works fine in Chrome. But Firefox won't register the onclick event.
Any idea why FireFox won't play nice?
I tried adding return false; as suggested here but it did not work, adding that above the very last closing bracket just produces more errors when viewed in console.
function ac_event(event, eventdata) {
return ajax({
url: activecampaignevent.ajax_url,
type: 'POST',
data: {
action: 'ac_event',
event: event,
eventdata: eventdata
},
success: function (response) {
console.log('response', response);
}
});
function ajax(options) {
var request = new XMLHttpRequest();
var url = options.url;
var data = encodeData(options.data);
if (options.type === 'GET') {
url = url + (data.length ? '?' + data : '');
}
request.open(options.type, options.url, true);
request.onreadystatechange = onreadystatechange;
if (options.type === 'POST') {
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
} else {
request.send(null);
}
return;
function onreadystatechange() {
if (request.readyState === 4 && request.status === 200){
options.success(request.responseText);
}
}
function encodeData(data) {
var query = [];
for (var key in data) {
var field = encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
query.push(field);
}
return query.join('&');
}
}
}
Click this link to test
you can create event in javascript and assign it with browser event to stop with preventDefault.
document.querySelector("#LinkID").addEventListener("click", function(event){
//do your code here
alert("preventDefault will stop you to go")
event.preventDefault();
}, false);

if-URL-exists check with javascript

I'm trying to create an if-file-exists check on a URL.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else xhr = null;
return xhr;
}
function UrlExists(url) {
var http = createCORSRequest('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
if (this.status == 404) {
alert(url + " is NOT available!");
} else if (this.status != 0) {
alert(url + " is available!");
}
}
};
http.send();
}
UrlExists("http://bar.baz");
UrlExists("http://google.com");
</script>
Testing URLs
</body>
</html>
Currently getting a XMLHttpRequest cannot load http://google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. error -- even when its running through Apache HTTPd on Mac OS 10.9.
Can you all help me to get this to work?
This is a cross origin issue.
You have to use proxy.
For example, I've used YQL.
Try the following:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");

Passing values from javascript to servlet not working in chrome

Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()

jquery getJSON IP

I am trying to convert the following code to work with jquery:
var req = new XMLHttpRequest();
req.open('GET', 'http://jsonip.appspot.com', true);
req.onreadystatechange = function (e) {
if (req.readyState === 4) {
if(req.status === 200) {
var ip = JSON.parse(req.responseText);
alert(ip.address);
} else {
alert("Error loading page\n");
}
}
};
req.send(null);
This the jquery piece that doesn't work:
$.getJSON("http://jsonip.appspot.com",
function(data){
alert( "Data Returned: " + data.ip);
});
This host supports JSONP custom callbacks, so you can get the result by:
$.getJSON("http://jsonip.appspot.com?callback=?",
function(data){
alert( "Data Returned: " + data.ip);
});
Check the above code here.
Try this:
$.getJSON('http://jsonip.appspot.com?callback=?', function(data) {
console.log( data.ip );
} );

Categories

Resources