Getting the data from mySql is easy, but after getting the list of items, I've been trying to get togheter a function to click on any of the list items to send the text up to the value of the input... Heres what I have after a couple of days of trying.
// AJAX Request to cityes database
function buscarCiudades(str) {
var respuestas = document.getElementById('sugerencias');
if (str.length == 0) {
respuestas.innerHTML = "";
respuestas.setAttribute("style", "display:none;border:none;outline:none;");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
respuestas.innerHTML = this.responseText;
respuestas.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");
}
};
xmlhttp.open("GET", "/editor/queries/paises.php?ciudad=" + str, true);
xmlhttp.send();
}
}
// my final effort to achive sending the content to a input field
var items = document.querySelectorAll("#sugerencias li");
for(var i = 0; i < items.length; i++ )
{
items[i].onclick = function(){
document.getElementById('campomx').value = this.innerHTML;
};
}
Hense the two html elements in the dynamic process
<input type="search" class="searchBox" name="ciudad" id="campomx" placeholder="Escribe el nombre del destino" onkeyup="buscarCiudades(this.value)" for="sugerencias">
<ul id="sugerencias" class="sugerencias">
</ul>
And this is the query structure:
$ciudad = htmlentities( $_GET['ciudad'], ENT_COMPAT, 'UTF-8' );
$pq = $dcon
->query( "
SELECT *
FROM ciudades
WHERE ciudad LIKE '%$ciudad%'
ORDER BY ciudad
ASC LIMIT 10" );
while ( $pr = $pq->fetch() )
{
echo $ciudadx = '<li>' . $pr['ciudad'] . ', ' . $pr['estado']. ", " . $pr['pais'] . '</li>';
}
Could it be that the function doesn't fire up because it needs to load a pre-existent list? And if so... HOW????
The issue was that the querySelector was loading before the list got populated.
My solution was to put the querySelector inside the onreadystatechange function after the response itself. like so...
// AJAX Request to cityes database
function buscarCiudades(str) {
var respuestas = document.getElementById('sugerencias');
if (str.length == 0) {
respuestas.innerHTML = "";
respuestas.setAttribute("style", "display:none;border:none;outline:none;");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
respuestas.innerHTML = this.responseText;
respuestas.setAttribute("style","display: block;border-top: 1px solid #272C33;border-radius: 0 0 4px 4px;padding: 10px;");
// newly Included querySelector ------------------
var items = document.querySelectorAll("#sugerencias li");
for(var i = 0; i < items.length; i++ )
{
items[i].onclick = function(){
document.getElementById('campomx').value = this.innerHTML;
};
}
// EO include --------------------------------------
}
};
xmlhttp.open("GET", "/editor/queries/paises.php?ciudad=" + str, true);
xmlhttp.send();
}
}
If this is wrong please feel free to comment.
Related
I have the following Microsoft Dynamics related XMLHttpRequest javascript function, and is encountering issue when attemtping to retrieve the entity attributes of the returned records.
The record managed to be created even though the conditions should have blocked it. It is likely that my following statement caused the issue:
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
function DisableInvalidRecordCreation(context) {
var saveEvent = context.getEventArgs();
var idNumber= Xrm.Page.getAttribute("IDNumber").getValue();
var category= Xrm.Page.getAttribute("Category").getValue();
var id = Xrm.Page.data.entity.getId();
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=1");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if (results.value.length > 0 && id == "") {
alert(results.value.length); //Displayed as 1
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
for (var i = 0; i < results.entities.length; i++) {
var returned_category= results.entities[i]["Category"];
alert(returned_category); //Not displayed
if (category == 100000003 && returned_category!= 100000003)
{
alert("Invalid record");
saveEvent.preventDefault();
}
}
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
This is happening because in your get request you are selecting only IDNumber field and not the one you desire like Category
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
Also it should not be var result1 = results.results[0];
rather it should be var result1 =results.value[0]
sample code snippet for reference
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var abc = results.value[i]["abc"];
var xyz = results.value[i]["xyz"];
var pqr = results.value[i]["pqr"];
var pqr_formatted = results.value[i]["pqr#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
I am adding the comments input box of every XML-RSS article.
When I select a RSS url, that results are commonly as below
PHP code
for ($i=0; $i<=19; $i++) {
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
$item_date=$x->item($i)->getElementsByTagName('pubDate')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "' target=\'_blank\'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "<br>".$item_date."</p>");
$item_link1 = str_replace('http://','',$item_link);
$item_link2 = str_replace('https://','',$item_link1);
$item_link3 = str_replace('/','-',$item_link2);
$item_link4 = str_replace('?','-',$item_link3);
$content = $item_title."--". $item_link."--".$item_desc."--".$item_date;
file_put_contents("./comments/".$item_link4.".txt",$content);
//Next line is something wrong or not??
echo "<option id=".$item_link4." onclick=\"showComment(this.value)\" value=".$item_link4."> Show Comments </option> <div id=\"".$item_link."\"></div>";
Next, I can see the results as a below picture.
And I am coding JS which has the showComment function as below.
function showComment(str) {
if (str.length == 0) {
document.getElementById(""+item_link4+"").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(""+item_link4+"").innerHTML = this.responseText;
}
};
var q = document.getElementById(""+item_link4+"").value;
xmlhttp.open("GET", "showComment.php?q=" + q, true);
xmlhttp.send();
}
}
And Next, I am coding the showComment.php as below to see the 'q' value.
But,
Notice: Undefined index: q in E:\xampp\htdocs\code\v1\showComment.php on line 5.
The first part is like next.
// line 5 is $q = html...
$q = htmlspecialchars($_GET['q']);
global $result;
echo $q;
Eventually, I got something wrong in JS code which received item_link4
How do I change the JS variable originated from php-HTML code?
Please your Kindness.
I have tried so many times. At last I got the good result for going to the better.
PHP code is
echo " <option id=".$i." onclick=\"showComment".$i."(this.value)\" value=".$item_link4."> Show Comments </option>";
And I changed JS code as below.
<script>
function showComment0(str) {
if (str.length == 0) {
document.getElementById("0").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("0").innerHTML = this.responseText;
}
};
var q = document.getElementById("0").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
....
<script>
function showComment22(str) {
if (str.length == 0) {
document.getElementById("22").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("22").innerHTML = this.responseText;
}
};
var q = document.getElementById("22").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
<script>
function showComment23(str) {
if (str.length == 0) {
document.getElementById("23").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("23").innerHTML = this.responseText;
}
};
var q = document.getElementById("23").value;
xmlhttp.open("GET", "showComment.php?q=" +q, true);
xmlhttp.send();
}
}
</script>
So I made Id 0 to 18 script. That is, 19 scripts are necessary.
I am waiting for better answer.
I want to take data from an XML file to display in an html page that is obtained by clicking a button. When the button is clicked, I'd like it to select a random child, and display the sub-child data. I made an XML file that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<kdramas>
<kdrama>
<title lang="en">A Gentleman's Dignity</title>
<genre>Comedy, Romance, Drama</genre>
<year>2012</year>
<episodes>20</episodes>
<about>This drama will tell the story of four men in their forties as they go through love, breakup, success and failure. </about>
</kdrama>
<kdrama>
<title lang="en">Boys Over Flowers</title>
<genre>Comedy, Romance, Drama, School</genre>
<year>2009</year>
<episodes>25</episodes>
<about>about text</about>
</kdrama>
<kdrama>
<title lang="en">Goblin</title>
<genre>Comedy, Romance, Melodrama, Supernatural</genre>
<year>2016</year>
<episodes>16</episodes>
<about>about text</about>
</kdrama>
I am able to display the XML data when the button is clicked, but it shows all of the data (except for the titles). I have looked around to see if it is possible to select a random child then display its sub-child elements, but so far, I am not having any luck finding anything. The JS code I have to display the XML data is:
function getDrama(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML =
this.responseText;
document.getElementById("content").style.display = "block";
}
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}
Any ideas on how to do this? Or even just pointing me to a place where I can read on how to do it myself would be great?
Use JQuery construction $(_your_text_).find('_elenent_name_') for find data:
function getDrama(_callback){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("content").innerHTML = this.responseText;
//document.getElementById("content").style.display = "block";
_callback(this.responseText);
}
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}
function get_random_title(){
getDrama(function(_text){
var titles_length = $(_text).find('kdrama').length;
var random_number = 1 + Math.floor(Math.random() * titles_length);
var random_title = $(_text).find('kdrama').eq(random_number).find('title').text();
$('#content').html( random_title );
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content"></div>
<input type="button" value="Get Random Title" onClick="get_random_title();">
I suggest converting the XML to JSON for easier handling, you can use the function found here https://davidwalsh.name/convert-xml-json
You get the array of kdramas and then select a random element. Just need to format the JSON for printing.
function xmlToJson( xml ) {
// Create the return object
var obj = {};
if ( xml.nodeType == 1 ) { // element
// do attributes
if ( xml.attributes.length > 0 ) {
obj["#attributes"] = {};
for ( var j = 0; j < xml.attributes.length; j++ ) {
var attribute = xml.attributes.item( j );
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if ( xml.nodeType == 3 ) { // text
obj = xml.nodeValue;
}
// do children
if ( xml.hasChildNodes() ) {
for( var i = 0; i < xml.childNodes.length; i++ ) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if ( typeof(obj[nodeName] ) == "undefined" ) {
obj[nodeName] = xmlToJson( item );
} else {
if ( typeof( obj[nodeName].push ) == "undefined" ) {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push( old );
}
obj[nodeName].push( xmlToJson( item ) );
}
}
}
return obj;
}
function getDramaList(callback){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDOM = new DOMParser().parseFromString(this.responseText, 'text/xml');
var jsonXml = xmlToJson(xmlDOM);
callback(jsonXml.kdramas.kdrama);
}
};
xhttp.open("GET", "https://raw.githubusercontent.com/npellow/npellow.github.io/master/kdramaList.xml", true);
xhttp.send();
}
getDramaList(function(dramaList){
var randomIndex = Math.floor(Math.random(0,dramaList.length));
var randomKdrama = dramaList[randomIndex];
document.getElementById("content").innerHTML = JSON.stringify(randomKdrama, null, " ").replace(/\n/g,"<br>");
document.getElementById("content").style.display = "block";
});
<div id="content">
</div>
Please help i have been trying from 1 hours and not able to get whats wrong
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out = arr[i].ID + arr[i].Title + arr[i].Description;
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I am trying to fetch details from http://it-ebooks-api.info/v1/book/2279690981 but it show only empty array being returned. What changes are required ?
Modification
I added [ ] on JSON object and it worked .. Please can someone explain me.
Thank in advance :)
The response does not contain an array, so the for loop is not needed and this should get you the result you are looking for:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var out = "";
var i;
out = "<p>" + response.ID + response.Title + response.Description + "<p>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
If you use the full listing available from http://it-ebooks-api.info/v1/search/php, then you need the for loop to go through the array like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse.Books);
}
}
function myFunction(Books) {
var out = "";
for (var i = 0; i < Books.length; i++) {
out += "<p>ID: " + Books[i].ID + "</p>" + "<p>Title: " + Books[i].Title + "</p>" + "<p>Description: " + Books[i].Description + "</p>"
}
document.getElementById("id01").innerHTML = out;
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
And to make it slightly more elegant, you could have a function that adds the book and if you get only one book you can call it directly from the onreadystatechange, and if you have the full listing, then you can loop it through, but still use the same function. So something like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttpo.responseText);
if (response.Books) { // If the response object has Books array, we pass it to the parseBooks functoin to add them all one by one.
parseBooks(response.Books)
} else {
addBook(response); // If there is no Books array, we assume that there is only one book and add it to the list with addBook function.
}
}
}
function addBook (Book) {
var text = document.getElementById("id01").innerHTML;
var body = "<p>ID: " + Book.ID + "</p><p>Title: " + Book.Title + "</p><p>Description: " + Book.Description + "</p>";
document.getElementById("id01").innerHTML = text + body; // Append the innerHTML with the new Book.
}
function parseBooks(Books) {
for (var i = 0; i < Books.length; i++) {
addBook(Books[i]) // Add all books in the array one by one
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
You JSON feed is just a simple object and not an Array of objects. Note the opening curly braces in the returned feed: {}
You should then change your myFunction function so it goes through an object and not an array just by removing the for loop:
function myFunction(obj) {
var out = "",
id01 = document.getElementById("id01");
out = obj.ID + obj.Title + obj.Description;
id01.innerHTML = id01.innerHTML + out;
}
Edit:
You can use the same function then inside a for loop when you have to parse an Array of Objects.
Taking as a feed the JSON returned from http://it-ebooks-api.info/v1/search/php, you can retrieve the Books value and then loop through it:
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
var url2 = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var rslt = JSON.parse(xmlhttp.responseText);
console.log(rslt);
var books = rslt.Books;
for (var i = 0; i < books.length; i++)
{
myFunction(books[i]);
}
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();
So my problem in the code below is in the following if else if statement at the bottom:
1. the code in both of the if statements work perfect.
2. the issue is that when i run the code on one can be use.
if i do 2 separate if statements only the second one works.
if i do 1 if and one else if only the if statement works and the else if does nothing.
a little more info: what I'm trying to do is every time the function times out and loops through again it will check the if statements and if something changed to run the appropriate if clause.
PLEASE LET ME KNOW IF MORE INFO IS NEEDED.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create object");
else
return xmlHttp;
}
function process_search()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
search_parameter = encodeURIComponent(document.getElementById("userInput").value);
search_type = encodeURIComponent(document.getElementById("userOptions").value);
xmlHttp.open("GET", "../pages/search_xml.php?search_parameter=" + search_parameter + "&search_type=" + search_type, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process_search()',5000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
if(document.getElementsByTagName('find_users')) // FIND USERS
{
first_name = root.getElementsByTagName('first');
last_name = root.getElementsByTagName('last');
users = document.createElement('ul');
users.setAttribute("id", "usersFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< first_name.length; i++)
{
usersList = document.createElement('li');
t = document.createTextNode(first_name.item(i).firstChild.data + " - " + last_name.item(i).firstChild.data + "<br/>");
usersList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(usersList);
}
}else if(document.getElementsByTagName('find_config_item')) //FIND CONFIG ITEMS
{
item = root.getElementsByTagName('item');
desc = root.getElementsByTagName('description');
itemsList = document.createElement('ul');
itemsList.setAttribute("id", "itemsFound");
document.getElementById("underInput").innerHTML = ""; //RESETS THE DIV BEFORE INSERTING DATA
for(var i=0; i< item.length; i++)
{
itemList = document.createElement('li'); // CREATE LIST ITEM ELEMENT
t = document.createTextNode(item.item(i).firstChild.data + " - " + desc.item(i).firstChild.data + "<br/>");
itemList.appendChild(t);
underInput = document.getElementById("underInput");
underInput.appendChild(itemList);
}
}
setTimeout('process_search()', 5000);
}
else
{
alert("something is wrong");
}
}
}
You shouldn't really rely on try/catch for this use case. You can be fairly certain the XMLHttpRequest or a Mircrosoft.XMLHTTP object will exist so you could simplify your code to the following:
function createXmlHttpRequestObject () {
return window.XMLHttpRequest ? new XMLHttpRequest() : new XDomainRequest();
}
var xmlHttp = createXmlHttpRequestObject();
Let me know if you would like to see a non ternary version