How to make php/ajax req into OOP - javascript

Currently, when a div is clicked, jQuery detects it sends request to fetch data from mysql via Ajax.
What I'm actually fetching is, sub categories for the item clicked and display them in html page.
Now all is done in procedural way, so when another sub level needed to be displayed, I have to copy paste the ajax function. But how do make it into objects so that I don't have to repeat myself?
I just need to know how to bring in OOP into this context..Any help will be greatly appreciated. Thank you.
HTML
<!--append the default top level items starts-->
<div id="default"></div>
<!--append the default top level items ends-->
<hr>
<!--append the default top level items starts-->
<div id="sub"></div>
<!--append the default top level items ends-->
Jquery/AJax
<!--select top level items and append to default id starts-->
$("#clickme").on("click",function()
{
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var data = JSON.parse(this.responseText);
//console.log(this.responseText);
//console.log(JSON.parse(this.responseText));
for (i = 0; i < data.length; i++)
{
var id=data[i].id;
var name=data[i].item_name;
/*check if sub item exist*/
checkSubExist(id);
/*append to div*/
$("#default").append("name= "+name+", ");
}
}
}
}
xmlhttp.open("GET", "selectTopLevel.php");
xmlhttp.send();
});
<!--select top level items and append to default id ends-->
function checkSubExist(param)
{
//alert(param);
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var data = JSON.parse(this.responseText);
//console.log(this.responseText);
//console.log(JSON.parse(this.responseText));
for (i = 0; i < data.length; i++)
{
var id=data[i].id;
var name=data[i].item_name;
//alert(name);
$("#sub").append(name+", ");
}
}
}
}
xmlhttp.open("GET", "checkSubExist.php?sub="+param);
xmlhttp.send();
}

I would use $.ajax to wrap the xmlHttpRequest.
If you want a more "OOP" like approach, I would suggest you define some kind of Request Wrapper Objects which you then create upon event binding, naive example:
var RequestWrapperProto = {
getSubnodes: function(){
//handle request
}
//etc
}
var requestWrapper = Object.create(RequestWrapperProto)
$('.sub').on('click', requestWrapper.getSubNodes);

Related

xmlHttpRequest issue

I am using Js xmlHttpRequest to display the same menu on different pages of my site. Lately I found out that some functions are not executed when the site is online, like a quiz I made.
I had also tried to use fetch, or put the scripts in different files, but the same thing kept happening.
(The quiz does work when checking locally, where the xml request cannot be satisfied.)
//load the menu
onload = function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByTagName('body')[0].innerHTML +=
this.responseText;
}
};
xhttp.open("GET", "mnu.html", true);
xhttp.send();
}
//check the quiz
const checkBtn = document.getElementById('checkBtn')
checkBtn.onclick = function quizCheck() {
//right answers
var score = 0;
if (q1a1.checked) {
score = score + 1;
}
if (q2a1.checked) {
score = score + 1;
}
alert("your score: " + score);
}
<li>
Check the right answer:
<br>
<input type="checkbox" id="q1a1">Right
<br>
<input type="checkbox">Wrong
</li>
<li>
Check the right answer:
<br>
<input type="checkbox" id="q2a1">Right
<br>
<input type="checkbox">Wrong
</li>
<button id="checkBtn">Check</button>
Anybody knows why and/or has some solutions?
The problem is this line which is wrong and that's why js is not working.
document.getElementsByTagName('body')[0].innerHTML += this.responseText;
You can't just add to innerHtml like that.
Instead you should create an html element and add it to body like this:
if (this.readyState == 4 && this.status == 200) {
var p = document.createElement("p");
p.innerText = this.responseText;
document.body.appendChild(p);
}
edit: of course you want to add an html menu instead of just a text inside a <p>, so you will have to add it like this:
var nav = document.createElement('nav');
nav.innerHTML = this.responseText;
document.body.prepend(nav); // always at the top

How to compare JSON data from the same API request?

