Using JSON to parse xmlhttp.responseText for populating textboxes - javascript

How can JSON be used to parse xmlhttp.responseText? I can't seem to get textboxes populated using the parsed data. I tried using .value and .innerHTML with the dot notation with b.first and b.second used with json_encode from the loadTextBox.php file (see below), but the textboxes won't populate.
Main page code:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
//code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var doc = window.document.createElement("doc");
var a = xmlhttp.responseText;
var b = JSON.parse(a);
document.getElementById("textbox").innerHTML=b.first;
document.getElementById("textbox2").innerHTML=b.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
loadTextBox.php code:
<?php
---Placeholder for correct DB login info---
$result = $mysql->query("SELECT column_one FROM table_one");
while ($row = $result->fetch_object())
{
$queryResult[] = $row->present_tense;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[2];
echo json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2));
?>

This is fully tested and works. Use as a starting point to accomplish what you are trying to do:
var url = "YOUR.php"
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.send(null);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && (ajax.status == 200)) {
console.log("ready")
var Data = JSON.parse(ajax.responseText);
console.log(Data);
console.log(Data.first);
} else {
console.log("not ready yet")
}
}
This assumes your JSON output is properly formatted as you stated:
{"first":"radim","second":"radi"}

I have figured out the underlying problem. Extra tags were being sent because I had unnecessary tags in my DB info file. Those tags were being sent in the responseText with {"first":"radim","second":"radi"}. So the code pertaining to ---Placeholder for correct DB login info--- was wrong. I also changed .innerHTML to .value and now it works as intended.
Main page code updated:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("textbox").value=a.first;
document.getElementById("textbox2").value=a.second;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}

Related

How will I show the data from my database when I view the page based on what is selected in my combo box?

When I view my sample.php page, I only see my combo box, and when I start to select a value from my combo box, that's when my data from database show which is from my getyear.php.
What I want to do is the moment I view that page with the default value which is, for instance, 2014-2016, I can already see the data from my getyear.php
This is what I have in my javascript:
/* event handler ~ no ajax function shown */
function showofficers(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
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("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getyear.php?q="+str,true);
xmlhttp.send();
}
$(document).ready(function(){
var year = document.getElementById("year").value;
if (year =="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
mlhttp.open("GET","get_year.php?q="+year,true);
xmlhttp.send();
});
My div is:
<div id="txtHint"></div>
Just continue with:
if (year =="") {
document.getElementById("txtHint").innerHTML="";
return;
} else {
showofficers(year);
};
and make sure the function showofficers is in context.

AJAX - PHP to Javascript Multi Array and Split

New to JSON/AJAX here but trying...
PHP page appears to be returning [{"id":"1"},{"id":2}] to my javascript.
How would I convert it to something useful like a dropdown in html?
Code:
<script>
function show(str) {
if (str=="") {
var ajaxDisplay=xmlhttp.responseText;
var res=ajaxDisplay.split("#");
document.getElementById("ajax1").innerHTML=res[1];
return;
}
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) {
var ajaxDisplay=xmlhttp.responseText;
var res=ajaxDisplay.split("#");
document.getElementById("ajax1").innerHTML=res[0];
}
}
xmlhttp.open("GET","get.php?q="+str,true);
xmlhttp.send();
}
</script>
<div id='ajax1'><b>ID dropdown will be listed here.</b></div>
I am not sure why you declared the variables twice, but I think this may help If you are asking what I think.
function showUser(fo,to)
{
if (fo=="")
{
document.getElementById("show").innerHTML="";
return;
}
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)
{
var arr=xmlhttp.responseText.split(":||:");//I used this as the delimiter
document.getElementById('show').innerHTML=arr[0];
document.getElementById('show1').innerHTML=arr[1];
}
}
xmlhttp.open("GET","some.php?q="+ fo + "&w=" + to,true);
xmlhttp.send();
}
And the php side is different than normal, you;ll need something like this.
if (!$result=mysqli_query($con,$sql))
{
die('Could not get data: ' . mysqli_error($sql));
}
$test=mysqli_fetch_all($result,MYSQLI_ASSOC);//this was key to fetching the array properly for display
$length=count($test);
$half_length=$length/2;
//echo $half_length."<br />";/used for testing
$test12=array_chunk( $test,$half_length+.5,false);//here use true to preserve keys, worked both ways for me
$test5=$test12[0];
$test6=$test12[1];
while(list($key,$val)=each($test5))
{
echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want and will list your array in the format you want
}
echo ":||:";//Make sure the delimiter is out of the loop
while(list($key2,$val2)=each($test6) )
{
echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want
//echo "result_count_".count($test)."_-st<br/>";//used for testing
Took me a while to get this, I hope it helps.

Ajax call to get Data

Dear I want to get Variable Value form PHP Value, and I want to write an ajax call in Java Script, tags,
How it is possible,
I want to get Value from get_result.php file,
and I have following code in get_result.php:
<?php
echo $val="abc";
?>
and I wrote follwing code in another file named ajax.php:
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url="<?php echo "get_result.php"; ?>";
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
var ok xmlhttp.responseText;
alert(ok);
</script>
is there any bug and Where?
I want to get value from get_result.php file and show this value in an Alert;
You can use jQuery. but for your code, you didn't assign the response
<script>
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url="get_result.php";
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
var ok = xmlhttp.responseText;
alert(ok);
The below code will help you in returning the value from the php page
<script>
function myfun()
{
var xmlhttp;
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)
{
var demo=xmlhttp.responseText;
alert(demo);
}
}
xmlhttp.open("GET","result.php",true);
xmlhttp.send();
}
</script>
body
<body>
<input type="button" onclick="myfun();"/>
</body>

