jquery getJSON IP - javascript

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

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

Change from jQuery to Plain Javascript in Post Request

I am trying to replace all the jQuery dependency with plain javascript in the following post request.
<script type="text/javascript">
$(function()
{
$.post("test_post.php",
{
name: "John Doe",
age: "42"
},
function(data, textStatus)
{
alert("Response from server: " + data);
});
});
</script>
Any ideas how?
You can play around, but this is the basic example:
var request = new XMLHttpRequest();
request.open('GET', 'test_post.php?name=john+doe&age=41', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
alert(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();

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

Ajax request response null

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

HTML5 java script XMLHttpRequest status 0 and responseText is empty

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>

Categories

Resources