I'm still learning a lot about web development and javascript, so forgive me if my explanations are not clear.
I have a function to request from an API informations about cryptocurrency (Price, volume etc.) in a JSON file and then i display the price on the web page every 15 seconds.
I want to change the background color of the card where the price is displayed by comparing the actual price and the new one coming from the next request.
here's my javascript :
function requestPrice(url, domLocation){
var req = new XMLHttpRequest();
req.open("GET", url);
req.addEventListener("load", function() {
if (req.status >= 200 && req.status < 400) {
var data = JSON.parse(req.responseText)
domLocation.innerHTML = data.ticker.price + "$";
erreur.innerHTML = "";
} else {
erreur.innerHTML = "Erreur: " + req.status + " " + req.statusText;
}
});
req.addEventListener("error", function () {
erreur.innerHTML = "Erreur";
});
req.send(null);
}
var btcPrice = document.getElementById('boxBTC'), erreur =
document.getElementById('erreur');
setInterval(requestPrice("https://api.cryptonator.com/api/ticker/btc-eur",
btcPrice), 15000);
I was thinking of a simple comparaison between the values and put this code in my loop but i need to stock the actual price somewhere to do the comparison with the new one coming and i'm stuck with that.
if (valueOf(data.ticker.price) <= valueOf(data.ticker.price)){
document.getElementById('overviewcard').style.backgroundColor = red;
} else {
document.getElementById('overviewcard').style.backgroundColor = blue;
}
Or
var overviewcard = getElementById('overviewcard');
if (data.ticker.price <= data.ticker.price){
overviewcard.style.backgroundColor = red;
} else {
overviewcard.style.backgroundColor = blue;
}
here's the html :
<div class="overviewcard">
<span id="boxBTC">...</span>
<span id="erreur"></span>
</div>
Thanks a lot for your help
You can do this in a myriad of ways, but the simplest is to grab the data from the actual HTML DOM element.
var currValue = document.getElementById('boxBTC').innerHTML;
if(valueOf(data.ticker.price) == currValue) {
// do something
}
If you're boxBTC string is formatted too much (eg. if you make "1000" -> "1,000"), then you can always also store a data attribute of the raw value inside the DOM as a data attr.
// assigning the data
document.getElementById('boxBTC').setAttribute('data-val', price);
...
// accessing the data
document.getElementById('boxBTC').getAttribute('data-val');

Getting All Same IDs with Java Script

The java script only get the first id. The 2nd id ignores the code. Are there anyway to make both IDs using the same java script ?
Add Item
List Items
<div id="add_item" class="tabcontent">
<div id="subcatchooser"></div>
<div id="list_item" class="tabcontent">
<div id="subcatchooser"></div>
Java Script here
function showsubcat(str) {
if (str.length == 0) {
document.getElementById("subcatchooser").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("subcatchooser").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "ajax.php?action=showsubcat&parent_id=" + str, true);
xmlhttp.send();
}
}
</script>
That is the main difference between classes and IDs. Classes are designed to be used multiple times, while IDs are designed to be unique. So you can change the divs to look like this:
<div class="subcatchooser"></div>
And then change the JavaScript to look like this:
var elements = document.getElementsByClassName("subcatchooser");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "";
}

Error on AJAX call PHP function with JSON return