multiple ajax calls using only javascript

isn't it possible to execute multiple ajax calls using javascript only and without using Jquery. I tried the below javascript code with two ajax calls but the code is not working when I place the second ajax call
<script type="text/javascript">
var class1;
var class2;
var sec1;
var sec2;
function func()
{
class1 = document.getElementById('selcla');
class2 = class1.options[class1.selectedIndex].value;
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("secdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsec.php?q="+class2,true);
xmlhttp.send();
}
function funcsec()
{
sec1 = document.getElementById('selsec');
sec2 = sec1.options[sec1.selectedIndex].value;
alert("selecting class and section details " + class2 + " " + sec2 );
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)
{
alert("successfully received " );
document.getElementById("studiv").innerHTML=xmlhttp.responseText;
}
else
alert("unsuccessful ajax second call ");
}
xmlhttp.open("GET","getstu.php?x="+class2"&y="+sec2,true);
xmlhttp.send();
}
It is, but you need a different "xmlhttp" handler for each request you make.
Setup a new xmlhttp object and make a second request with the new object.
My suggestion is to break out the part with you initializing the xmlhttp object, into a standalone function, and use it to create a few instances of those objects.
However I must advise against such an approach. It is better to use a library for ajax requests.

Dynamically populate dynamically created select list

I'm having a bit of difficulty here; I am using js to dynamically create select boxes, but I need Ajax to fill them with options. So far, my code is returning undefined, and I frankly don't know what to do here. My php returns the info fine, but the js isn't parsing it. Another set of eyes, or another brain full of knowledge would be appreciated here;
function getSkilllist(group) {
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) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
xmlhttp.send();
}
function addInput(divName,group) {
var skillst = getSkilllist(group);
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="ski[]">' + skillst + '</select> .....
The rest of the function is fine, but the var skillst is returning undefined as stated, and I can't figure out why. I assume it has something to do with strings, but I can't figure out what needs to be done.
Your function does not return anything, which is why it isn't working. Try this:
function getSkilllist(group) {
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) {
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="ski[]">' + xmlhttp.responseText + '</select> .....
//place in DOM here
}
}
xmlhttp.open("GET","skl_lst_gen2.php?group=" + group + "&t=" + Math.random(),true);
xmlhttp.send();
}
function addInput(divName,group) {
getSkilllist(group);

Categories