First off, thanks for taking the time to read.
I'm trying to delve into ASP.NET MVC at the moment, however i currently have no wish to use any type of JavaScript framework, so please, don't tell me how much easier it would be etc, in your answer.
I currently have a Javascript function that successfully makes an AJAX call, however i am struggling to understand why no values are being returned from the request.
The function is as follows.
function ajaxRequestUser(num) {
var ajax;
try {
ajax = new XMLHttpRequest();
} catch(e) {
try {
ajax = new ActiveXObject(Msxml2.XMLHTTP);
} catch(e){
alert('old browser');
}
}
ajax.readystatechange = function () {
if (ajax.readyState == 4) {
var queryResult = ajax.responseText;
if (!queryResult) {
alert('No Information.');
} else {
alert(queryResult);
}
}
}
var requestString = "?user="+num;
ajax.open("GET", "/Users/GetUser" + requestString, true);
ajax.send(null);
}
The function is called via a separate function that simply does some UI modifications to allow for the display of the data.
The alerts are there at this point, because i was not receiving any data back from the call and i was testing to see if that part of the code was being hit at all (Don't go into the differences between Synchronous and Asynchronous.). No matter how long i waited the data being returned was not being returned, after breaking through the actual server side c#, i saw the data being sent back, but it was just never being received. Is there something in the code that was done wrong? Or am i going about receiving the inbound data in the wrong way?
I have found the issue related to my code, and it is solely an error based around the declaration of my ajax.event where the event is onreadystatechange as opposed to readystatechange
Related
Note: I am aware that json/jquery appears to be the preferred way of doing things at the moment. Nevertheless, I am using just plain old ajax without json/jquery.
I have set my website up so that there are no php calls in the index page. Instead, I load scripts which handle most link clicks via ajax calls back to the server. Theoretically, the server returns the response text, and then the javascript on readystatechange function (set to ajax_response()) inserts the response text directly into the div container with id="innercontent".
Here is the code for my main javascript file:
function ajax()
{
try{ var request = new XMLHttpRequest()}
catch(e1){
try{ request = new ActiveXObject("Msxml2.XMLHTTP") }
catch(e2){
try{ request = new ActiveXObject("Microsoft.XMLHTTP") }
catch(e3){ request = false }
}
} return request
}
function ajax_response()
{
if(this.readyState == 4){
if(this.status == 200){
if(this.responseText != null){
document.getElementById('innercontent').innerHTML = this.responseText
} else alert("Ajax error: No data received")
} else alert("Ajax error: " + this.statusText)
}
}
function fetch_document(opcode)
{
params = "opcode=" + opcode
request = new ajax();
request.open("POST", "/site-php/fetch_document.php", true)
// request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = ajax_response()
request.send(params)
}
function fetch_comic(series, page_number)
{
params = "series=" + series + "&page_number=" + page_number
request = new ajax();
request.open("POST", "/site-php/fetch_comic.php", true)
// request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = ajax_response()
request.send(params)
}
There doesn't appear to be any syntax errors in the javascript, so I thought maybe that the problem was on the server side. But no errors are logged in /var/log/error_log.
Here is the code for my php functions:
<?php
require_once "kolodruid.php";
require_once "login.php";
if(isset($_POST['series']) && isset($_POST['page_number'])){
$series = $_POST['series'];
$page_number = $_POST['page_number'];
}
$mysql_db = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_select_db("webcomics");
mysql_close($mysql_db);
$fd = $docroot . "test.html";
$msg = file_get_contents($fd);
echo $msg;
?>
Note that the actual functionality of this function is to fetch webcomic information from a database. In the process of trying to figure out what has gone wrong, however, I ended up simplifying the function to try to see if just a simple echo statement would work.
also:
<?php
require_once "kolodruid.php";
$opcode = $_POST['opcode'];
switch($opcode){
case "ABOUT":
echo file_get_contents("about.html");
break;
default:
echo file_get_contents("whoops.html");
break;
}
?>
When I look at the firefox console network tab, clicking on the links "webcomic" generates green lights all the way. I check to see if the parameters tab has any data, and it does. The response tab, however, doesn't contain anything.
I've checked that all the files are reachable and in places that the server has access to. I also took out the setrequestheader() functions in the javascript, as it seems that was causing a fatal error. I then re-enabld the close connection setrequestheader() to see if maybe I actually still had to set that one manually. It seems that it didn't generate a fatal error, so I didn't comment it back out.
I've checked the php code for syntax errors, and also checked the javascript code for syntax errors. Both come out clean. I've restarted my server several times (it's localhost), and have also restarted my mysql database server out of desperation.
At this point, the whole enterprise had devolved into just making minor edits in the desperate hope that SOMETHING gives a clue as to what is going on. I have changed the asynchronous calls to synchronous calls to see if that maybe was the problem, but to no avail. (Thus, I rechanged them back to asynchronous calls).
I feel like it's something really stupid and/or obvious, but I've been pouring over the code for hours, and am afraid I can't see the forest for the trees by now. Please help!
Thank you for reading this. I'm aware that Javascript questions are pretty common, but I've been reading question and answer sites for hours, too. D:
In case it matters, I'm using Apache version 2.4.6
Thank you for you help!
It turned out to be something mind-blowingly obvious after all. I was calling the function ajax_response() and assigning the value to onreadystatechange. Removing the parenthesis after ajax_response produced the desired behavior.
I've been working with phonegap to build an app and have been using ajax to communicate with the server to get all the necessary data. Some of the pages take a few seconds to load (and I dont display the page until everything is loaded) and I would like a loading screen to appear while the client is communicating with the server and processing all the data.
I had everything working great until I decided to throw the the ajax calls into functions (I'm working with a few team members, so I thought it would be easier for them to use these ajax calls if they were in some nice functions). Now because of the ajax function is asynchronous, the loading screen turns on and off before the requests are finished processing. I would like my function to stop the execution of code (similar to an alert) so that the loading screen will turn off AFTER all the ajax calls are made.
Essentially I want my javascript code to look like this:
loading();
sendRequests();
notLoading();
where loading() displays the loading screen, and notLoading() turns the loading screen off. My sendRequests() function is specific to each page (each page has to send different requests depending on the functionality of the page)
if you guys are wondering what the loading() and notLoading() functions looks like, here you go
// functions to make loading screen appear and disappear
function loading() {
document.getElementById("blackout").style.display = 'block';
}
function notLoading() {
document.getElementById("blackout").style.display = 'none';
}
I looked into a few other posts about it
How to wait for ajax request to complete in javascript when synchronous option is not available?
http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX
Which those two links essentially tell you the same information, that the third parameter in request.open() needs to be set to false... well, I've tried that and it didn't work =/
here is an example of my getRequest() function so everyone can see what I'm trying to do:
// will send a GET request to the parameter url
function getRequest(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
setHeaders(req);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if( (req.status == 200) || (req.status == 0) ) {
if( (typeof req.responseText != "undefined") && (req.responseText != "") ) {
localStorage["request"] = req.responseText;
}
else {
alert("GR: Error talking to the server");
}
}
else {
alert("GR: Error talking to server");
}
}
}
req.send(null);
return parseJSON();
}
If anyone knows how I can fix this, I would be very appreciative!
I ended up just throwing the notLoading() function at all the exit statuses in the sendRequests() function. Kind of a pain, but seems to work now.
I want to make a little web page which calculates stuff, based on various data from another site. Let's say for an online browser game.
I would like to have it take some specific details from the web pages on the game, but I don't even know where to start.
Is this doable with javascript (if not I would like to know with what language it is)? Could anyone give me a general of guideline of how this can be done?
You can use a combination of AJAX and XMLHTTPRequest, but these are subject to the same origin policy.
Of course, it would make it a lot easier if the external site can send back data in JavaScript Object Notation format (JSON) for readability.
There is a similar question asked here for how to obtain the contents of an external site using XMLHTTPRequest here: How to specify an external website for XMLHTTPRequest
There is another similar question on using XMLHTTPRequest and JSON: Cross-domain JSON request?
I have a standard function for using AJAX to get information dynamically. I use PHP as my listener. Your listener would have to be able to accept variables from the URL, like PHP $_GET[].
In the example below, your listener named "source_url.php" would have to check the values received in $_GET[field] and then simply print/echo the result.
JAVASCRIPT:
function get_(url, func)
{
var http;
try { http = new XMLHttpRequest(); } catch (e) { try { http = new ActiveXObject(\"Msxml2.XMLHTTP\"); } catch (e) { try { http = new ActiveXObject(\"Microsoft.XMLHTTP\"); } catch (e) { alert(\"Your browser broke!\"); return false; } } }
http.open(\"GET\", url, true);
http.onreadystatechange = function() { if(http.readyState == 4) { func(http); } }
http.send(null);
}
function get_info(fieldname)
{
get_("source_url.php?field=" + fieldname, showResult)
}
function showResult(h)
{
alert("The result is: " + h.responseText);
}
HTML
<button onClick='get_info("name");'>Get the ship Name</button>
<button onClick='get_info("reg");'>Get the Registration Number</button>
<button onClick='get_info("capt");'>Who is the Captain?</button>
PHP
<?php
if ($_GET[field] == "name") { print "U.S.S. Enterprise"; }
if ($_GET[field] == "reg") { print "NCC - 1701"; }
if ($_GET[field] == "capt") { print "Jean Luc Picard"; }
?>
I use this all the time, though I have created a more advanced version with authentication security. This is where you should start if you are just learning how AJAX works.
I am using the following Ajax function format:
var xmlhttp;
function addAddress(str)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
var addAddress = "add";
xmlhttp.open("POST", "sys.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&addAddress=" + addAddress;
xmlhttp.send(queryString);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (windows.ActiveXObject)
{
return new ActiveXObject("Micorsoft.XMLHTTP");
}
return null;
}
Up until now, all of my Ajax functions, like the one above, have been running fine. However, now the function will work only sometimes. Now, sometimes I will have to click the onclick event a couple times to execute the function or the function will just hang, and then after about 4 minutes it will execute.
I tested parts of the function and found that the issue lies some where at the:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.status);
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
When the function works, I can alert(xmlhttp.status) and get 200. However, when it's not working, the alert box doesn't even trigger. In fact, nothing happens, not even an error.
Could this be a server issue? I am kind of thinking my website got hacked, but I cannot find any issues accept that the Ajax functions are not executing properly.
Lastly, I do not get this problem on my localhost, it's only happening on the live website.
Any help will be greatly appreciated.
Thanks
First just confirm that the addAddress function is actually being called when you click the button or control that should trigger it.
Just a simple alert in the first line like this would work:
function addAddress(str)
{
alert('addAddress has been called!')
....
}
If you don't get the alert, make sure there isn't a javascript error on the page that is preventing the function from running. In firefox you press CTRL+SHIFT+J to see the error console for example.
If that part is working, trying putting the URL for the ajax request directly into your browser and diagnose it that way.
Looks like you are requesting this url with ajax:
sys.php&addAddress= (address goes here)
Check that the page will load directly in your browser. If not, the problem is not the ajax request, but something with the sys.php page itself - which you can then drill down on.
Hope that helps!
This wasn't the answer I was expecting, but I ended up having my web host (GoDaddy) change servers, and that resolved the problem. For almost a year, I was running IIS7 with PHP. Since I had never run into any problems, I just continued using that server. After the Ajax latency issue and not being able to figure out a solution, I figured I would just switch over to Apache. After the change, everything started running smoothly again.
I am thinking maybe there was a software update that I was not notified about. Or, maybe my website was getting hit with a DDoS, which was decreasing the performance of my Ajax requests. Lastly, maybe someone got into IIS and changed a setting. I don't know, all I know is that the minute the server was changed over to Apache was when the website started running normally again.
Thanks for everyone's suggestions.
Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.
I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!
As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:
function doRequest() {
var req_url, req_type, body;
req_url = document.getElementById('server_url').value;
req_type = document.getElementById('request_type').value;
alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
req = new XMLHttpRequest();
req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
req.onreadystatechange=function() {
if (req.readyState == 4) {
alert(req.status);
}
}
req.send(null);
}
When I run this on FF, I get a
Access to restricted URI denied" code: "1012
error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.
Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.
For security reasons, you cannot use AJAX to request a file from a different domain.
Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.
Instead, you can write server-side code on your domain to send you the file.