AJAX Function Requires Double Click? - javascript

I have to click twice for the activation/deactivation of a user for some reason. Obviously I dont want that, it should be enough with one click. What am I doing wrong here?
(I am guessing that it's something wrong with the AJAX call)
C#:
var toggleUrl = "AdminListUsers.aspx?column=" + (IsClicked.FirstOrDefault().Key ?? "Name") + "&direc=" + (IsClicked.FirstOrDefault().Value) + "&a=chstat&q=" + id.ToString() + "&d=" + disabled + "&z=" + Server.UrlEncode(txtSearchFor.Text);
var hl = new HyperLink();
hl.Text = status;
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = toggleUrl;
hl.Attributes.Add("onclick", "loadDoc();return true;"); //Calling the function here
cell.Controls.Add(hl);
tr.Cells.Add(cell);
cell = new TableCell();
cell.Width = new Unit("10%");
cell.Controls.Add(new LiteralControl("<nobr>"));
var linkbtn = new HyperLink
{
NavigateUrl = toggleUrl,
Width = 16,
Height = 16,
CssClass = disabled ? "user-status-disabled" : "user-status-enabled"
};
linkbtn.Attributes.Add("id", "aButton_" + id);
linkbtn.Attributes.Add("onclick", "loadDoc();return true;"); //Calling the function here
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl(" "));
JavaScript:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
window.scrollTo(window.pageXOffset, window.pageYOffset);
window.location.reload();
}
};
xhttp.open("GET", "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+", true);
xhttp.send();
$('.TellusAlternatingRowColor').load(document.URL + ' .TellusAlternatingRowColor');
}
Image for DataRows

The object you're using to contact the server, the XMLHttpRequest is part of the Ajax concept. Ajax stands for Asynchronous JavaScript and XML. This means that as soon as the request from the URL passed resolves, the event tied to onreadystatechange will be fired. Should the readyState and status be appropriate, your window calls will be resolved, too.
Being asynchronous, the whole browser won't stop because the server hasn't responded yet, the whole program will continue. You can still press the button because of this, but nothing will happen until that request is responded to. Clicking it again is sending another request to your server, which I'm assuming is also resolved, but your calls on window have happened by this point.

Related

POST with Javascript AJAX

I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:
function newoption()
{
var option = "";
while((option.length < 1)||(option.length > 150))
{
var option = prompt("Please enter the option value... ").trim();
}
var add = confirm("You entered " + option + ", are you sure?");
if(add==1)
{
var code = window.location.href.length;
var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{this.responsetext = option;}};
xhttp.open("POST", "../special/new.php", true);
xhttp.send("poll=" + poll + "&opt=" + option);
}
else
{
alert("OK... try again");
}
}
The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?
The code for new.php is:
<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
new_poll_option($connection, $poll, $option);
}
?>
From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.
You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome).
If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.
You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.

Display loader while waiting for Ajax response, then fade out the loader and fade in the response no jQuery

I am using a regular XMLHttpRequest and I want to display a loading element while waiting for the response and then display the response with an animation.
I was able to do this with jQuery, but I have found no answers for vanilla JS.
Here is the relevant code.
<div id="loader"></div>
<div id="demo" class="animate-bottom">
ooo
</div>
<button type="button" onclick="loadDoc()">Get the AJAX data</button>
The Css is not necessary, the loader is set to opacity 0.3(to see what is happening) and the
The JS
var output = ''; // the variable to hold the parsed response
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// so far ok, the trouble starts here, setting the loader to opacity 1
document.getElementById("loader").style.opacity = 1;
var theResponse = this.responseText;
var parsedResponse = JSON.parse(theResponse);
// the looping through the data
for (i=0; i < parsedResponse.length; i++ ) {
output += '<li>' + parsedResponse[i].title +'</li>' + '<img src=' +
parsedResponse[i].thumbnailUrl + '/>' + '<span>' + parsedResponse[i].url
+ '</span>';
};
// here the response goes to the demo div.
document.getElementById("demo").innerHTML = output;
}
// these 2 lines do not work as desired
document.getElementById("loader").style.display = "none";
document.getElementById("demo").style.display = "block";
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/photos", true);
xhttp.send();
}
I know, this is an asynchronous request and the problem lies there.
What is happening now, the demo div is animated to the screen as soon the button is clicked and the loader is not displayed while the data is parsed.
I am using a large data set , the request and parsing take few seconds.
Is there a way to make this work, or do I have to wrap some of the code into a setTimeout?
The codepen is here, I apologize for the time it takes to load the data(5seconds for me).
https://codepen.io/damPop/pen/gQOVEe?editors=0010

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

