Fill div with a php script via Ajax call? - javascript

I'm wondering what is the simplest way to fill a div by grabbing a PHP script (and send data like POST or GET) to process what data to return.
But without the use of a library... All I ever find is prototype and jquery examples.
Has any one done this without a library?

var xmlhttp;
function showUser()
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="yourpage.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("yourdiv_id").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

I'd suggest you look at this code.
You will see how to handle perfectly XHR objects, and it also gives you some sugar syntax.
Btw, a less-than-one-hundred-lines "library" should be fine, since it basically does what you want it to, and no more.

Related

Response.Redirect and javascript ajax call

I am using javascript to make call to server. The javascript code is following,
function cs() {
alert("");
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "lp.aspx?pb=true", true);
xmlhttp.send();
}
And my server code is following
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["pb"] != null)
{
Response.Redirect("main.aspx");
}
}
The problem is my Response.Redirect is not working with my ajax call. Why is that?
You can not redirect on ajax call, because, it expects some return value from the invoked page. And if that page itself redirects, it has no way to tell calling function to redirect, as it simply expects some return value in success callback.
So to solve this, you can return a param lets say { redirect: true } if condition satisfied. And on success callback , if redirect is true, then redirect using JS - window.location.href="required".
I believe that redirect doesn't work because the Response for the page with the javascript is closed before the AJAX call is even made.
Instead of using Response.Redirect you could send back a string containing the url and in your script use location.href to redirect.
Simple you can not use response on ur ajax call. use
window.location

Catch cross domain response in pure javascript ajax [duplicate]

This question already has answers here:
How to make a JSONP request from Javascript without JQuery?
(12 answers)
Closed 8 years ago.
I want to catch cross domain response in pure javascript ajax not using jquery or other external libraries.
var xmlhttp, response;
try {
xmlhttp = new XMLHttpRequest();
} catch(e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e2) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
if(callback != undefined) {
console.log(xmlhttp.responseText);
}
}
}
url = "http://xxxx.com/layer.php?callback=callRes";
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("Content-Type",
"application/json,application/javascript,text/javascript");
xmlhttp.send();
spent lots of time and googling but not find any solution
suggestions are most welcome but not script method only pure javascript ajax
I assume you want to see the response in console.
Before calling console.log() you are checking to see if callback exists. In the given piece of code callback is not yet defined so maybe this is the only barrier preventing the output of xmlhttp.responseText.
Solution: remove if (callback != undefined) and just call console.log(xmlhttp.responseText)

Show Save-As window from JSP

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

Running Ajax in IE, FF, and Safari

I'm trying to create an ajax connection to a weather xml feed and then parse returned data. I don't have any issues making a connection via IE, but for some reason I don't have any luck in FF or Safari. Basically what I'm doing is running an html file that contains the following code.
<html>
<script type="text/javascript" language="javascript">
function makeRequest(zip) {
var url = 'http://rdona.accu-weather.com/widget/rdona/weather-data.asp?location=' + zip;
//var httpRequest;
var httpRequest = false;
if (window.XMLHttpRequest) {
document.write("xmlhttprequest");
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
// See note below about this line
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
httpRequest.open('GET', url, true);
httpRequest.send('');
}
function alertContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
makeRequest(84405);
</script>
</html>
Any help and or suggestions would be greatly appreciated.
I'm afraid you will run into some issues because of same origin policy, meaning that you cant do XMLHTTPRequests to another domain.
Not even jQuery (which you really should check out anyways) can help you with that.
I strongly suggest you use a framework to do this sort of thing. Frameworks will do all of the browser compatibility stuff for you.
On the other hand, if you are interested in how to do this as an academic exercise... still get a framework! See how the framework does it and you will immediately learn all of the pitfalls.
Mootools is my framework of choice.
In order to perform a basic AJAX request in Mootools you would do the following:
window.addEvent('domReady', function() {
new Request({
'url': "The url where you want to send the request
'data': "Some data to send. It can be an object."
}).send();
});
Full documentation for the Request class can be found here.
If you want to see how Mootools implements cross-browser AJAX, you can find the source of the Request class here.
You'll find the source for Browser.Request particularly useful.
For cross browser stuff, I recommend you use a library like JQuery because it will quietly smooth over IE vs Firefox vs Safari etc issues. Also to make the code format properly, use the 101010 button in the toolbar.

What more is needed for Ajax than this function

I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.
Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax.
I would remove this line.
alert("Your browser does not support AJAX!")
Shouting at the user in a language he probably doesn't understand is worse than failure. :-)
I've never been a fan of nested try/catch blocks, so I'd do it something like:
var xmlHttp;
if (window.XMLHttpRequest) {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (xmlHttp) {
// No errors, do whatever you need.
}
I think that'll work. But as has been mentioned before - why reinvent the wheel, use a library. Even better - find out how they do it.
jQuery is probably one of the lightest popular libraries out there.
The same thing in prototype:
function loadPage(pagePath, displayElement) {
new Ajax.Updater(displayElement, pagePath);
}
Ajax.Updater in Prototype API
If you really want to see what you are missing, read the jQuery or Prototype source code for their ajax routines. If there are bug numbers in the comments, look those up as well.

Categories

Resources