XMLHttpRequest in Ajax and PHP - ajax

In internet explorer we can create the object of ActiveXObject like follows
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("note_error.xml");
It is possible to use the xmlDoc.load("note_error.xml"); for the object of XMLHttpRequest in other browsers.If no,any other substitute for this method when we use XMLHttpRequest.Please help...am using firefox as my browser

xmlDoc.async="false";
That's not doing what you think. async is a boolean property. When you assign the string "false" to it, you're getting the value true, because all non-empty strings are truthy.
It is possible to use the xmlDoc.load("note_error.xml"); for the object of XMLHttpRequest in other browsers.
Yes, in fact that's what you should be doing in IE too. There is no reason to use XMLDOM to fetch an XML Document; XMLHttpRequest can do that fine and it's much more widely supported.
var xhr= window.XMLHttpRequest? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHttp');
xhr.async= false;
xhr.open('GET', 'note_error.xml');
xhr.send();
var doc= xhr.responseXML;
If you do need an XMLDOM-like object in other browsers, it's called new DOMParser, but it's not as widely-supported as XMLHttpRequest.

the activeX 'concept' is only in Internet Explorer. All other browser implement a similar, but more or less standard version.
http://www.w3schools.com/Ajax/ajax_browsers.asp
that shows you how to create an xmlhttp object in 'any' browser.

Related

DocumentNode.SelectSingleNode return null

I want to get the time of this url "https://www.toutiao.com/a6619068128406028804/" with the HtmlAgilityPack, my code is as following:
string url = "https://www.toutiao.com/a6619068128406028804/"
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(url);
HtmlNode node_time= doc.DocumentNode.SelectSingleNode("/html/body/div[1]/div[2]/div[2]/div[1]/div[1]/span[2]");
time = node_time.InnerText.Trim();
node_time is always being null, how can I get the content of the time tag?
The problem is not the xPath selector, it's the fact that those elements are rendered client side. If you look at the actual initial get request (can do this in chrome/fiddler/ext) you see that those elements are not there. However there is a "articleInfo" json object inside of the "BASE_DATA" json string that is sent back. Normally you want to parse out that string and then deserialize it, then you have a structured object to grab data from. I normally use visual studio paste as classes feature but this seems kind of complicated for that and is mostly outside of the scope of your issue with this.
Also to note the object does get loaded into javascript but you cannot access that with HAP, if you were using headless browsers you could access that object directly using the execute javascript features.
So basically you can either parse out the json string manually or switch to something like a headless browser where the javascript is actually executed.

Does Ajax always require the use of node.js?

I learning about the use of AJAX in web development, and I need to know if AJAX always require the use of node.js, or JQUERY?
Thanks.
That is a very broad question, so the answer might be broad as well:
The short answer: Ajax does not require jQuery nor Node.js.
In practice, Ajax is a technology for asynchronous operations utilized by Javascript send data to and retrieve from a server asynchronously(1). Ajax is fully available in plain, vanilla Javascript, and it works as follows (example taken from Wikipedia, see sources):
// This is the client-side script.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php');
// Track the state changes of the request.
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
This is a classic example, showing both how to use Ajax with vanilla Javascript, and also why it's much easier with other means such as jQuery, shortening the same snippet to just:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
}).done(function(data) {
// Do something with data.
});
Sources (including vanilla Ajax examples):
Wikipedia: Ajax
A Guide to Vanilla Ajax Without jQuery
jQuery: ajax()
There is no need to use node.js to perform an Ajax request. You can make an Ajax request even using vanilla Javascript. However, jQuery made the Ajax request is very easy and cross-browser compatible with just some lines of code. So, I recommend you to stick with jQuery instead of using vanilla Javascript.
You can find more information regarding the jQuery Ajax feature here: http://api.jquery.com/jquery.ajax/
You can also find more information about the vanilla Javascript Ajax request feature here:
http://www.w3schools.com/ajax/
No, most browsers supply means to perform asynchronous javascript requests but libraries such as jQuery partly came about to smooth over the differences between browsers, making ajax a lot more portable.
Modern browsers generally don't have so great differences, so portability is probably is less of an issue, but using libraries has become common practice.

