var xmlHttp;
function RefreshORP(eventTarget, eventArgument)
{
xmlHttp = GetXmlHttpObject();
if(xmlHttp == null)
{
return true;
}
xmlHttp.onreadystatechange = StateChanged;
var params = GetFormParam(eventTarget,eventArgument);
xmlHttp.open("POST","/contact.jsp",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("ajaxcall", "true");
xmlHttp.send(params);
}
In jQuery you have it all done...
$.post("/contact.jsp", $("formID").serialize(), function(data){
// process callback
});
jQuery will also set all appropriate (and somehow standardized) request headers.
Related
We have the following method to invoke the URL using ajax.
Currently after hitting the url we are using the response.
So we want to put a timeout for reposne.So when we invoke the url if the response didn't came after 2sec then call one more method and if resp comes within two seconds call other mehtod.
We have tried using the timeout,but unable to made it working with the code.
function ajaxCall(url1) {
var ajaxresp = null;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url1, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
ajaxresp = xmlhttp.responseText;
//function call
getAdResponse(ajaxresp);
}
}
}
}
Please advice me how to proceed.
Try smth like this
xmlhttp.open("GET",url1,true);
xmlhttp.onreadystatechange= function (){
if (xmlhttp.readyState==4){
if (xmlhttp.status == 200){
ajaxresp = xmlhttp.responseText;
}
}
xmlhttp.send();
setTimeout(function() {
if(ajaxresp) {
dosmth(ajaxresp);
} else {
dosmthelse();
}
}, 2000);
I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
I tried this code :
var xmlHttp = new XMLHttpRequest();
function activecomm(comm_id,a_link_id)
{
var postComm = "id="+encodeURIComponent(comm_id);
var url = 'comments_mgr_proccesser.php';
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleInfo(a_link_id);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", postComm.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postComm);
}
function handleInfo(a_link_id)
{
if(xmlHttp.readyState == 1)
{
document.getElementById("commactiveresult").innerHTML = 'loading ..';
}
else if(xmlHttp.readyState == 4)
{
var response = xmlHttp.responseText;
document.getElementById("commactiveresult").innerHTML = response;
}
}
When readyState == 1 the contents of the commactiveresult element is updated, but when readyState == 4 nothing is shown in the same element.
Does anyone know what the problem is please?
You're calling the handleInfo function instead of assigning a ready state handler. Try
xmlHttp.onreadystatechange = function (){
handleInfo(a_link_id);
};
I have 2 .jsp pages.
The 1. one contains just a xml structure for applicants:
<% response.setContentType("text/xml") ; %>
<applicant>
<citizenship>GERMANY</citizenship>
<residence>Inc.</residence>
<street>9500 Gilman Drive</street>
<city>La Jolla</city>
<state>USA</state>
<countryTelCode>Vandelay Industries</countryTelCode>
<zipCode>Inc.</zipCode>
<areaCode>9500 Gilman Drive</areaCode>
<telNumber>La Jolla</telNumber>
<major>USA</major>
<awarded>Vandelay Industries</awardeds>
<gpa>Inc.</gpa>
<specialization>9500 Gilman Drive</specialization>
</applicant>
The second one tries to retrieve GERMANY from the tag and print it in the "..." field of:
<span id="Citizenship">...</span>
using this code after calling showCustomer():
<script type="text/javascript">
function showCustomer() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "getApplicant_xml.jsp";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var xmlDoc = xmlHttp.responseXML.documentElement;
document.getElementById("Citizenship").innerHTML = xmlDoc.getElementsByTagName("citizenship")[0].childNodes[0].nodeValue;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
</script>
Unfortunately it does not print anything....
I would be really thankful if someone finds my mistake.
Thank you
Your problem is that xmlHttp.responseXML is null. You need to parse a new DOM object from xmlHttp.responseText. I fixed the code.
<script type="text/javascript">
function showCustomer() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = "getApplicant_xml.jsp";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var xmlDoc = xmlHttp.responseText;
xmldom = (new DOMParser()).parseFromString(xmlDoc, 'text/xml');
text = xmldom.getElementsByTagName("citizenship")[0];
document.getElementById("Citizenship").innerHTML = text.childNodes[0].nodeValue;
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
};
</script>
How can I rewrite this code without using jQuery? I need to do it in a mobile app where I can't use jQuery.
$.ajax({
type: "POST",
url:"../REST/session.aspx?_method=put",
data: JSON.stringify(dataObject, null,4),
cache: false,
dataType: "json",
success: onSuccessLogin,
error: function (xhr, ajaxOptions){
alert(xhr.status + " : " + xhr.statusText);
}
});
You can try this:
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) {
// What you want to do on failure
alert(xmlhttp.status + " : " + xmlhttp.responseText);
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// What you want to do on success
onSuccessLogin();
}
}
xmlhttp.open("POST", "../REST/session.aspx?_method=put", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Cache-Control", "no-cache"); // For no cache
xmlhttp.send("data=" + JSON.stringify(dataObject, null,4));
As for how to do more stuff with only javascript without jQuery library take a look at W3Schools AJAX Tutorial or Mozilla - Using XMLHttpRequest
And as duri said, you will have to find a way to convert dataObject to string, as not all browsers support JSON object.
try this
var xmlHttp = createXmlHttpRequestObject();
//retrieves the xmlHttpRequest Object
function createXmlHttpRequestObject()
{
//will store the refrence to the xmlHttpRequest Object
var xmlHttp;
//if running in internet explorer version below 7
if(window.ActiveXObject)
{
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error Creating the xmlHttpObject");
else
return xmlHttp;
}
function callThisFunction()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
var queryString = JSON.stringify(dataObject, null,4);
var url = "../REST/session.aspx?_method=put";
xmlHttp.open("POST", url, true);
//Send the proper header information along with the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", queryString.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = checkHandleServerResponse;
xmlHttp.send(queryString);
}
}
function checkHandleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var JSONFile = 'jsonFormatData = '+xmlHttp.responseText;
eval(JSONFile);
if(jsonFormatData.description == 'Success')
{
//showDialog('Success','Login Successful','success',3);
location.href='default.aspx';
//setTimeout(function(){location.href='myGrupio.php';},3000);
}
else
showDialog('Error','You Need a Valid Login.','error',3);
}
else if(xmlHttp.status == 400)
{
setTimeout( function()
{
alert('you have error');
},3000);
}
else
alert("Error Code is "+xmlHttp.status)
}
}
For the Ajax request itself, have a look at the XMLHttpRequest object (special treatment for IE).
To parse the JSON response (dataType: 'json'), use JSON.parse (you might need the json2.js library).
jquery is already javascript. It's a library, entirely written in javascript. So you can use it within every javascript project. If you want to write a rest client yourself, you might look at this article
You may also consider using jQuery Mobile edition - very light - 17KB minified. 1.0 is alpha now, but I think it will be more stable and portable than self-baked code.