xhr response: connection closed

I wrote a Flickr search engine that makes a call to either a public feed or a FlickrApi depending on a selected drop down box.
examples of the JSONP function calls that are returned:
a) jsonFlickrApi({"photos":{"page":1, "pages":201, "perpage":100, "total":"20042", "photo":[{"id":"5101738723"...
b) jsonFlickrFeed({ "title": "Recent Uploads tagged red","link": "http://www.flickr.com/photos/tags/red/","description": "", ....
the strange thing is that in my local install (xampp) both work fine and i get images back BUT when i host the exact same code on the above domain then the jsonFlickrApi doesn't work. What i notice (by looking at Firebug) is that for the jsonFlickrApi the response Header says Connection close
Also, Firebug doesn't show me a Response tab when i submit a request to the jsonFlickrApi
here is the code:
function makeCall(uri)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "jsonget.php?url="+uri, true);
xmlhttp.send();
}
function jsonFlickrApi(response)
{
var data= response.photos.photo ;
var output = "";
output += "<img src=http://farm" + data[4].farm + ".static.flickr.com/" + data[1].server + "/" + data[4].id + "_" + data[4].secret + ".jpg>";
document.getElementById("cell-0").innerHTML = output ;
}
//Public Feed
function jsonFlickrFeed(response)
{
var data= response.items[0].media.m ;
alert(data);
var output = "";
output += "<img src=" + data+ ">";
document.getElementById("cell-0").innerHTML = output ;
}
function callback()
{
//console.log("Ready State: " + xmlhttp.readyState + "\nStatus" + xmlhttp.status);
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonResponse = xmlhttp.responseText;
jsonResponse = eval(jsonResponse);
}
}
examples of calls:
a)
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
b)
http://api.flickr.com/services/feeds/photos_public.gne?tags=red&format=json&timestamp=1339190039407
Question: why does my connection close? why is it working on localhost and not on the actual domain?
Looking at the HTTP response headers of
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
I get a 302 with location
http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
So, what flicker wants to tell you is "use www.flicker.com instead of flicker.com!". With this URL I get content.

bottle.py: sending data via javascript

Basically, I want to have an interactive button on my website, that, when clicked, sends some data to the server in order to be checked and display the response (without form sending / page reload).
I thought it would be something like:
function checkData()
{
var req = new XMLHttpRequest();
var conf = document.getElementById('my_text_area').value;
req.open("GET", 'check_data', true);
req.onreadystatechange = function ()
{
var pre = document.getElementById('check_data_out');
pre.innerHTML = req.responseText;
}
req.send(conf);
return false;
}
And on the server side:
#get('/check_data')
def check_data():
# Process the content and answer something...
content = str(request.is_ajax) + ' - ' + str(request.GET) + ' - ' + str(request.POST)
return content
But this obviously doesn't work. Either it is not the right way to send data via javascript or not the right way to access it in bottle.py.
Showing me how it works is highly appreciated.
You can use dojo for client side logic.
var button = dojo.byId('button_id'); // button_id refers to the id of the button you want to click
dojo.connect(button,'onclick',dojo.xhrGet({
url: '/check_data',
handleAs : 'text',
load : function(response){
dojo.byId('button_id').innerHTML = response;
}
}));

Categories

Resources