I need a function that click one link, send ajax request to 2 pages one by one.
first send data to page1.php, when finish page1's work, back the data to the main page, then send data to page2.php do another ajax process and return data to the main page.
I write page2.php Request in page1.php document.getElementById("div1").innerHTML = HttPRequest.responseText;, but this will only return the page2's data and miss back the data from page1.php
in firebug , consule:
page1.php (always show loading.gif)
page2.php 200 OK 2199ms
how to do the ajax one by one well? Thanks.
function myajax(text) {
var HttPRequest = false;
if (window.XMLHttpRequest) {
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'page1.php';
var pmeters = "text=" + text;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("div1").innerHTML = HttPRequest.responseText;
var url = 'page2.php';
var pmeters = "text=" + text;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("div2").innerHTML = HttPRequest.responseText;
}
}
}
}
}
There are two options to do it.
Use Ajax in Synchronous mode, so the code will wait until you get results from page1
Call the Ajax method for Page2 only at the response of Page1
Option 2 is better since it work in Asynchronous mode.
Here is a pseudo code:
var xhr = new XMLHttpRequest();
xhr.open( ..)
xhr.onreadstatechange = function() {
// handle page1 response
// do page2 reauest
var xhr2 = new XMLHttpRequest();
xhr2.open( ... )
xhr2.onreadystatechange = function() {
// handle page2 response
}
xhr2.send(null);
}
xhr.send(null);
Related
I've been struggling for hours with following code without success. In my html I have several inputs (type=text, type=date and selects), and a button calling a js function: onclick=SendNewData().
The JS function is something like the following:
function SendNewData() {
var MyData1=document.getElementById("id1").value;
var MyData2=document.getElementById("id2").value;
var MyData3=document.getElementById("id3").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', 'Handler.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("FormNuevaCom").innerHTML = xmlhttp.responseText;
}
}
var data = new FormData;
data.append('DATA1', MyData1);
data.append('DATA2', MyData2);
data.append('DATA3', MyData3);
xhr.send(data);
}
and the Handler.php is something like the following:
if(isset($_POST['DATA1'])) {
$MyVar=$_POST['DATA1'];
echo "Hi there! ".$MyVar." received...";
}
I canĀ“t get any response. Anyone can spot the problem?
I have one nominal.jsp page,which includes header.jsp.Here i am using Ajax for the first time, for the request in header.jsp,then for the second time Ajax request is called to the nominal.jsp,i am facing the conflict issue in the Ajax request. Because of this issue,my preferred drop-down list is not displayed. Sometimes when response is entered in the JavaScript, the drop-downs are displayed and if the response are not entered in the JavaScript, the drop-downs are not displayed. Tried my level best to resolve the issue, but could not resolve it. Please help me guys
thank u,
My header.jsp code:
<script>
headerDisplay();
function headerDisplay()
{ var url ='<%=request.getContextPath()%>/summary?operation=header';
transactionRequest(url);
}
function transactionRequest(url)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = transactionResponse;
try
{
req.open("POST", url, true); //was get
}
catch(e)
{
alert("Problem Communicating with Server\n"+e);
}
req.send(null);
}
else if (window.ActiveXObject)
{
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = transactionResponse;
req.open("POST", url, true);
req.send();
}
}
}
function transactionResponse()
{
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{ var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
}}}......
</script>
And,this is my nono.jsp code:
<%#include file="/pages/common/header.jsp"%>
<script>
function displayNominal()
{
document.getElementById("ajaxLoading").style.display="block";
var url ='<%=request.getContextPath()%>'+'/nominalList';
postRequest(url);
}
function postRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = nominalSelect;
try {
req.open("POST", url, true); //was get
} catch (e) {
alert("Problem Communicating with Server\n" + e);
}
req.send(null);
} else if (window.ActiveXObject) {
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = nominalSelect;
req.open("POST", url, true);
req.send();
}
}
}
function nominalSelect() {
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
if (userId == null || userId == "") {
window.location = '/accounts1/?status=session';
}
}}..
</script>
<body class="bodystyle" onload="displayNominal()">
<% if("N".equals(roleDemoStatus))
{%>
<!-- /#demo Header -->
<div style="top: 0px; display: block;" id="header" class="fixed">
<div class="outer">
<h1 class="blog-title" style="text-align:center;margin-top:10px;"><span style="font-weight: normal; color:#777777; font-size: 30px;">accounts<font color="#5DA915">1</font>.co</span> Demo Only - <font color="red">Click Here</font> To Use For Free Forever</h1>
</div><!-- .outer -->
<div style="display: block;" class="shadow"></div>
</div>
<!-- /#Demo Header -->
<%} %>
</body>
Again thanks for advance.
Use a single callback and a try/catch block to enforce the request order:
function transactionResponse()
{
// Check whether this is the initial callback or a subsequent one
if (!!transactionResponse.state)
{
try
{
//POST data from the GET request
}
catch(e)
{
//Get data from the GET request
}
}
// Set state after the initial callback reference
else
{
transactionResponse.state = this;
}
}
References
Long Polling Experiment
I want to make a request to external domain,
parameter is sent correctely to php file (on external server)
but "request.responseText" allways empty,
thanks in advance (an example will be very apreciate)
<script type="text/javascript">
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest() {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var url = 'http://www.mydomain.fr/connexion.php?term=3334';
request.open("GET", url, true); // define the request
request.send(null); // sends data
request.onreadystatechange = function() {
if (request.readyState == 4) {
//response allways empty
document.getElementById("context").innerHTML = request.responseText;
}
}
}
window.onload = ajaxrequest();
</script>
<div id="context"></div>
by default you cannot just load data from another server, however if the server is configured to allow cross origin requests then you'll be good to go.
Take a read through the info here
http://www.html5rocks.com/en/tutorials/cors/
I am working in PHP I have created a page here I have 2 combo box when I select first combo box item the second one is filled according the first combobox using JavaScript the problem I am facing is where I am trying to save the data of second combo box in database I found null value. transition_party_id is the combobox that fill dynamically here I code
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;
}
}
}
return xmlhttp;
}
function getparty(category) {
var strURL="../admin/get_partyname.php?category="+category;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('partydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
req.open("GET", strURL, true);
req.send(null);
You send 'null' post data by "GET" method.
Or you waiting data in get?
There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is
My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT
This is the code I referred : code
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
you have to check, if the request was successful:
if (req.readyState === 4) {
// what should be done with the result
}
finally, it has to look like this:
req.onreadystatechange = function () {
if (req.readyState === 4) {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
}