Ajax parsexml without jquery - javascript

I have a piece of code to get the unread count of Gmail. It is using jQuery, and I would like to know how to do it without a Javascript library, just with Javascript.
$.ajax({
type: "GET",
url: "https://mail.google.com/mail/feed/atom",
dataType: "xml",
success: parseXml
});
function parseXml(xml)
{
var result = $(xml).find("fullcount").text();
alert("count:" + result);
}

try this
var xmlhttp=new XMLHttpRequest();
xmlhttp.setRequestHeader("Access-Control-Allow-Origin","https://mail.google.com");
xmlhttp.open("POST","https://mail.google.com/mail/feed/atom",false,"username","pwd");
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var mailCount=xmlDoc.getElementsByTagName("entry").length;

ok, Solved
xhrGmail = new XMLHttpRequest();
xhrGmail.open('GET','https://mail.google.com/mail/feed/atom')
xhrGmail.onload = function() { console.log(xhrGmail.responseText.split("<fullcount>") [1].split("</fullcount>")[0]) }
xhrGmail.send(null);

Related

Request JSON by AJAX in two ways

I don't know why but when I do request JSON in this way console log prints nothing:
var xhr = new XMLHttpRequest();
function elenco_studenti() {
var url = "/controller?action=student_list";
xhr.responseType = 'text';
xhr.open("GET", url, true);
xhr.onreadystatechange = print();
xhr.send(null);
}
function print(){
console.log(xhr.responseText);
}
Instead when I do request JSON in this way, it works:
$(document).ready(function(){
$.ajax({
url: '/controller?action=student_list',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
});
Can you help me? Thank you very much.
Assign the function reference instead of invoking the function
xhr.onreadystatechange = print();
to
xhr.onreadystatechange = print;
and wait for the actual response to be ready
function print() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
link to docs

Using AJAX GET request to pass the value of <option> tags to the URL

I want to pass options' values to the URL whenever the users select an option. For example these are the options:
Option 1
Option 2
Option 3
And this is the URL: http://example.com/products
When he selects an option among those 3, the URL changes into this: http://example.com/products?option=option1
I tried vanilla Javascript XMLHttpRequest for this, and this is my code:
function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState < 4) {
return;
}
if(xmlHttp.status !== 200) {
_fallback(xmlHttp.response);
return;
}
if(xmlHttp.readyState === 4) {
_callback(xmlHttp.response);
}
};
xmlHttp.open(_method, _url, true);
xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
_sort.addEventListener('change', function(){ //If the value of the field changes
var _frmData = new FormData(); //Create a new FormData object
_frmData.append('sort', _sort.value); //Append the value to this object
ajaxFormValidate('GET', location.href, function(response){
//Perform the redirection here (without reloading the page)
}, function(response){
alert("Request cannot be sent!");
}, _frmData);
}, false);
});
Recently, I don't have any ideas for this. Any help is appreciated. Thanks
This is a good way of using GET in pure Javascript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
console.log(data);
}
}
And this is the jQuery way (my preferred method):
var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){
if(data =='success'){
alert('done deal...');
}
}
});

Why wikipedia ajax call is not working

var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&search=' + search;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function() {
var data = JSON.parse(ourRequest.responseText);
console.log(data);
};
ourRequest.send();
Can someone tell me why i am not able to get parsed data in my console.
You need to add one more parameter to your url variable to make this request work -
origin=*. Add it and your code will be fine.
Check how I've changed the url variable. Wikipedia API requires the request origin included in the parameters string.
document.getElementById('do-search').addEventListener('click', search);
function search(){
var search = document.getElementById('search').value;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search='+search;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function() {
var data = JSON.parse(ourRequest.responseText);
document.getElementById('results').innerHTML = data;
};
ourRequest.send();
}
<input id="search" type="text">
<button id="do-search">Search</button>
<div id="results"></div>
Well i made it to work with the following code.
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});

converting javascript code to jquery

I have following code of javascript for search function. It works well when written inside html/php file it self, however, when I try to add this in my jQuery file, it doesn't work anymore.
<script type="text/javascript">
function findmatch(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
document.getElementById('search_result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'php/search.php?search_text='+document.search.search_text.value , true);
xmlhttp.send();
}
</script>
I tried replacing 'getElementById' with $('#') and few some ways. But didn't work. I want to convert in jQuery so I can manage/animate 'search_result' div according to size of result returned. I don't know how will I do that. But, if you can guide me fir that extra, It would be great/
If i understand correctly, it's Ajax call:
<html>
<head>
<script src="jqueryLibrary.js"></script>
<script type="text/javascript">
function findmatch() {
$.ajax({
url: 'php/search.php?search_text=' + document.search.search_text.value,
type: 'get',
success: function(responseText){
$('#search_result').text(responseText);
}
})
}
</script>
</head>
</html>
try this one
function findmatch(){
$.ajax({
type : "GET",
url : 'php/search.php?search_text='+document.search.search_text.value,
cache : false,
async : false,
success : function(data) {
$('#search_result').text(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
So this should work:
function findmatch() {
$.post('php/search.php?search_text='+document.search.search_text.value,function(response){
$('#search_result').html(response);
});
}
//EDIT: Made a mistake, semikolon after function findmatch() { }; <<
Greetings

Javascript - XMLHttpRequest failing in Internet Explorer

* SOLVED * Answer is in separate post below
This code runs fine in FireFox but it will not run in Internet Explorer 8. It gives me the error of "access denied. Is there something I am missing?
function loadXMLDoc(dname){
if (window.XMLHttpRequest){
var xhttp=new XMLHttpRequest();
}
else{
var xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc=loadXMLDoc("notSchema.xml");
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
It specifically doesn't like the .open() and the .send()
Edited...
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
xmlDoc = http;
alert(http);
x=http.getElementsByTagName("ROOT_NODE_ID");
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Edited the Code once again. What I'm trying to do is load the XML, parse for the tag "ROOT_NODE_ID" and then get that value and store it into an array
When I run that code in firefox, it returns 51, which is the number of ROOT_NODE_ID tags and fills the tree that I am making.
When I run the same exact code in IE8, it does not even alert.
I'm Stumped.
I figured it out. Like I said before, if you run the code above in Firefox, it returns the 'object' and if you run it in IE8, it returns the contents of the object. I solved this problem by loading the content of the object again in IE8, thus turning the content of the object back into an object that will be ready to be parsed. If that makes any sense.
Just to clarify to people that are just visiting this thread. When I called 'alert(http);' in firefox, it would return '[object XMLDocument]', but in IE8 it would return the actual contents of '[object XMLDocument]'.
var treeArray=new Array();
var count = 0;
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
//Loading the contents of the object 'http' a second time, which turns it into an object again.
xmlDocument.loadXML(http);
x = xmlDocument.getElementsByTagName("ROOT_NODE_ID");
alert(x.length);
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Zack,
You can use jquery to do the ajax call - jquery will do everything properly behind the curtains.
In your case here:
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(html){
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
},
error: function(html){
alert('failure: ' + html);
}
});
}

Categories

Resources