ajax.responseText to paragraph - javascript

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.

Related

Concurrent AJAX requests not working. Newest request overwrites previous request

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");
}

how to compare ajax response text with some string without jQuery

I am trying to get a value back through if it found value in database sends/echo result value in it does found sends back/echo 'not_found'.
When I try to compare in the following script it always goes inside if, and never goes to else.
I also tried NULL, FALSE instead not_found does not work.
function showHint(str) {
var xmlhttp;
var url= "check_album.php?q="+str;
document.getElementById("txtHint1").innerHTML=(url);
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) {
if(xmlhttp.readyState.responseText !='not_found') {
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else {
document.getElementById("txtHint3").innerHTML='no result';}
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
and this is check_album.php code which sending result back
require_once('../php/classes/class.add_album.php');
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$album_name = $_GET["q"];
//make new object
$objfile = new add_album();
//call object method with post method value we got and save result in result
$file_found=$objfile->find_album($album_name);
if ($file_found)echo $file_found;
else echo 'not_found';
}
Try this.
if(xmlhttp.responseText !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else
{
document.getElementById("txtHint3").innerHTML='no result';
}
This is because response text may have unwanted spaces Try to trim that response
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
if(xmlhttp.responseText.trim() !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}else{
document.getElementById("txtHint3").innerHTML='no result';
}

HTTP login API authentication by using javascript?

function login1() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
var url = "http://agero-dev.apigee.net/v1/id/auth/login";
var http = getHTTPObject();
if (http.status == 200 ) {
this.http.open("post", url, false, user, pass);
this.http.send("");
document.location = job-list.html;
} else {
alert("Incorrect username and/or password!");
}
return false;
}
function getHTTPObject() {
var xmlhttp = false;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
Please look at the above code, while giving wrong username and password, it showing an alert, but while using correct login, it doesnt redirecting to job-list.html page, please advice?
You can use readyState to check whether response is ready.
http.onreadystatechange=function() {
if (http.status == 200 && http.readyState == 4) {
.... //your code
window.location = job-list.html;
}
}
http.open("post", url + '?user=' + user + '&pass=' + pass, true);
http.send();

How do I create an HTML select box with results from a PHP search through AJAX?

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>

how to read xml file with many nodes with javascript

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);
}

Categories

Resources