My webpage features a table where each row has a "+" button so that a mini table appears. The mini table houses data from a super slow database so I am having the data come in through ajax requests. My problem is rooted in a certain situation. Suppose you pressed a plus button causing an AJAX request and while waiting you press another plus button. The second ajax request causes the first request to never come back. In other words the newest request overwrites all previous pending requests. Any idea why this might be happening? I feel like this might just be what happens when you don't use jQuery to handle AJAX but I am not sure and I couldn't find anything that said that was the case. I am appending my code below. Any help is appreciated!
function fetchSINamesForVariantAJAX(latestBuild, variantToExpand){
if (latestBuild == "") {
//document.getElementById(subTableId).innerHTML = "";
return;
}
else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
spinner.stop();
var variantRow = variantToExpand + "Row";
if (document.getElementById(variantRow).rows.length == 1){
var json = JSON.parse(xmlhttp.responseText);
var SINames = json['SIs'];
var locations = json['locations'];
var SIBuilds = json['SIBuilds'];
for (var i = 0; i < SINames.length ; i++){
var row = document.getElementById(variantRow).insertRow(-1);
var cell = row.insertCell(-1);
var SILinkURL = "exampleWebsite.com/name.php?names=" + SINames[i];
cell.innerHTML = "" + SINames[i] + "";
cell = row.insertCell(-1);
var fullLocation = locations[i] + "\\" + SIBuilds[i];
cell.innerHTML = "" + fullLocation + "";
cell = row.insertCell(-1);
cell.innerHTML = "";
}
}
}
}
//create the GET message to be sent using AJAX window
var stateToSend = "SITableGeneratorFromVariant.php?";
stateToSend += "latestBuild=" + latestBuild;
xmlhttp.open("GET", stateToSend, true);
xmlhttp.send();
}
}
I think the reason is that you overwrite your xmlhttp variable with a new one each time a new AJAX call gets done try declaring it inside the function:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Related
I have a search form where when someone enters the salary(which is unique in my case), it returns the corresponding values from the database. I am using ajax to do that, i have managed to retrieve the value in input fields. I have an onchange event on my input text which calls in "UpdateCityState"
I would like to show the values inside paragraphs and not input field.
<p id='employee_name'></p>
<p id='employee_age'></p>
<p id='safe_code'></p>
<script>
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var employee_salary = document.getElementById("employee_salary").value;
if(employee_salary)
{
var param = "?employee_salary=" + employee_salary;
var url = "test04.php";
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
var employee_name = document.getElementById('employee_name');
var employee_age = document.getElementById('employee_age');
var safe_code = document.getElementById('safe_code');
if(!!ajax.responseText) {
var result = JSON.parse(ajax.responseText);
if(!!result){
employee_name.value = (!!result.employee_name) ? result.employee_name : '';
employee_age.value = (!!result.employee_age) ? result.employee_age : '';
safe_code.value = (!!result.safe_code) ? result.safe_code : '';
}
}
}
}
I tried replacing employee_name.value with employee_name.text but no luck
If you replace value with innerHTML everything should work.
I have a Sharepoint 2013 site set up. I added a web part to the home page that makes an ajax call to an outside API, and returns JSON data, showing an image and a link. When you visit the site in Chrome, it works perfectly, however in Internet Explorer (11), it doesn't work. The odd part is I know that it is running the JS, because it is showing the "No Current News" p tag from the second line. This is my code:
<h1 style="text-align: center">PQA In The News</h1>
<div id="myNewsFeed"><p>No Current News</p></div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script><script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script><script type="text/javascript">
$(document).ready(function() {
document.getElementById("myNewsFeed").innerHTML = "<p>No Current News</p>";
var d = new Date();
var n = d.getTime();
var mo = 86400000 * 30;
n = n - mo;
var queryString = "https://webhose.io/search?token=xxxx&format=json&q=Company%20Name&ts=" + n;
loadJSON(queryString);
function loadJSON(newsURI){
var data_file = newsURI;
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 ){
var jsonObj = JSON.parse(http_request.responseText);
DisplayData(jsonObj);
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
function DisplayData(data) {
var htmlSource = "<ul>";
for(var i=0; i < data.posts.length; i++) {
htmlSource += "<li><img src=\"" + data.posts[i].thread.main_image + "\" height=\"150px\" width=\"150px\">" + data.posts[i].title + "</li>";
}
htmlSource += "</ul>"
document.getElementById("myNewsFeed").innerHTML = htmlSource;
}
});</script>
I changed the Query String, because it has my company's key, but I can assure you it works. On Chrome, this shows everything fine, but in IE it just shows "No Current News".
Did I do anything wrong, or does Internet Explorer have something against Ajax?
As suggested by Kalamarico best way is to use jquery ajax call and also add fail handler to check exact error. In the above code your javascript call is working but it might not be going to ready state 4 and hence not setting the value. Can you check for other states and also should not be the http request call inside readystatechange event inside else otherwise after hitting ready state 4 also it will fire again.
Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.
Here is some background: I have a text file that is broken down into context blocks. Each block has a header of a pattern "[header]". So far, I have been able to create a php script that will search for these headers and generate a list of only the headers.
What I have not yet been able to figure out is how to supply these results to a web page that will take this list and generate a drop-down/select box with the list as options. Here is the php script:
<?php
$theList = array();
$theInFile = 'extensions.conf';
$theLine = '';
$theReturnString = '';
$inFile=fopen($theInFile, 'r') or exit('Unable to open file.');
while(!feof($inFile))
{ $theLine = fgets($inFile);
$theLine = (string)$theLine;
// Is it a context header?
// Check for the presence of a '[', then the position of '['
// This method is used due to STRPOS returning ZERO if not found,
// which is the position we are looking for.
$x = strstr($theLine, '[');
if ($x != '')
{ $y = strpos($theLine, '[');
if ($y == 0)
{ // Only the context name itself is wanted.
// If there is anything after the ']', strip it.
$end = strlen($theLine);
$tBracket = strpos($theLine, ']') + 1;
if($end != $tBracket)
$theLine = substr($theLine, 0, $tBracket);
$theReturnString = $theReturnString.$theLine.'~';
}
}
}
fclose($inFile);
echo $theReturnString;
?>
The following HTML page is as far as I have gotten. It will at least get the return string separated into a list of headers, but I am at a loss as to how to get that list into a select / drop-down box:
<!DOCTYPE html>
<html>
<form id="StartingPage" action="GetList.php" method="post">
</form>
<head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var received;
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange=function()
{ var newString = new Array();
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ received = document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
received = received.split('~');
for ( i = 0; i < received.length; i++ )
document.writeln(received[i] + '<br>');
document.writeln('Done.<br>');
}
}
xmlhttp.open("GET","GetList.php",true);
xmlhttp.send();
}
</script>
And and all advice and critiques are appreciated.
First, I think it would be better if you parse your file with regular expressions for performance reasons.
Then, prefer JSON for the response, it will be easier for you to read it with Javascript. JSON is also a good choice because it allows you to easily change your script (adding items) without requiring to change the way to parse the responses from Ajax requests.
Following regex will search for contents between "[" and "]".
<?php
$content = file_get_contents('extensions.conf');
preg_match_all('~\[(.+)\]~Usmx', $content, $headers, PREG_PATTERN_ORDER);
echo json_encode($headers[1]);
Now, for the client side, we parse response with JSON.parse() method and put it into select box by creating option elements with document.createElement.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form id="StartingPage" action="GetList.php" method="post">
<select name="mySelectName" id="mySelectId"></select>
</form>
<script>
function loadXMLDoc()
{
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var mySelect = document.getElementById('mySelectId');
var headers = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < headers.length; i++) {
var option = document.createElement('option');
option.setAttribute('value', i);
option.innerHTML = headers[i];
mySelect.appendChild(option);
}
}
}
xmlhttp.open("GET", "GetList.php", true);
xmlhttp.send();
}
loadXMLDoc();
</script>
</body>
</html>
Hope it helps !
If I understood the question right, you need to display select with options from that array .. this should work :
<!DOCTYPE html>
<html>
<form id="StartingPage" action="GetList.php" method="post">
</form>
<head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var received;
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange=function()
{ var newString = new Array();
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ received = document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
received = received.split('~');
var select = document.createElement("select");
select.setAttribute("name", "mySelect");
select.setAttribute("id", "mySelect");
var option;
for ( i = 0; i < received.length; i++ )
{
/* create options elements */
option = document.createElement("option");
/* You can change i with received[i] if you need your options with values equal to displayed text */
option.setAttribute("value", i);
option.innerHTML = received[i];
select.appendChild(option);
}
// Append the select to the end of the body tag
document.body.appendChild(select);
// Or You can use something like this also
// document.getElementById("myDiv").appendChild(select);
}
}
xmlhttp.open("GET","GetList.php",true);
xmlhttp.send();
}
</script>
i have an RegistrationResponseMessages.xml:
<messages>
<error>
<code id="501">Couldn't retrieve the HTML document because of server-configuration problems.</code>
<code id="502">Server busy, site may have moved ,or you lost your dial-up Internet connection.</code>
</error>
<success></success>
</messages>
trying to read contents of code id 501 and 502 with javascript, but it not works.
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("errorCode403").innerHTML = getElementsByTagName(501)[0].childNodes[0].nodeValue);
displaying it here:
<label id="errorCode403" style="font-weight: 600; color: red;">give some error</label>
what is my problem?
It's ajax, you have to wait for the data to be returned, then you have to access it the right way:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onload = function() {
var xmlDoc = this.responseXML,
value = xmlDoc.getElementsByTagName('501')[0].childNodes[0].nodeValue;
document.getElementById("errorCode403").innerHTML = value;
}
xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();
Not sure about the traversal in the XML, as 501 sounds like a strange tagName ?
EDIT:
to get a list of the ID's you do this inside the onload handler:
xmlhttp.onload = function() {
var xmlDoc = this.responseXML,
var codes = xmlDoc.getElementsByTagName('code');
var array = [];
for (var i=0; i<codes.length; i++) {
array.push( codes[i].id );
}
console.log(array);
}