I'm new to web-development. Created a signup page making some asynchronous calls to php. Ran debugging found the control skips the onreadystatechange function completely. Please help...
var ajax = ajaxObj("POST", "signup.php"); //defines the ajax object, definition is below
ajax.onreadystatechange = function () { //doesn't run after this line
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box
at <u>"+e+"</u> in a moment to complete the sign up process.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g); //control reaches here directly
}
}// control exits here
The ajax object is created externally here..
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is because it's an event callback function and it will be called when server responds to your ajax request. If you're using firefox press F12, switch to network tab and check html and xhr to see it's status.
Because it is asynchronous so the function won't be called as you step through the code in a linear fashion.
It gets called by native code when the ready state changes.
Stick a breakpoint inside the function if you want to debug it.
Related
I have some javascript that sends a XMLHttpRequest to a PHP file. This PHP file sends a response, and javascript is supposed to create a URL and redirect to it, using the response text as a parameter. In all other browsers it works fine, but Firefox won't include the response text in the URL.
This is the javascript example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'filename.php', true);
xhr.onreadystatechange = function(e){
var id = e.currentTarget.responseText;
var urlWithId = "restofurl?id=" + id;
window.location.href = urlWithId;
}
xhr.send(fd);
and filename.php is just a number at the moment:
<?php
echo "3";
?>
I have tried putting other parts of the url (up to the whole url) in the php part, and firefox always cuts out exactly that part. I have also tried copying the response several times to different variable, copying it character by character, putting it in a function that just returns the input again,...
This is only going to be on my own computer, so I don't need to worry about any security issues, so I'm mostly looking for an easy way to cheat around this rather than the way it would be done professionally. Does anyone have any idea?
This is a basic example, you actually have to test readyState status. If i remember well, it is also safer to set the event function before sending the request (not really sure of that).
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
//do something with this.responseText
}
};
xhr.open("POST", url, true);
xhr.send();
EDIT:
This is one of the reasons why i use frameworks, for the old browser support, but this is not an answer. To be more precise, in the past (present?), browsers used to implement exotic functions. It's been a long time i didnt bother to use XHR objects directly, last time it was for file uploads with loading bar (canvas). It shows you the basic way to handle some stuff. This is longer and a bit old fashioned, but well, it works.
function customXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest;
}else{
try{ //the weird ones
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex){
return null;
}
}
}
var xhr = customXHR(), pleaseStop = false, startDraw = false;
if(xhr){
xhr.addEventListener('load', function(e){
var jsonRep;
if(!pleaseStop){
//did use a JSON response
jsonRep = $.parseJSON(e.target.responseText);
//do the rest, we finished
}
}, false);
xhr.addEventListener('error', function(e){
//error
pleaseStop = true;
}, false);
xhr.upload.addEventListener('progress', function(e){
//why not let this as an example!
//file_size must be retreive separately, i fear
if(e.lengthComputable && file_size > 0 && !pleaseStop && startDraw){ draw_progress(e.loaded / file_size); }
}, false);
xhr.addEventListener('loadstart', function(e){
//can be used too
}, false);
xhr.addEventListener('readystatechange', function(e){
if(e.target.status == 404 && !pleaseStop){
//error not found
pleaseStop = true;
}
if(e.target.readyState == 2 && e.target.status == 200){
startDraw = true;
}
/*if(e.target.readyState == 4){
//not used here, actually not exactly the same as 'load'
}*/
}, false);
xhr.open("POST", url, true);
xhr.send();
} //else no XHR support
I am loading a page through xmlHttpRequest and I am not getting one variable which come into existance after some miliseconds when page loading is done
so the problem is when xmlHttpRequest sends back the response I do not get that variable in it.
I want it to respond back even after onload.
var xhr = new XMLHttpRequest();
xhr.open("GET", event.url, true);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() { callback(); };
xhr.followRedirects = true;
xhr.send();
I tried setTimeOut but of no use because may be at that time call is finished
xhr.onload = function() {
console.log('wait for response');
setTimeout(function(){
callback(xhr.responseText);
},2000);
};
I tried readyStateChange , but no success
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
callback(xhr.responseText);
};
};
by the way, I am trying to load amazon signIn page
and the variable which is missing everytime is hidden Input Field metadata1,
I get all other hidden Input fields in response text , except input field, named "metadat1"
I'll be more than Happy, If anyone can help.
Thanks in advance
ohh Finally I did it,
I din't read any javascript, Instead I just extracted scripts which I received in xhr calls and executed it inside a hidden div, and here it is , I got that variable's value
abc(xhr.responseText);
function abc(xhrRes){
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrdiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var scr = document.getElementById('xhrdiv').getElementsByTagName("script");
//5 scripts needed to generate the variable
for(i=0;i<5;i++){
eval(scr[i].innerHTML);
if( i+1 == 5){
var response = document.getElementById('xhrdiv').innerHTML;
return response; //and in this response variable I have every thing I needed from that page which I called through xmlhttp Req
}
}
}
---------------------Improved Version-----------------------
Instead of executing script through eval,
keep script content in a file AND Include it, as we normally include the script, that works better.
xhrRes = xhr.responseText;
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrDiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var xhrDiv = document.getElementById('xhrDiv');
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = JSfile;
xhrDiv.appendChild(newScript);
(it shows the edit is done my anonymous user, :( because I forgot to Login, while editing)
If the data doesn't exist until some time after the page has loaded then, presumably, it is being generated by JavaScript.
If you request the URL with XMLHttpRequest then you will get the source code of that page in the response. You will not get the generated DOM after it has been manipulated by JavaScript.
You need to read the JavaScript on the page you are requesting, work out how it is generating the data you want to read, and then replicate what it does with your own code.
I have an ajax request executing through the XMLHttpRequest() object
My AJAX method is called in this format:
var xmlhttp = new XMLHttpRequest();
$(document).ready(function () { LoadData(); });
function LoadData()
{
var parameters = "DisplayData=true";
var url = "default.aspx";
Send(url, parameters, "DisplayData");
CheckForAbort();
}
function Send(url, parameters, QueryType)
{
...
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-lencoded");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange = function (){...}
}
There is also a timer on the page which refreshes the data by making a new request through the Send(...) method in intervals of 15 seconds. Every .3 seconds and it calls an Elipsis() method that displays and "blinks" the "loading message" (if appropriate to be displayed) and checks for the abort.
var Color = "red";
function Elipsis() {
if (ResponseMessage != "")
{
if (Color == "darkred") { Color = 'red'; } else { Color = 'darkred'; }
$("#StatusResponse").css("display", "block");
$("#StatusResponse").css("color", Color);
CheckForAbort();
}
}
function CheckForAbort()
{
console.log("MenuActivted: " + MenuActivted);
if (MenuActivted)
{
xmlhttp.abort();
ResponseMessage = "Aborting Request";
MenuActivted = false;
}
}
But when the user clicks the menu bar which is an anchor tag with the HREF set to another page. The browser doesn't respond until the ajax request has completed it's fetch.
The HTML HREF is called the following way on an ASPX page:
<%#Eval("Text")%>
the Ajax Abort sets the flag that is checked in the CheckForAbort() method:
var MenuActivted = false;
function AbortAjax()
{
MenuActivted = true;
return false;
}
I am running IE 11 on Win 7. I have called an abort() method in another section of the code. which executes the xmlhttp.abort(). The response status and ready state respond (console output below) but the page still waits to respond to the HREF
Console output:
HTML1300: Navigation occurred.
File: ChangePassword.aspx
MenuActivted: true
ReadyState: 4
Status: 0
Does anyone have a solution to this problem?
[Updated **********]
I thought I had the solution but I didn't.
I commented out the set header but although it allowed my HREF to execute it was because the xhr was throwing an error and the fetch was terminating.
xmlhttp.open("POST", url, true);
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
Please read the entire post before responding.
I'm trying to update a status page live.
I'm using Ajax to update the page. The update is set to update every 3 seconds. But whenever the update is being called the browser freeze at least for a second or two.
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
If someone can give me tips on improving this. To make it less laggy or make it go away.
2) I have been thinking about using JQuery. Should I make the move? Pros and Cons? Also how is JQuery performance wise comparing to just JavaScript ?
You are letting the AJAX request run synchronously - which you never ever need to so, since that prevents it from being AJAX in the first place, because the A stands for asynchron.
Change the third parameter of the xmlhttp.open call to true (or just leave it out, since that is the default).
i have a trouble with my project.
In my site i have a page html with a single button and at onclick() eventa js function call intro.js, trough a XmlHttpRequestObject have to do many calls at many php function, in detail:
in js i call scan() function
function scan() {
if (xmlHttp)
{
// try to connect to the server
try
{
// initiate reading the async.txt file from the server
xmlHttp.open("GET", "php/intro.php?P1=http://"+oStxt.value, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
// change cursor to "busy" hourglass icon
document.body.style.cursor = "wait";
}
// display the error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
And in handleRequestStatuschange i have:
function handleRequestStateChange()
{
// obtain a reference to the <div> element on the page
// display the status of the request
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
// read response only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
try
{
// read the message from the server
response = xmlHttp.responseText;
// display the message
document.body.appendChild(oRtag);
oPch = document.getElementById("divRtag");
oOch = document.createTextNode(response);
oPch.appendChild(oOch);
}
catch(e)
{
// display error message
alert("Error reading the response: " + e.toString());
}
}
else
{
// display status message
alert("There was a problem retrieving the data:\n" +
xmlHttp.statusText);
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
It works for just one php call, but i need to call different php page in scan function after intro.php (scan2.php, scan3.php, ecc ecc) and with json_decode write single data of the array that return in div tags on my html page.
Which is the best way to call different php pages and manage the results with a single js function in ajax?
Thanks in advance
Alessandro
Not sure how you built your php-functions. Cant you create a function, that calls other functions (scans)?
function doScan(){
$data = array();
//like this, or with a loop
$data['scan1'] = scan1();
....
$data['scanN'] = scanN();
echo json_encode($data);
}
Really, the simplest method that comes to mind is just to parameterise this function. This is as simple as
function doScan(url) { // Code here }
Then simply make the exact same ajax request with the url variable.
xmlHttp.open("GET", "php/" + url + "?P1=http://"+oStxt.value, true);
Next, simply call the doScan function with various parameters.
doScan("index.php");
doScan("otherPage.php");
doScan("somethingElse.php");
This will make ajax requests on the PHP file that you specify.