I want to develop a News Ticker using three technologies: PHP, Javascript and AJAX.
First, I made a PHP function getFeed() to fetch data from News websites on an Array, then I made a JSON return using this code: echo json_encode($articles, true);
Secondly, I aim to use AJAX and Javascript to make repeated calls to getFeed() function, here is my javascript code:
<script type="text/javasript">
var xmlhttp=false;
function begin() {
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200){
var jsonContent=JSON.parse(this.responseText);
displayT(jsonContent);
}
};
// rssnews.inc.php contain the getFeed() function
xmlhttp.open('GET','rssnews.inc.php', true);
xmlhttp.send();
}
// displayT(content) function display the JSON element
function displayT(content){
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<h4><a href="' + arr[i].link+ '">' +
arr[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}
</script>
On the HTML page, I have the following components a button (id="start") - on click execute begin() function, a div container (id="Ticker") and a div (id="item") for display data with AJAX
<form>
<button type="submit" class="btn btn-default" id="start" onclick="begin();"> START </button>
</form>
<div id= "ticker" style="border: 1px solid #ccc; height: 500px; weight:600px;">
<div id="item">
<!-- I want to display the fetched data by 4 items at a specific time Interval-->
</div>
</div>
When I click on the start button, I don't get the json data.
How can I solve this problem and how can I ensure that this AJAX calls is the most appropriate way to my Ticker.
Thank you!
The error is essentially saying that the file you are trying to GET with you AJAX call, does not exist at the specified location (which is http://localhost/rss/rssnews.inc.php).
You are using a Relative path, which searches for 'rssnews.inc.php' in the same folder. To go up to the parent directory, use ../.
Or use an Absolute path, as in http://localhost/rss/rssnews.inc.php. (Replace with absolute path to your PHP script)
Update
(after HTTP 401 solved)
displayT function is taking content as input, and is then reffering to arr, which is not defined.
Assuming content is actually an array containing your data in the desired format, replace arr with content:
function displayT(content){
var out = "";
var i;
for(i = 0; i < content.length; i++) {
out += '<h4><a href="' + content[i].link+ '">' +
content[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}

getting autosuggest from a url using javascript

i have an auto-suggest url from that i need to write a JavaScript code through which i will be able to see the auto-suggest data.
i tried the below code but i am not able to get through it.
<!DOCTYPE html>
<head>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://***.poc.xxxxx.com/v1/staples/suggest?authKey=baef7f8e39c512342c8a14b7f6018b58&q=wat&rows=8";
var words = []
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var data = JSON.parse(response);
var req_data = data.suggestions[0].suggestion;
console.log(req_data);
//document.getElementById("id01").innerHTML = words;
}
</script>
</head>
<body>
<!-- <div id="id01"></div> -->
</body>
</html>
the thing i am getting in response is:-
{"suggestions":[{"suggestion":"\u200B\u200B\u200B<b>wat</b>er","categories":[{"name":"Water & Juice","filter":"category_id%3A4606"},{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er cooler","categories":[{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"},{"name":"Kitchen Storage & Organization","filter":"category_id%3A1303"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er bottle","categories":[{"name":"Lunch Totes & Water Bottles","filter":"category_id%3A8812"},{"name":"Water & Juice","filter":"category_id%3A4606"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er cups","categories":[{"name":"Disposable Plates & Cups","filter":"category_id%3A992"},{"name":"Disposable Cups","filter":"category_id%3A13302"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er bottle labels","categories":[{"name":"Labels","filter":"category_id%3A997"},{"name":"Mailing & Shipping Labels","filter":"category_id%3A6118"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er dispenser","categories":[{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"},{"name":"All Kitchen","filter":"category_id%3A60479"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>ch","categories":[{"name":"Pedometers & Fitness Trackers","filter":"category_id%3A2554"},{"name":"Smart Watches","filter":"category_id%3A62030"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>ercolor","categories":[{"name":"Abstract Art","filter":"category_id%3A12645"},{"name":"Wall Art/Decor","filter":"category_id%3A26678"}]}]}
from that response i need to find all the product name which coming after suggestion not suggstions like suggestion for wat water cooler etc.
It is hard to discern what exactly you're asking for. If what you want is just a list of all the "name" properties that are returned as suggestions, you could collect those like this:
function myFunction(response) {
var data = JSON.parse(response);
var items = data.suggestions;
var names = [], cat;
// iterate array of suggestions
for (var i = 0; i < items.length; i++) {
cat = items[i].categories;
// iterate array of categories in each suggestion
for (var j = 0; j < cat.length; j++) {
names.push(cat[j].name);
}
}
console.log(names.join(","));
}
Working demo: http://jsfiddle.net/jfriend00/trdppth0/
Now that you've clarified what output you want, you can get the list of suggestion words like this:
function myFunction(response) {
var data = JSON.parse(response);
var items = data.suggestions;
var suggestions = items.map(function(item) {
return item.suggestion;
});
console.log(suggestions.join(","));
}
Working demo: http://jsfiddle.net/jfriend00/bv3yfkwr/

Categories