Ajax request to load .php file not working - javascript

Trying to load contents from postcode.php file into a #postcodeList div, but it is not working (nothing happens). I checked postcode.php file it echoes al correct information.
var loadicecream = document.getElementById("iceCreams");
loadicecream.addEventListener("click", iceAjax, false);
function iceAjax() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","ice-cream-list.php",true);
xmlhttp.send();
document.getElementById("ice-cream-list").innerHTML = xmlhttp.responseText;
}

You want the query to execute asynchronously (the third parameter to open function) and then you synchronously try to read the value. This happens before the query has been sent, so it will always be empty.
Either run the load synchronously, or set the xmlhttp.onreadystatechange to point into a function where you handle the loaded state. The best way is to do it asynchronously since you don't want to block the user from using the page while loading data.
Quick example, only handles the success case:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("postcodeList").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","postcode.php",true);
xmlhttp.send();
Read up on the documentation for the onreadystatechange, at least you want to handle the case where there is a timeout or some error, otherwise the user won't know something went wrong.

Related

Cannot traverse inside html object

I'm trying to retrieve page source from the link by http request, and than try to parse it.
Lets assume that I have url;
http://www.biletix.com/search/ISTANBUL/tr#!selectedDate:01/07/16
When I run the following command on the console I get the title as; "Hüsnü Şenlendirici - Taksim Trio"
document.getElementsByClassName("ln1 searchResultEventName")[2].innerText
But the same approach does not work when I try to apply it on the page source that I request.
To get the page source I use;
httpGet("http://www.biletix.com/search/ISTANBUL/tr#!selectedDate:01/07/16",function(result) {
var el = document.createElement('html');
el.innerHTML = result;
//the following code returns undefined
console.log(el.getElementsByClassName("ln1 searchResultEventName")[2].innerText);
});
Why the line console.log(el.getElementsByClassName("ln1 searchResultEventName")[2].innerText); returns undefined? Why I cannot reach as I reach from the console?
httpGet is here;
function httpGet(theUrl, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, true );
xmlhttp.send();
}

AJAX Call from Javascript does not work the first time but works each successive time

I am using an AJAX call within a javascript function to populate a SELECT input. This script does not work the first time but works as I intend it to each subsequent time that it is called. The relevant code follows:
function getXMLHttp()
{
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;
}
}
}
return xmlHttp;
}
function populateEntries(menu, userName, entryRow)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200) && (xmlHttp.responseText == ""))
{
window.alert("There are no records to view!"); }
else if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
{
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "getUsers.php", true)
xmlHttp.send(null);
ADDITIONAL UNRELATED CODE FOLLOWS ....
}
I've checked to see if the "response" is being passed from the AJAX call during the first function call and it is but it is not being passed out of the function for further use in the code that follows except on subsequent function calls. Can anyone tell me why this is happening? Your help will be very much appreciated. Before you tell me that this can be done with jquery, please understand that I need to do it with javascript.

XMLHttpRequest - Hitting serverside aspx method - 505 Internal Server Error

I have coded an AJAX GET request using a XMLHttpRequest object. My problem is that the request is never hitting the server side code. I had a look at many forums and at stackoverflow and I dont really know what I am missing.
My JS code
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "login.aspx/GetData", true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(null);
}
Server side code - login.aspx
[WebMethod]
public static string GetData()
{
return "break here";
}
Looking at the Network tab in developer tools, I see that it cannot find the method as the error code is 505 (Internal Server Error)
Can this work within an aspx page? maybe only wrks in a asmx service?
Is there anything in the code that I have not done or is wrong?
Thanks

AJAX: head and more

For asynchronous quick-checks of an URL, I use AJAX with method=HEAD:
function ajax_quickresponse(url) {
var xmlhttp = null;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlhttp.open("HEAD", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if ((xmlhttp.status > 199 && xmlhttp.status < 400))
; //OK
else
; //ERR
};
};
xmlhttp.send(null);
};
};
This receives is enough for checking the http status, but seems to abort the script at serverside (url). E.g. I can try with a simple php script (url="http://my-host.er/test/script.php") which does sleep(2); and log a success message afterwards.
With xmlhttp.open("HEAD", url, true);, there is no success entry in the log.
With xmlhttp.open("GET", url, true);, there is a success entry in the log.
However, with GET/POST, the javascript is waiting 2 seconds instead of instantly (with HEAD).
The status is known instantly and the javascript does not need to wait for the final response.
How to take advantage of both methods? First, I need the status instantly, as soon as the header comes in, and after the external url/script returns, then i'd like another listener.
E.g. first alert('http status='+xmlhttp.status); and maybe delayed, depending on the url/script, alert('finally completed');
Do you have a tip how to achieve this with one single call?

Unable to consume WCF service by Java Script using XmlHttpRequest

Here is my java script to call WCF service
function CallWcfAjax() {
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:20949/RestService/tiger/pandey";
// Send the HTTP request
xmlHttp.open("GET", url, true);
xmlhttp.send();
// Create result handler
xmlHttp.onreadystatechange = function X() {
if (xmlHttp.readyState == 4) {
alert(xmlHttp.responseText);
}
}
}
if I enter the same URL in browser http://localhost:20949/RestService/tiger/pandey i get a response.
Any idea what wrong I am doing in Java Script?
Thanks
You variable name is xmlhttp and in the rest of you code, you use xmlHttp. This is a problem.

Categories