d3.js setrequestheader fails in ie8

Can someone say how to set a request header using the d3js xhr interface in IE8?
Code is like this:
d3.csv(url).header("accept","text/csv").rows(function(d) {...}).get(function(e,r) {...});
This doesn't have the desired effect in IE8, but works in Firefox and Chrome.
I load the aight compatibility library before loading d3, and the aight.d3 library after, but I don't think those are relevant to this problem.
The request is sent, but the response type is incorrect (it's json instead of csv), so the rows() function fails to get any data. At the server, the "Accept:" header value is */* from IE8, but text/csv from other browsers.
When I write the equivalent in bare javascript, IE8 sets the request header correctly.
I have d3 version 3.4.3.
Thanks for any help.
Regards,
--Paul
I'm not an expert on the subject, but looking through the d3 source code and various MSDN references, I think the problem is that d3 automatically checks whether you're using an absolute url reference, and if so assumes that it is a cross-domain request and switches to IE's XDomainRequest instead of XMLHttpRequest for older IE.
Relevant d3 source code (line 17-26):
var xhr = {},
dispatch = d3.dispatch("beforesend", "progress", "load", "error"),
headers = {},
request = new XMLHttpRequest,
responseType = null;
// If IE does not support CORS, use XDomainRequest.
if (d3_window.XDomainRequest
&& !("withCredentials" in request)
&& /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest;
The first line tests whether the XDomainRequest object exists (it does for IE8 and up), the second tests if the created XMLHttpRequest object does not have the withCredentials property for cross-domain requests (which only exists in IE10 and up), and the third tests whether the url starts with "http://" or "https://".
So, if you pass in an absolute url to any of the d3 file-grabbing functions in an IE8 or IE9 browser, it will use an XDomainRequest object instead of XMLHttpRequest.
Which is good if you want to actually grab files from a cross-origin server. Not so good if your same-domain server is expecting you to specify the accepted file type, since as far as I can tell XDomainRequest doesn't have any way of setting headers, and it certainly doesn't have the setRequestHeader method that d3 checks for (line 96):
xhr.send = function(method, data, callback) {
/*...*/
if (request.setRequestHeader) for (var name in headers)
request.setRequestHeader(name, headers[name]);
/*...*/
So how do you get it to work? If you're not doing a cross-origin request (and therefore XMLHttpRequest should work fine), specify your URL using relative notation if you can. Otherwise, you're either going to have to change the d3 source code or create the XMLHttpRequest yourself.

ajax response for node file

so still a newb to nodeJS and back end code in general. I need some help with ajax and node. For instance I have a function that goes like this
function random(response) {
var objToJson = {...};
response.write(objToJson);
response.end();
}
if instead of writing I want to pass this json object to another function as a response of an ajax call made to it how would that be?
Thanks for you help!
Node.js allows you to easy manipulate HTTP request and response objects.
Ajax still sends a HTTP request object and the Ajax onsuccess callback manipulates a HTTP response object.
Writing an object to a response for an ajax request allows your ajax success handler to manipulate that data.
There are abstraction libraries for RPC like now
It sounds like you want to return a javascript object to work with in your client-side code. While that's not possible directly (you can't send an object directly over HTTP; you're always serializing/deserialing in some fashion), you can certainly return a JSON payload and easily convert that to an in-memory javascript object. If that's what you're doing, you should set the response content type to application/json.
response.setHeader("Content-Type", "application/json");
If you're writing "pure" javascript (no framework wrapping XmlHttpRequest), you'll need to eval() the responseText to convert it to an object. If you're using something like jQuery, it will do that work for you (assuming you set the content type as suggested above).

Upload file and parameters with ajax request, pure javascript or prototypejs

I want to upload a file using an ajax request
var xhr = new XMLHttpRequest();
xhr.open("POST", "/photos");
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr.sendAsBinary(bin);
Works fine, but I want to post a parameter with this request ie: token=abc123
How can give a parameter to this request?
this is pure javascript, if you have the answer using prototypejs it's even better
Thanks a lot
You can still append query string parameters in a POST Request:
xhr.open("POST", "/photos/?token=abc123");

Resources